Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .dependency-cruiser-known-violations.json
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@
},
{
"type": "dependency",
"from": "src/http/token-store.test.ts",
"from": "src/auth/token-store.test.ts",
"to": "src/ports/token-secrets.ts",
"unresolvedTo": "../ports/token-secrets.js",
"dependencyTypes": ["local", "type-only", "import"],
Expand Down
7 changes: 7 additions & 0 deletions .dependency-cruiser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,13 @@ export default {
pathNot: "^src/$1/definition\\.ts$",
},
},
{
name: "auth-imports-little",
comment: "src/auth imports only ports and contract",
severity: "error",
from: { path: "^src/auth/", pathNot: linkTestFile },
to: { path: "^src/", pathNot: "^src/(auth|ports|contract)/" },
},
{
name: "modules-imports-little",
comment: "src/modules imports only ports, contract and core, plus the bus for its types",
Expand Down
4 changes: 3 additions & 1 deletion docs/internal/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘
| link | Byte channels over the uplink | [link](../../src/link/AGENTS.md) |
| agent-device | Optional edge: the agent-device daemon beside a worker, its HTTP front | [agent-device](../../src/agent-device/AGENTS.md) |
| stream | Optional edge: a leased device's live screen over HTTP, relayed by a gateway | [stream](../../src/stream/AGENTS.md) |
| http | HTTP frontend: routes, tokens, SSE | [http](../../src/http/AGENTS.md) |
| auth | Credential → identity: tokens, admin secret, `hello`, uplink join token, HTTP strategies | [auth](../../src/auth/AGENTS.md) |
| http | HTTP frontend: routes, SSE | [http](../../src/http/AGENTS.md) |
| cli | Operator command surface | [cli](../../src/cli/AGENTS.md) |
| mcp | stdio MCP server for one agent session | [mcp](../../src/mcp/AGENTS.md) |
| simlock-client, client, admin | The typed programmatic client (`simlock/client`, `simlock/admin`) | [simlock-client](../../src/simlock-client/AGENTS.md) · [client](../../src/client/AGENTS.md) · [admin](../../src/admin/AGENTS.md) |
Expand All @@ -74,6 +75,7 @@ Arrows point from the optional to the required (architecture rule 15).
| `core-not-drivers` | Core and leasing reach a platform only through the `Driver` interface |
| `no-fs-or-process` | Core, leasing, agent-device, host-load and stream use ports, never `fs` or `child_process` |
| `definition-is-light` | A module's definition file imports its own module only for types or by dynamic import |
| `auth-imports-little` | `src/auth` imports only ports and contract |
| `modules-imports-little`, `modules-imports-bus-types-only` | `src/modules` imports only ports, contract and core, and the bus for types |
| `not-modules` | Core, leasing, drivers, gateway and contract import nothing from modules or module-registry |
| `not-agent-device` | Core, leasing and drivers import nothing from agent-device |
Expand Down
6 changes: 3 additions & 3 deletions docs/internal/flows/startup.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Entry: `src/daemon/main.ts` `startDaemon` → `DaemonServer.start` (`src/daemon/
2. `Logger` → `daemon.log`. At `log.level: debug` the `ProcessRunner` is wrapped.
3. Host info read once (`sw_vers` on macOS); bounded, never throws.
4. `EventBus` → the event history is created (`createEventHistory`). It touches no file yet.
`createAuth` then builds the token store and the admin secret (hash in memory), once, for both modes.
5. `config.mode: gateway` → the gateway section. Otherwise go on.

## Worker: build (before the claim)
Expand All @@ -23,8 +24,7 @@ Entry: `src/daemon/main.ts` `startDaemon` → `DaemonServer.start` (`src/daemon/
driver starts its adb server and reattaches running emulators here.
9. Host facts read in the background; host load sampler built.
10. `ComponentInstaller`, `createCore`, the optional-module host (`createModuleHost`; it loads each enabled module's worker half, agent-device's supervisor among them), `createLeasing`,
`core.connect(leasing.corePorts)`, `CleanupReaper`, `Nuke`, `TokenStore`,
`AdminSecretManager` (secret minted, hash in memory), `GatewayUplink` when
`core.connect(leasing.corePorts)`, `CleanupReaper`, `Nuke`, `GatewayUplink` when
`gateway.url` and `gateway.token` are set, `DaemonServer`.

## Worker: claim and converge (`DaemonServer.start`)
Expand Down Expand Up @@ -92,7 +92,7 @@ platform runs the deferred reclaim (step 21.2).
## Gateway

1. Instance identity — `instance.json`.
2. `TokenStore`, `AdminSecretManager`, `FleetLeaseIndex`, routing policy,
2. `FleetLeaseIndex`, routing policy,
`GatewayService` (`workers.json`), `FleetLeaseCoordinator`, `DaemonServer`
with `GatewayDispatcher`. No registry, drivers, reaper or health monitor.
3. `DaemonServer.start`: claim → host load → `admin.token` → converge starts →
Expand Down
2 changes: 1 addition & 1 deletion src/agent-device/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Does: runs one agent-device daemon per worker and serves the agent-device CLI at `/v1/agent-device/*`, one simlock lease per agent-device lease.
Entry: `index.ts` → `agentDeviceModule`. The front parts live in `front/edge-parts.ts` (`createGatewayAgentDeviceFrontParts`, `createAgentDeviceFront`, `disposeAgentDeviceEdge`, `cancelWaitingAllocates`). The gateway half is `gateway.ts` (`createGateway`, builds the `FleetPort` from the gateway context); the worker half is `worker.ts` (`createAgentDeviceEdgeParts`, builds `AgentDeviceSupervisor`). The module host loads both.
Uses: ports, http (session, errors, token identity), contract types, core and leasing types. Never imports: gateway, drivers, `fs`, `child_process`.
Uses: ports, auth (`Identity`), http (session, errors), contract types, core and leasing types. Never imports: gateway, drivers, `fs`, `child_process`.
Imported by: the module registry (`index.ts` only); `daemon/main.ts` imports nothing from it (tests may use `testing.ts`). Pinned in `lint-rules.test.ts`.
Off unless `capabilities.agent-device.enabled` (false). Off: nothing mounted, no daemon.

Expand Down
2 changes: 1 addition & 1 deletion src/agent-device/dispose.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ describe("disposeAgentDeviceEdge", () => {

expect(linkDisposed).toBe(1);
const context = {
map: { get: () => ({ endedAt: undefined, identity: { requesterId: "a" }, ttlMs: 30_000 }) },
map: { get: () => ({ endedAt: undefined, identity: { principal: "a" }, ttlMs: 30_000 }) },
};
renewals.begin(context as never, "lease", "a", 60_000);
expect(clock.pendingTimerCount).toBe(0);
Expand Down
5 changes: 3 additions & 2 deletions src/agent-device/front/allocate.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { describe, expect, it, vi } from "vitest";

import { tokenIdentity } from "../../auth/testing.js";
import type { HttpDispatch } from "../../http/dispatcher-session.js";
import type { TokenIdentity } from "../../http/token-store.js";
import type { Identity } from "../../auth/index.js";
import { FakeClock, NoopLogger } from "../../ports/index.js";
import { allocate } from "./allocate.js";
import type { FrontContext } from "./context.js";
import { FrontMap } from "./front-map.js";

const agent: TokenIdentity = { requesterId: "tok_a", role: "agent" };
const agent: Identity = tokenIdentity("tok_a");
const leaseId = "00000000000000000000000000000001";

interface AdmitSession {
Expand Down
10 changes: 5 additions & 5 deletions src/agent-device/front/allocate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { z } from "zod";
import type { OPERATIONS } from "../../contract/index.js";
import { buildHttpSession } from "../../http/dispatcher-session.js";
import { mapError } from "../../http/errors.js";
import type { TokenIdentity } from "../../http/token-store.js";
import type { Identity } from "../../auth/index.js";
import type { Clock } from "../../ports/index.js";
import {
frontReply,
Expand Down Expand Up @@ -135,7 +135,7 @@ type LeaseOutcome =
// why: a request parked while the daemon starts cannot be called back, so wait on a read that parks at the same gate and give up if the CLI leaves, or a CLI that left would still be admitted.
async function stillWaiting(
context: FrontContext,
identity: TokenIdentity,
identity: Identity,
signal: AbortSignal,
): Promise<boolean> {
if (signal.aborted) return false;
Expand All @@ -156,7 +156,7 @@ function requiresOf(context: FrontContext): { readonly requires?: string[] } {

async function requestLease(
context: FrontContext,
identity: TokenIdentity,
identity: Identity,
plan: Plan,
signal: AbortSignal,
): Promise<LeaseOutcome> {
Expand Down Expand Up @@ -254,13 +254,13 @@ function forwardedBody(

export interface AllocateArguments {
readonly request: Request;
readonly identity: TokenIdentity;
readonly identity: Identity;
readonly call: RpcRead & { readonly kind: "request" };
}

interface Granted {
readonly request: Request;
readonly identity: TokenIdentity;
readonly identity: Identity;
readonly call: RpcRead & { readonly kind: "request" };
readonly plan: Plan;
readonly grant: Grant;
Expand Down
4 changes: 2 additions & 2 deletions src/agent-device/front/context.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";

import type { Logger } from "../../ports/index.js";
import type { TokenIdentity } from "../../http/token-store.js";
import type { Identity } from "../../auth/index.js";
import { exchange, type FrontContext } from "./context.js";

function rig(reply: () => Promise<Response>) {
Expand All @@ -14,7 +14,7 @@ function rig(reply: () => Promise<Response>) {
}

const request = new Request("http://127.0.0.1/rpc", { method: "POST" });
const identity = {} as TokenIdentity;
const identity = {} as Identity;

describe("exchange", () => {
it("a reply that is not JSON-RPC is logged with its status and the start of its body", async () => {
Expand Down
12 changes: 6 additions & 6 deletions src/agent-device/front/context.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { HttpDispatch } from "../../http/dispatcher-session.js";
import type { TokenIdentity } from "../../http/token-store.js";
import type { Identity } from "../../auth/index.js";
import type { Clock, Logger } from "../../ports/index.js";
import { buildHttpSession } from "../../http/dispatcher-session.js";
import { mapError } from "../../http/errors.js";
Expand Down Expand Up @@ -34,7 +34,7 @@ export interface Exchange {
export async function exchange(
context: FrontContext,
request: Request,
identity: TokenIdentity,
identity: Identity,
call?: CallClass,
leaseId?: string,
): Promise<Exchange> {
Expand Down Expand Up @@ -106,7 +106,7 @@ export type SimlockRelease =

export async function releaseSimlock(
context: FrontContext,
identity: TokenIdentity,
identity: Identity,
leaseId: string,
): Promise<SimlockRelease> {
try {
Expand Down Expand Up @@ -144,7 +144,7 @@ export function scopeOf(
export async function releaseAgentDevice(
context: FrontContext,
request: Request,
identity: TokenIdentity,
identity: Identity,
leaseId: string,
scope: Record<string, unknown>,
) {
Expand All @@ -160,7 +160,7 @@ export async function releaseAgentDevice(
// why: a lease the token holds under another requester than its own id was made by something else (a gateway, for a worker's token of the same name), so this front has no claim to end it.
export async function heldForAnother(
context: FrontContext,
identity: TokenIdentity,
identity: Identity,
leaseId: string,
): Promise<boolean> {
try {
Expand All @@ -174,7 +174,7 @@ export async function heldForAnother(

const LIST_TIMEOUT_MS = 5_000;

export async function listLeases(context: FrontContext, identity: TokenIdentity) {
export async function listLeases(context: FrontContext, identity: Identity) {
let timer: ReturnType<FrontContext["clock"]["setTimer"]> | undefined;
const timeout = new Promise<never>((_resolve, reject) => {
timer = context.clock.setTimer(LIST_TIMEOUT_MS, () =>
Expand Down
8 changes: 4 additions & 4 deletions src/agent-device/front/devices-filter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { TokenIdentity } from "../../http/token-store.js";
import type { Identity } from "../../auth/index.js";
import { failure, frontReply, workerUnreachable } from "../shared/replies.js";
import { readBounded, readReply } from "../shared/rpc.js";
import { asRecord } from "../shared/selectors.js";
Expand All @@ -15,7 +15,7 @@ function emptyList(rpc: { readonly id: unknown }): Response {

export async function filterDevices(
context: FrontContext,
identity: TokenIdentity,
identity: Identity,
response: Response,
rpc: { readonly id: unknown },
): Promise<Response> {
Expand Down Expand Up @@ -44,7 +44,7 @@ export async function filterDevices(
// why: one lease the gateway cannot reach makes the whole list unknown, so `devices` answers it rather than a list missing that device.
export async function anyUnreachable(
context: FrontContext,
identity: TokenIdentity,
identity: Identity,
leases: readonly { readonly leaseId: string }[],
): Promise<boolean> {
for (const lease of leases) {
Expand All @@ -55,7 +55,7 @@ export async function anyUnreachable(

interface GatewayDevices {
readonly request: Request;
readonly identity: TokenIdentity;
readonly identity: Identity;
readonly read: { readonly id: unknown; readonly text: string };
readonly forward: (request: Request, leaseId: string) => Promise<Response>;
}
Expand Down
4 changes: 2 additions & 2 deletions src/agent-device/front/ended.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { TokenIdentity } from "../../http/token-store.js";
import type { Identity } from "../../auth/index.js";
import { leaseIdOf } from "../shared/rpc.js";
import { asRecord } from "../shared/selectors.js";
import type { FrontContext } from "./context.js";
Expand Down Expand Up @@ -43,7 +43,7 @@ function endedLeaseIds(text: string): string[] {
// why: the daemon no longer sends a release after it ends a lease, so the front ends the simlock lease from the command's reply; a copy is read so the CLI's reply goes out untouched.
export function releaseEndedLeases(
context: FrontContext,
identity: TokenIdentity,
identity: Identity,
response: Response,
): void {
if (!(response.headers.get("content-type") ?? "").includes("json")) return;
Expand Down
9 changes: 5 additions & 4 deletions src/agent-device/front/front-map.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { describe, expect, it, vi } from "vitest";

import type { TokenIdentity } from "../../http/token-store.js";
import { tokenIdentity } from "../../auth/testing.js";
import type { Identity } from "../../auth/index.js";
import { FakeClock } from "../../ports/index.js";
import { FrontMap } from "./front-map.js";

const agent: TokenIdentity = { requesterId: "tok_a", role: "agent" };
const agent: Identity = tokenIdentity("tok_a");
const ttlMs = 60_000;

function entry(deadline: number) {
Expand Down Expand Up @@ -80,14 +81,14 @@ describe("the front map", () => {
const clock = new FakeClock(1_000);
const map = new FrontMap(clock);
for (let n = 0; n < 101; n += 1) {
const identity: TokenIdentity = { requesterId: `tok_${n}`, role: "agent" };
const identity: Identity = tokenIdentity(`tok_${n}`);
map.add(`lease-${n}`, { address: "a", deadline: 2_100 - n, identity, ttlMs });
}
clock.advance(10_000);
const asked: string[] = [];

await map.refresh(async (who) => {
asked.push(who.requesterId);
asked.push(who.principal);
return [];
});

Expand Down
21 changes: 9 additions & 12 deletions src/agent-device/front/front-map.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { TokenIdentity } from "../../http/token-store.js";
import type { Identity } from "../../auth/index.js";
import type { Clock } from "../../ports/index.js";

const MAX_PRINCIPALS_PER_REFRESH = 100;
Expand All @@ -14,7 +14,7 @@ interface DeviceFacts {
}

export interface FrontMapEntry extends DeviceFacts {
readonly identity: TokenIdentity;
readonly identity: Identity;
readonly address: string;
readonly ttlMs: number;
readonly deadline: number;
Expand All @@ -23,7 +23,7 @@ export interface FrontMapEntry extends DeviceFacts {
export type EndedBy = "agent" | "simlock";

export interface HeldView extends DeviceFacts {
readonly identity: TokenIdentity;
readonly identity: Identity;
readonly address: string;
readonly ttlMs: number;
readonly endedAt?: number;
Expand All @@ -37,7 +37,7 @@ export interface ListedLease {

interface Held extends Omit<DeviceFacts, "deviceKey"> {
deviceKey?: string;
readonly identity: TokenIdentity;
readonly identity: Identity;
readonly address: string;
ttlMs: number;
deadline: number;
Expand Down Expand Up @@ -79,7 +79,7 @@ export class FrontMap {
liveOf(requesterId: string): readonly (HeldView & { readonly leaseId: string })[] {
this.#prune();
return [...this.#held]
.filter(([, held]) => held.identity.requesterId === requesterId && held.endedAt === undefined)
.filter(([, held]) => held.identity.principal === requesterId && held.endedAt === undefined)
.map(([leaseId, held]) => ({ ...held, leaseId }));
}

Expand Down Expand Up @@ -112,18 +112,15 @@ export class FrontMap {
held.releasing = false;
}

async refresh(list: (identity: TokenIdentity) => Promise<readonly ListedLease[]>): Promise<void> {
async refresh(list: (identity: Identity) => Promise<readonly ListedLease[]>): Promise<void> {
this.#prune();
const now = this.clock.now();
const byPrincipal = new Map<
string,
{ identity: TokenIdentity; oldest: number; ids: string[] }
>();
const byPrincipal = new Map<string, { identity: Identity; oldest: number; ids: string[] }>();
for (const [id, held] of this.#held) {
if (held.endedAt !== undefined || held.deadline > now) continue;
const group = byPrincipal.get(held.identity.requesterId);
const group = byPrincipal.get(held.identity.principal);
if (group === undefined) {
byPrincipal.set(held.identity.requesterId, {
byPrincipal.set(held.identity.principal, {
identity: held.identity,
ids: [id],
oldest: held.deadline,
Expand Down
Loading
Loading