@parcha/agentrun-kernel 0.1.0-beta.36 → 0.1.0-beta.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/dist/host/index.d.ts +2 -4
  3. package/dist/host/index.js +2 -3
  4. package/dist/host/overhead.d.ts +42 -0
  5. package/dist/host/overhead.js +84 -10
  6. package/dist/host/proxy.d.ts +34 -15
  7. package/dist/host/proxy.js +99 -25
  8. package/dist/index.d.ts +2 -1
  9. package/dist/index.js +1 -0
  10. package/dist/kernel/cap/index.d.ts +4 -4
  11. package/dist/kernel/cap/index.js +3 -3
  12. package/dist/kernel/cap/port.d.ts +14 -3
  13. package/dist/kernel/cap/port.js +29 -16
  14. package/dist/kernel/cap/price.d.ts +31 -6
  15. package/dist/kernel/cap/price.js +49 -15
  16. package/dist/kernel/cap/rule.d.ts +11 -1
  17. package/dist/kernel/cap/rule.js +30 -3
  18. package/dist/kernel/cap/run-cap.d.ts +9 -2
  19. package/dist/kernel/cap/run-cap.js +8 -3
  20. package/dist/kernel/cap/types.d.ts +11 -5
  21. package/dist/kernel/registry/computer-surface.generated.d.ts +9 -0
  22. package/dist/kernel/registry/computer-surface.generated.js +618 -0
  23. package/dist/kernel/registry/computer.d.ts +14 -0
  24. package/dist/kernel/registry/computer.js +75 -0
  25. package/dist/kernel/registry/defs.d.ts +1 -4
  26. package/dist/kernel/registry/defs.js +1 -13
  27. package/dist/kernel/registry/handoff.js +4 -4
  28. package/dist/kernel/registry/hands.d.ts +22 -115
  29. package/dist/kernel/registry/hands.js +0 -2
  30. package/dist/kernel/registry/index.d.ts +4 -4
  31. package/dist/kernel/registry/index.js +5 -5
  32. package/dist/kernel/registry/registry.d.ts +4 -5
  33. package/dist/kernel/registry/registry.js +27 -29
  34. package/dist/kernel/types.d.ts +10 -2
  35. package/dist/process/tools.d.ts +5 -1
  36. package/dist/process/tools.js +62 -8
  37. package/dist/run-booking.d.ts +3 -0
  38. package/dist/run-booking.js +7 -0
  39. package/dist/runner.d.ts +21 -2
  40. package/dist/runner.js +126 -11
  41. package/dist/testing.d.ts +6 -2
  42. package/dist/testing.js +5 -3
  43. package/dist/tool-deferral.d.ts +12 -0
  44. package/dist/tool-deferral.js +17 -0
  45. package/dist/types.d.ts +83 -39
  46. package/package.json +2 -2
  47. package/dist/host/mcp-route.d.ts +0 -14
  48. package/dist/host/mcp-route.js +0 -125
  49. package/dist/kernel/registry/desktop.d.ts +0 -11
  50. package/dist/kernel/registry/desktop.js +0 -90
  51. package/dist/kernel/registry/phone.d.ts +0 -15
  52. package/dist/kernel/registry/phone.js +0 -135
package/dist/types.d.ts CHANGED
@@ -56,13 +56,49 @@ export interface HostTool {
56
56
  sessionDir?: (key: string) => string; /** The kernel's attempt at this call: 0 the first time; above 0 when a crash cut an earlier attempt of a replay-safe tool and this one runs it again, so the earlier one may have been sent. */
57
57
  attempt?: number;
58
58
  model?: unknown;
59
- output?(chunk: string): void;
59
+ output?(chunk: string): void; /** The session's other tools, called as calls of their own nested in this one (NestedCalls): given to a tool that `nests`, where the harness has a way to. */
60
+ nested?: NestedCalls;
60
61
  }): Promise<{
61
62
  text: string;
62
63
  isError?: boolean;
63
- images?: readonly ToolImage[];
64
+ images?: readonly ToolImage[]; /** The answer as a value (a computer tool's), its images' data left out: what a script's nested call reads (Codex's code mode) and an MCP client's structuredContent. */
65
+ structured?: JsonValue;
64
66
  parked?: true;
65
67
  }>;
68
+ /** The tool only calls the session's other tools (tools_call, codemode), each as a call of its own nested in this one
69
+ * (`context.nested`): each nested call passes the gate as itself and is recorded under its own id, so this call writes
70
+ * no intent or outcome of its own. A harness runs it again after a crash, its recorded nested calls answered from their
71
+ * records, never run twice. */
72
+ nests?: true;
73
+ /** Registered and callable (by the gate, and by a nested call: tools_call, a script), but not listed to the model: a
74
+ * catalog tool of a run whose catalog is deferred (tool-deferral.ts), which the model finds with tools_search. */
75
+ deferred?: true;
76
+ }
77
+ /**
78
+ * A tool's calls of the session's other tools, each a call of its own nested in the calling one: asked about at the gate
79
+ * as itself (GateCall `nested`), its intent and outcome recorded under `<callId>/<key>` before and after it runs, as a
80
+ * call the model made is. A call the record finished answers from the record, never runs again.
81
+ */
82
+ export interface NestedCalls {
83
+ /** Call tool `name` (a session tool, by its host name) with `args`, under `key`: stable for the same call in a rerun
84
+ * of the calling one. A deny answers `refused` with the gate's words; a park holds until the session lets go, then
85
+ * rejects. */
86
+ call(name: string, args: Record<string, unknown>, key: string): Promise<NestedResult>;
87
+ /** `value` the first time `key` is asked in this call, and that first value again in every rerun of the call. */
88
+ memo<T extends JsonValue>(key: string, value: T): Promise<T>;
89
+ }
90
+ /** A nested call's answer. */
91
+ export interface NestedResult {
92
+ text: string;
93
+ isError?: boolean;
94
+ images?: readonly ToolImage[];
95
+ structured?: JsonValue;
96
+ /** The gate refused it: `text` is the gate's words, and nothing of it ran. */
97
+ refused?: true;
98
+ /** Its intent was recorded and its outcome lost (a crash cut it): it may or may not have taken effect. */
99
+ interrupted?: true;
100
+ /** It was asked and run (or refused) now, in this attempt of the calling call; false when its answer came from the record. */
101
+ fresh: boolean;
66
102
  }
67
103
  /** A tool of a remote MCP server, as the server listed it when its owner saved it (the run's pinned copy). */
68
104
  export interface McpTool {
@@ -72,29 +108,13 @@ export interface McpTool {
72
108
  inputSchema: Record<string, unknown>;
73
109
  annotations?: Record<string, unknown>;
74
110
  }
75
- /** What an MCP tool call answers the model: its text, and whether the tool said it failed. */
111
+ /** What an MCP tool call answers: its text, and whether the tool said it failed. */
76
112
  export interface McpCallResult {
77
113
  content: {
78
114
  type: "text";
79
115
  text: string;
80
116
  }[];
81
117
  isError?: boolean;
82
- /** The host parked the call for a person's approval: it did not run, and the text says it waits. The harness's own
83
- * client never sees this flag (the door sends `content` and `isError`). */
84
- parked?: true;
85
- }
86
- /** A session's remote MCP servers: each one's granted tools, and the call that reaches them through the host, which holds
87
- * their credentials. A harness with its own MCP client points it at the session's model proxy (`/mcp/<server>`). */
88
- export interface SessionMcp {
89
- servers: readonly {
90
- name: string;
91
- tools: readonly McpTool[];
92
- }[];
93
- /** Never throws: a failure is an `isError` result the model reads. `callId` is the harness's id for the call. */
94
- call(server: string, tool: string, args: Record<string, unknown>, context: {
95
- signal: AbortSignal;
96
- callId?: string;
97
- }): Promise<McpCallResult>;
98
118
  }
99
119
  /** One durable record of a session, in the order it was appended. */
100
120
  export interface SessionRecord {
@@ -114,6 +134,12 @@ export interface SessionStore {
114
134
  /** The one holder that may write a session. */
115
135
  export interface SessionWriter {
116
136
  readonly key: string;
137
+ /** The session's identity across the claims of one holder (a runner's name and a run's id beside the key), for a store
138
+ * whose claims a holder can lose and take again. A booking of the session whose cost write is refused (its claim lost
139
+ * as its request answered) hands that booking to the next booking of the same scope in this process, which writes it
140
+ * before it books any request cut (ModelBooking.bookCut). Absent: nothing is handed on, and such a request is booked
141
+ * cut. Never shared by two holders: another runner, as one that died, takes nothing of it. */
142
+ readonly scope?: string;
117
143
  read(): Promise<SessionRecord[]>;
118
144
  /** Resolves once the records are durable, in order. Rejects with `SessionFenced`, writing none of them, once a newer
119
145
  * `open` of the key has resolved. */
@@ -130,11 +156,13 @@ export interface SessionSpec {
130
156
  label: string;
131
157
  executionPath?: string;
132
158
  system: string[];
133
- /** Exactly these tools; the harness's own stay off. */
159
+ /** Exactly these tools (a run's remote MCP tools among them, as host tools); the harness's own stay off. */
134
160
  tools: HostTool[];
135
- /** The remote MCP servers it may call, for a harness that has its own MCP client. */
136
- mcp?: SessionMcp;
137
161
  context: "fresh" | "fork";
162
+ /** The host's one verdict on whether the run's catalog tools are deferred (tool-deferral.ts defersCatalog, and both
163
+ * tools_search and tools_call allowed). A harness with a tool search of its own (`ownToolSearch`) turns it on exactly
164
+ * when this is true; absent, it decides by the names alone. */
165
+ deferCatalog?: boolean;
138
166
  tier?: NodeRequest["tier"];
139
167
  effort?: NodeRequest["effort"];
140
168
  thinking?: NodeRequest["thinking"];
@@ -178,6 +206,9 @@ export interface ModelRequest {
178
206
  /** A side call, never its turn's own: on another model than the session's (a client's title, a summary), or the
179
207
  * host's own request beside the harness's (`host`). */
180
208
  side?: true;
209
+ /** On the session's model but no answer of the turn (a title, a summary, a child's request): booked as any request, but
210
+ * never one of the session's recent requests for the cap's expected pricing, read or kept. */
211
+ unanswered?: true;
181
212
  /** It carries the host's note (ModelPort.note) in its body: the note is delivered once this request is admitted.
182
213
  * `inputTokensMaxWithoutNote`: its input measured as its client sent it, before the note was placed. */
183
214
  noted?: true;
@@ -239,6 +270,9 @@ export interface ModelPort {
239
270
  * session's model proxy adds it to that request's body (ModelProxyHooks.note). `request`: that request as its client
240
271
  * sent it, measured before the note is placed (NoteRequest), so the host can price it as its admission will. */
241
272
  note?(model: string, request?: NoteRequest): string | undefined;
273
+ /** The note `note` gave back: the request that took it left before its admission (its client gone, a refusal or an
274
+ * error before `beforeRequest`), so it was never sent, and the host may give it to the next request at once. */
275
+ noteReturned?(note: string): void;
242
276
  }
243
277
  /** A request about to take its host's note, as its client sent it: its input bound and the output it asks for and needs
244
278
  * at least, as the model proxy reads them (ModelRequest's figures, without the note). */
@@ -276,6 +310,12 @@ export interface SessionIO {
276
310
  * runs nothing; a park holds the call, writing nothing, until the session's signal is aborted (the run parks on a
277
311
  * person). Absent: every call runs. */
278
312
  gate?(call: GateCall, context?: unknown): Promise<GateAnswer>;
313
+ /** The host's setting now for one of the harness's own tools, by the harness's name for it (Codex's `web_search`), read
314
+ * again at each ask, so a permission set while the session runs reaches its next request. For a tool no call of which
315
+ * reaches the gate before it runs: a provider-hosted search runs inside a model request, so the session offers it only
316
+ * while this says "allow" (a throw reads as "deny"). Absent: the host keeps no per-tool permissions, and what the
317
+ * session was opened with stands. */
318
+ permission?(tool: string): Promise<ToolPermission>;
279
319
  /** A tool the adapter adds of its own (read_skill_file over the session's skills), made the host's: its calls go the
280
320
  * way the host's own tools' do (the run's record of the call and its result, which its Timeline shows, the rule before
281
321
  * a side effect, the host's hooks on the result). An adapter hands every tool it adds through it. Absent: the host
@@ -292,6 +332,9 @@ export interface GateCall {
292
332
  /** The call runs again after an earlier attempt whose start the log holds (a replay-safe call a crash cut): that
293
333
  * attempt may have been sent, so a refusal never says nothing was. */
294
334
  readonly replayed?: true;
335
+ /** A call a running tool made (NestedCalls: a script's, tools_call's), part of a call already let through: the cap's
336
+ * wrap-up never refuses one, so a call in flight is never cut short, as pi's nested call is not. */
337
+ readonly nested?: true;
295
338
  }
296
339
  /** The host's answer before a call's intent: run it, refuse it in these words, or park the run on it. */
297
340
  export type GateAnswer = "allow" | {
@@ -299,6 +342,8 @@ export type GateAnswer = "allow" | {
299
342
  } | {
300
343
  readonly park: true;
301
344
  };
345
+ /** A tool's setting on the host (SessionIO.permission): it runs, it waits for a person's answer, or it is refused. */
346
+ export type ToolPermission = "allow" | "ask" | "deny";
302
347
  /** An event of a session, as the adapter reports it. The runner adds the node it belongs to. A call's `tool_end` is sent
303
348
  * only once its outcome is durable in the session's records, so a host never shows a result its store does not have;
304
349
  * `result` is the text recorded, when the adapter reports it. A call stopped before its outcome was recorded gets no
@@ -430,8 +475,6 @@ export interface AdapterFacts {
430
475
  readonly recoversCutAnswers?: number;
431
476
  /** What one run of it holds in memory, in MiB: the host admits runs by it. */
432
477
  readonly runMib: number;
433
- /** Whether it binds a session's remote MCP servers (its own MCP client, at the session's gateway). */
434
- readonly mcp: boolean;
435
478
  /** The thinking levels it takes, lowest first: a run's level above its highest runs at that highest. */
436
479
  readonly thinking: readonly ("low" | "medium" | "high" | "xhigh" | "max")[];
437
480
  /** Its own web search, when the provider runs it: `native`, the provider's search through the session's proxy (its
@@ -440,6 +483,12 @@ export interface AdapterFacts {
440
483
  readonly webSearch?: "native" | "live";
441
484
  /** Its model is its own, chosen on its own wire's settings, never the host's default for the other harnesses. */
442
485
  readonly ownModel: boolean;
486
+ /** It runs the model's scripts itself (Codex's code mode, its nested calls the host's tools): the host offers no
487
+ * `codemode` of its own beside it. Absent: the host's codemode is offered. */
488
+ readonly ownCodemode?: true;
489
+ /** It defers a run's MCP tools behind a tool search of its own (Claude Code's ToolSearch), so the host offers no
490
+ * `tools_search` or `tools_call` beside it. Absent: the host's are offered when a run's catalog tools are deferred. */
491
+ readonly ownToolSearch?: true;
443
492
  /** The model as the harness names it (Anthropic's id has no dot). */
444
493
  normalizeModel(model: {
445
494
  provider: string;
@@ -458,9 +507,9 @@ export interface AdapterFacts {
458
507
  pins: string;
459
508
  };
460
509
  };
461
- /** The problems its own MCP client has with a tool's input schema (`tool` as it names it, `mcp__<server>__<tool>`):
462
- * shapes it drops or retypes, measured on its pinned build, so a grant of that tool would offer the model another
463
- * tool than the one granted. None: its client takes any schema the kernel's check does. */
510
+ /** The problems it has with a host tool's input schema (`tool` by its name, a run's MCP tool's `mcp__<server>__<tool>`):
511
+ * shapes it drops or retypes, measured on its pinned build, so a grant of an MCP tool would offer the model another
512
+ * tool than the one granted. None: it takes any schema the kernel's check does. */
464
513
  schemaProblems?(tool: string, schema: Record<string, unknown>): string[];
465
514
  /** A name its client calls a session's MCP tool by beside `mcp__<server>__<tool>` (OpenCode's `<server>_<tool>`). */
466
515
  readonly toolAlias?: RegExp;
@@ -488,20 +537,15 @@ export interface SessionPort {
488
537
  /** The API the proxy serves: Anthropic's Messages (claude-agent) or OpenAI's Responses (codex, opencode). */
489
538
  api: "anthropic-messages" | "openai-responses";
490
539
  }
491
- export interface AdapterCapabilities {
492
- /** Its harness's own MCP client, when it has one: it calls `spec.mcp`'s servers at the session proxy's `/mcp/<server>`,
493
- * which the kernel's model proxy mounts from the session's MCP and this fact (ModelProxyOptions.mcp). */
494
- mcpClient?: McpClient;
495
- }
496
- /** A harness's own MCP client, as its adapter declares it: the `_meta` key of a `tools/call` that carries the harness's
497
- * own id for the call (Claude Code's `claudecode/toolUseId`, Codex's `callId`), the id its timeline and gate know the
498
- * call by. The route reads that key and no other. */
499
- export interface McpClient {
500
- callIdMeta: string;
501
- }
502
540
  export interface AgentAdapter {
503
541
  readonly id: string;
504
- capabilities(): AdapterCapabilities;
542
+ /** Tools the harness runs itself beside the session's host tools (pi's subagent tool, its browser's): offered to the
543
+ * model as the host tools are, so the host's tools_search lists them and a nested call reaches one by its name. */
544
+ readonly ownTools?: readonly {
545
+ readonly name: string;
546
+ readonly description: string;
547
+ readonly inputSchema: Record<string, unknown>;
548
+ }[];
505
549
  /** Problems with a session before anything is spent; an empty list opens it. */
506
550
  check(spec: SessionSpec): string[];
507
551
  /** Opens the session, restoring it from `io.writer` when its key has records. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-kernel",
3
- "version": "0.1.0-beta.36",
3
+ "version": "0.1.0-beta.38",
4
4
  "description": "Agent harnesses other than Pi, starting with Codex, behind one seam: a DSL node's runNode and an AgentRun run on a harness adapter, durable in AgentRun's own store.",
5
5
  "keywords": [
6
6
  "agentrun",
@@ -60,7 +60,7 @@
60
60
  "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
61
61
  },
62
62
  "dependencies": {
63
- "@parcha/agentrun-dsl": "0.1.0-beta.36",
63
+ "@parcha/agentrun-dsl": "0.1.0-beta.38",
64
64
  "ajv": "8.18.0",
65
65
  "typebox": "1.3.27"
66
66
  },
@@ -1,14 +0,0 @@
1
- import type { IncomingMessage, ServerResponse } from "node:http";
2
- import type { SessionMcp } from "../types.js";
3
- /** The protocol revisions answered, newest first: a client asking for another gets the newest. */
4
- export declare const MCP_ROUTE_VERSIONS: readonly string[];
5
- export interface McpRouteOptions {
6
- /** How often a call in flight sends a keepalive. Default 15 s. */
7
- keepaliveMs?: number;
8
- /** The `_meta` key of a `tools/call` that carries the harness's own id for the call (McpClient.callIdMeta); none, the
9
- * call has no id. */
10
- callIdMeta?: string;
11
- }
12
- /** The handler a model proxy mounts at `/mcp/<server>` (ModelProxyOptions.mcp). */
13
- export type McpHandler = (server: string, req: IncomingMessage, res: ServerResponse) => Promise<void>;
14
- export declare function mcpRoute(mcp: SessionMcp, options?: McpRouteOptions): McpHandler;
@@ -1,125 +0,0 @@
1
- import { parseStrict } from "./proxy.js";
2
- /** The protocol revisions answered, newest first: a client asking for another gets the newest. */
3
- export const MCP_ROUTE_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26"];
4
- const MAX_BODY = 4 * 1024 * 1024;
5
- const KEEPALIVE_MS = 15_000;
6
- const isPlain = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7
- const isId = (v) => typeof v === "string" || (typeof v === "number" && Number.isSafeInteger(v));
8
- export function mcpRoute(mcp, options = {}) {
9
- const keepaliveMs = options.keepaliveMs ?? KEEPALIVE_MS;
10
- const servers = new Map(mcp.servers.map((server) => [server.name, server]));
11
- /** Calls in flight, by server and JSON-RPC id. */
12
- const running = new Map();
13
- const keyOf = (server, id) => `${server}\0${typeof id}:${id}`;
14
- const json = (res, status, body) => {
15
- res.writeHead(status, body === undefined ? { "content-length": "0" } : { "content-type": "application/json" });
16
- res.end(body === undefined ? undefined : JSON.stringify(body));
17
- };
18
- const failure = (id, code, message) => ({ jsonrpc: "2.0", id, error: { code, message } });
19
- return async (server, req, res) => {
20
- const served = servers.get(server);
21
- if (!served)
22
- return json(res, 404, failure(null, -32601, `this session has no MCP server ${server}`));
23
- if (req.method !== "POST") {
24
- res.writeHead(405, { allow: "POST", "content-length": "0" });
25
- return void res.end();
26
- }
27
- const chunks = [];
28
- let size = 0;
29
- for await (const chunk of req) {
30
- size += chunk.length;
31
- if (size > MAX_BODY)
32
- return json(res, 413, failure(null, -32600, "the request is too large"));
33
- chunks.push(chunk);
34
- }
35
- let message;
36
- try {
37
- const parsed = parseStrict(Buffer.concat(chunks).toString("utf8"));
38
- if (!isPlain(parsed))
39
- return json(res, 400, failure(null, -32600, "one JSON-RPC message per request; no batches"));
40
- message = parsed;
41
- }
42
- catch {
43
- return json(res, 400, failure(null, -32700, "the body is not JSON"));
44
- }
45
- const params = isPlain(message.params) ? message.params : {};
46
- // A notification, or the client's answer to a request: nothing to say back.
47
- if (typeof message.method !== "string" || message.id === undefined) {
48
- if (message.method === "notifications/cancelled" && isId(params.requestId))
49
- running.get(keyOf(server, params.requestId))?.abort();
50
- return json(res, 202);
51
- }
52
- if (!isId(message.id))
53
- return json(res, 400, failure(null, -32600, "the request's id must be a string or an integer"));
54
- const id = message.id;
55
- const answer = (result) => json(res, 200, { jsonrpc: "2.0", id, result });
56
- switch (message.method) {
57
- case "initialize": {
58
- const asked = params.protocolVersion;
59
- const protocolVersion = typeof asked === "string" && MCP_ROUTE_VERSIONS.includes(asked) ? asked : MCP_ROUTE_VERSIONS[0];
60
- return answer({ protocolVersion, capabilities: { tools: {} }, serverInfo: { name: `agentrun-${server}`, version: "1.0.0" } });
61
- }
62
- case "ping":
63
- return answer({});
64
- case "tools/list":
65
- return answer({ tools: served.tools.map((tool) => ({ name: tool.name, ...(tool.title ? { title: tool.title } : {}), description: tool.description ?? "", inputSchema: tool.inputSchema, ...(tool.annotations ? { annotations: tool.annotations } : {}) })) });
66
- case "tools/call":
67
- return call(server, id, params, req, res);
68
- default:
69
- return json(res, 200, failure(id, -32601, `${String(message.method).slice(0, 64)} is not a method this server answers`));
70
- }
71
- };
72
- async function call(server, id, params, req, res) {
73
- const meta = isPlain(params._meta) ? params._meta : {};
74
- const progressToken = isId(meta.progressToken) ? meta.progressToken : undefined;
75
- // The harness's own id for the call, under the key its adapter declared (McpClient.callIdMeta), and no other.
76
- const own = options.callIdMeta !== undefined && Object.hasOwn(meta, options.callIdMeta) ? meta[options.callIdMeta] : undefined;
77
- const callId = typeof own === "string" ? own : undefined;
78
- const stream = String(req.headers.accept ?? "").includes("text/event-stream");
79
- const controller = new AbortController();
80
- const key = keyOf(server, id);
81
- running.set(key, controller);
82
- // A client gone before the answer: its call is aborted, upstream too.
83
- res.once("close", () => { if (!res.writableFinished)
84
- controller.abort(); });
85
- const send = (body) => res.write(`event: message\ndata: ${JSON.stringify(body)}\n\n`);
86
- let timer;
87
- if (stream) {
88
- res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });
89
- res.flushHeaders();
90
- let beat = 0;
91
- timer = setInterval(() => {
92
- beat += 1;
93
- if (progressToken === undefined)
94
- res.write(": keepalive\n\n");
95
- else
96
- send({ jsonrpc: "2.0", method: "notifications/progress", params: { progressToken, progress: beat } });
97
- }, keepaliveMs);
98
- }
99
- let result;
100
- try {
101
- const name = params.name;
102
- const args = isPlain(params.arguments) ? params.arguments : {};
103
- const granted = typeof name === "string" && servers.get(server).tools.some((tool) => tool.name === name);
104
- result = granted
105
- // The door calls the session's MCP (serve's gateway.call); its target is the tool plane's one invoke() (fix 2).
106
- ? await mcp.call(server, name, args, { signal: controller.signal, ...(callId ? { callId } : {}) })
107
- : { content: [{ type: "text", text: `${String(name).slice(0, 64)} is not a tool of the MCP server ${server} in this session.` }], isError: true };
108
- }
109
- catch (error) {
110
- result = { content: [{ type: "text", text: `The MCP server ${server}'s call failed: ${String(error?.message ?? error).slice(0, 300)}` }], isError: true };
111
- }
112
- finally {
113
- clearInterval(timer);
114
- running.delete(key);
115
- }
116
- if (res.destroyed)
117
- return;
118
- // What the client reads of the answer: its content, and whether it failed (never the host's `parked`).
119
- const body = { jsonrpc: "2.0", id, result: { content: result.content, ...(result.isError ? { isError: true } : {}) } };
120
- if (!stream)
121
- return json(res, 200, body);
122
- send(body);
123
- res.end();
124
- }
125
- }
@@ -1,11 +0,0 @@
1
- import type { ToolDef } from "./defs.js";
2
- import { type Executor } from "./hands.js";
3
- /** computerd's key table (protocol.ts KEYS): a key is one of these names, or one printable ASCII character. */
4
- export declare const DESKTOP_KEYS: readonly ["enter", "tab", "space", "backspace", "delete", "escape", "insert", "up", "down", "left", "right", "home", "end", "pageup", "pagedown", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "shift", "ctrl", "alt", "super", "capslock"];
5
- /** The most actions one desktop_input call holds: computerd's MAX_ACTIONS. */
6
- export declare const DESKTOP_MAX_ACTIONS = 100;
7
- /** The actions desktop_input offers, of computerd's input.actions. */
8
- export declare const DESKTOP_ACTIONS: readonly ["move", "click", "drag", "scroll", "type", "key"];
9
- export declare const DESKTOP_TOOL_DEFS: readonly ToolDef[];
10
- /** The desktop's tools' runs, on the hands' screen and input. */
11
- export declare const DESKTOP_EXECUTORS: Readonly<Record<string, Executor>>;
@@ -1,90 +0,0 @@
1
- import { answerOf, needsKindWords, shotAnswer } from "./hands.js";
2
- import { HANDOFF_TOOL, handoffDef, handoffExecutor } from "./handoff.js";
3
- /** computerd's key table (protocol.ts KEYS): a key is one of these names, or one printable ASCII character. */
4
- export const DESKTOP_KEYS = [
5
- "enter", "tab", "space", "backspace", "delete", "escape", "insert",
6
- "up", "down", "left", "right", "home", "end", "pageup", "pagedown",
7
- "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12",
8
- "shift", "ctrl", "alt", "super", "capslock",
9
- ];
10
- /** The most actions one desktop_input call holds: computerd's MAX_ACTIONS. */
11
- export const DESKTOP_MAX_ACTIONS = 100;
12
- /** The actions desktop_input offers, of computerd's input.actions. */
13
- export const DESKTOP_ACTIONS = ["move", "click", "drag", "scroll", "type", "key"];
14
- const def = (name, description, parameters, replaySafe) => ({
15
- name, source: "host", gateName: `host:desktop/${name}`, settingsKey: "desktop", description, parameters, replaySafe,
16
- });
17
- const object = (properties, required) => ({ type: "object", additionalProperties: false, properties, required });
18
- const POINT = { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2, description: "[x, y] in screenshot pixels, origin top left." };
19
- const BUTTON = { type: "string", enum: ["left", "right", "middle"], description: "left when absent." };
20
- const KEY = { type: "string", description: "A key name (enter, tab, space, backspace, delete, escape, insert, up, down, left, right, home, end, pageup, pagedown, f1 to f12, shift, ctrl, alt, super, capslock) or one printable character (\"a\", \"A\", \"/\")." };
21
- const action = (type, properties, required, description) => ({ ...object({ type: { const: type }, ...properties }, ["type", ...required]), description });
22
- export const DESKTOP_TOOL_DEFS = Object.freeze([
23
- def("desktop_screen", "Take a screenshot of the desktop computer's screen, as an image. Its pixels are the coordinates desktop_input takes, origin top left. With region, only that part of the screen, still in the whole screen's coordinates.", object({
24
- region: { ...object({ x: { type: "integer", minimum: 0 }, y: { type: "integer", minimum: 0 }, w: { type: "integer", minimum: 1 }, h: { type: "integer", minimum: 1 } }, ["x", "y", "w", "h"]), description: "Only this part of the screen: its top left corner and its size, in screenshot pixels." },
25
- }, []), true),
26
- def("desktop_input", `Act on the desktop computer with a list of actions, run in order: move the pointer, click, drag, scroll, type text, press keys. Points are [x, y] in the pixels of a desktop_screen screenshot, origin top left. Several keys in one key action press together, as a combo ("ctrl", "c"). A list with a malformed action runs nothing; one that fails partway says how many ran. It answers no image: take a screenshot to see what the actions did. At most ${DESKTOP_MAX_ACTIONS} actions a call.`, object({
27
- actions: {
28
- type: "array",
29
- minItems: 1,
30
- maxItems: DESKTOP_MAX_ACTIONS,
31
- items: {
32
- oneOf: [
33
- action("move", { at: POINT }, ["at"], "Move the pointer to at."),
34
- action("click", { at: POINT, button: BUTTON, count: { type: "integer", enum: [1, 2, 3], description: "1 when absent; 2 is a double click." } }, [], "Click at at (where the pointer is when absent)."),
35
- action("drag", { path: { type: "array", items: POINT, minItems: 2, description: "The points to drag through, from the first to the last." }, button: BUTTON }, ["path"], "Press at the path's first point, move through it, release at its last."),
36
- action("scroll", { at: POINT, dx: { type: "number" }, dy: { type: "number", description: "Above 0 scrolls down." }, unit: { type: "string", enum: ["clicks", "px"], description: "Wheel clicks, or pixels where the computer scrolls by pixels." } }, ["unit"], "Scroll at at (where the pointer is when absent)."),
37
- action("type", { text: { type: "string" } }, ["text"], "Type text, as given, into what has focus."),
38
- action("key", { keys: { type: "array", items: KEY, minItems: 1 } }, ["keys"], "Press a key, or several together as a combo."),
39
- ],
40
- },
41
- },
42
- }, ["actions"]), false),
43
- // The agent's hand-over of the desktop to the person (handoff.ts), under the desktop's settings key.
44
- handoffDef("desktop"),
45
- ]);
46
- const isWhole = (value, min) => Number.isSafeInteger(value) && value >= min;
47
- const regionOf = (value) => {
48
- if (value === undefined)
49
- return undefined;
50
- const region = value;
51
- if (typeof region !== "object" || region === null || !isWhole(region.x, 0) || !isWhole(region.y, 0) || !isWhole(region.w, 1) || !isWhole(region.h, 1)) {
52
- throw new Error("region is {x, y, w, h}: x and y whole numbers from 0, w and h whole numbers above 0");
53
- }
54
- return { x: region.x, y: region.y, w: region.w, h: region.h };
55
- };
56
- /** The batch as given, once each action is one of the six: the computer checks the rest, whole, before anything runs. */
57
- const actionsOf = (value) => {
58
- if (!Array.isArray(value) || value.length === 0 || value.length > DESKTOP_MAX_ACTIONS)
59
- throw new Error(`actions is a list of 1 to ${DESKTOP_MAX_ACTIONS} actions`);
60
- for (const [index, one] of value.entries()) {
61
- const type = one?.type;
62
- if (!DESKTOP_ACTIONS.includes(type))
63
- throw new Error(`action ${index} is a ${JSON.stringify(type)}: an action is one of ${DESKTOP_ACTIONS.join(", ")}`);
64
- }
65
- return value;
66
- };
67
- const port = (hands, key, tool) => {
68
- const found = hands[key];
69
- if (!found)
70
- throw new Error(needsKindWords(tool, "desktop"));
71
- return found;
72
- };
73
- /** The desktop's tools' runs, on the hands' screen and input. */
74
- export const DESKTOP_EXECUTORS = Object.freeze({
75
- desktop_screen: (args, call) => answerOf(call, async () => {
76
- const screen = port(call.hands, "screen", "desktop_screen");
77
- const region = regionOf(args?.region);
78
- const shot = await screen.shot(region ? { region } : {});
79
- return shotAnswer(region
80
- ? `A screenshot of the screen's region at (${region.x}, ${region.y}), ${region.w}x${region.h} pixels, in the whole screen's coordinates.`
81
- : `A screenshot of the whole screen, ${shot.width}x${shot.height} pixels.`, shot);
82
- }),
83
- desktop_input: (args, call) => answerOf(call, async () => {
84
- const input = port(call.hands, "input", "desktop_input");
85
- const actions = actionsOf(args?.actions);
86
- await input.actions(actions);
87
- return { text: `Ran ${actions.length} action${actions.length === 1 ? "" : "s"}. desktop_screen shows what ${actions.length === 1 ? "it" : "they"} did.` };
88
- }),
89
- [HANDOFF_TOOL]: handoffExecutor("desktop"),
90
- });
@@ -1,15 +0,0 @@
1
- import type { ToolDef } from "./defs.js";
2
- import { type Executor, type PhoneKey } from "./hands.js";
3
- /** How long a swipe takes when a call names no duration, and the longest one may. */
4
- export declare const PHONE_SWIPE_MS = 300;
5
- export declare const PHONE_SWIPE_MAX_MS = 10000;
6
- /** The most nodes phone_tree lists, and the most characters its answer takes: past either, one line counts the rest. A
7
- * screen's structure can hold thousands of nodes; the answer stays a screenful, never a flood in the model's context or
8
- * the run's journal. */
9
- export declare const PHONE_TREE_MAX_NODES = 150;
10
- export declare const PHONE_TREE_MAX_CHARS = 12000;
11
- /** The keys phone_key presses. */
12
- export declare const PHONE_KEYS: readonly PhoneKey[];
13
- export declare const PHONE_TOOL_DEFS: readonly ToolDef[];
14
- /** The phone's tools' runs, on the hands' phone. */
15
- export declare const PHONE_EXECUTORS: Readonly<Record<string, Executor>>;
@@ -1,135 +0,0 @@
1
- import { answerOf, needsKindWords, shotAnswer } from "./hands.js";
2
- import { HANDOFF_TOOL, handoffDef, handoffExecutor } from "./handoff.js";
3
- /** How long a swipe takes when a call names no duration, and the longest one may. */
4
- export const PHONE_SWIPE_MS = 300;
5
- export const PHONE_SWIPE_MAX_MS = 10_000;
6
- /** The most nodes phone_tree lists, and the most characters its answer takes: past either, one line counts the rest. A
7
- * screen's structure can hold thousands of nodes; the answer stays a screenful, never a flood in the model's context or
8
- * the run's journal. */
9
- export const PHONE_TREE_MAX_NODES = 150;
10
- export const PHONE_TREE_MAX_CHARS = 12_000;
11
- /** The most characters of a node's text or label phone_tree shows. */
12
- const PHONE_TREE_TEXT_CHARS = 80;
13
- /** The keys phone_key presses. */
14
- export const PHONE_KEYS = Object.freeze(["back", "home", "enter"]);
15
- const def = (name, description, parameters, replaySafe) => ({
16
- name, source: "host", gateName: `host:phone/${name}`, settingsKey: "phone", description, parameters, replaySafe,
17
- });
18
- const object = (properties, required) => ({ type: "object", additionalProperties: false, properties, required });
19
- const COORDINATE = { type: "integer", minimum: 0 };
20
- const POINT = { ...object({ x: COORDINATE, y: COORDINATE }, ["x", "y"]), description: "A point in screenshot pixels, origin top left." };
21
- export const PHONE_TOOL_DEFS = Object.freeze([
22
- def("phone_screen", "Take a screenshot of the phone's screen, as an image. Its pixels are the coordinates phone_tap and phone_swipe take, origin top left.", object({}, []), true),
23
- def("phone_tree", `List what on the phone's screen can be tapped or typed into, from the screen's structure: each node's class, its text or label, its id, and its center and bounds in a phone_screen screenshot's pixels (tap the center). At most ${PHONE_TREE_MAX_NODES} nodes; a last line counts any more.`, object({}, []), true),
24
- def("phone_tap", "Tap the phone's screen once at x, y, in the pixels of a phone_screen screenshot.", object({ x: COORDINATE, y: COORDINATE }, ["x", "y"]), false),
25
- def("phone_swipe", `Swipe on the phone's screen from one point to another, in screenshot pixels, over duration_ms (${PHONE_SWIPE_MS} ms when absent). A swipe up scrolls a list down.`, object({ from: POINT, to: POINT, duration_ms: { type: "integer", minimum: 1, maximum: PHONE_SWIPE_MAX_MS } }, ["from", "to"]), false),
26
- def("phone_type", "Type text into the field that has focus on the phone, as given. Tap the field first.", object({ text: { type: "string", minLength: 1 } }, ["text"]), false),
27
- def("phone_key", "Press one of the phone's keys: back (the system back: leaves a page, closes a dialog or the keyboard), home (the home screen) or enter (submits the field in focus).", object({ key: { type: "string", enum: [...PHONE_KEYS] } }, ["key"]), false),
28
- def("phone_apps", "List the phone's installed apps, each by its id (and its name where the phone gives one), and which app is in front.", object({}, []), true),
29
- def("phone_open", "Open an app on the phone by its id (phone_apps lists them), bringing it to the front.", object({ id: { type: "string", minLength: 1 } }, ["id"]), false),
30
- // The agent's hand-over of the phone to the person (handoff.ts), under the phone's settings key.
31
- handoffDef("phone"),
32
- ]);
33
- const POINT_WORDS = "x and y are whole numbers from 0, in the screenshot's pixels";
34
- const pointOf = (value, what = POINT_WORDS) => {
35
- const point = value;
36
- if (typeof point !== "object" || point === null || !Number.isSafeInteger(point.x) || !Number.isSafeInteger(point.y) || point.x < 0 || point.y < 0)
37
- throw new Error(what);
38
- return { x: point.x, y: point.y };
39
- };
40
- const said = (point) => `(${point.x}, ${point.y})`;
41
- const phoneOf = (hands, tool) => {
42
- if (!hands.phone)
43
- throw new Error(needsKindWords(tool, "phone"));
44
- return hands.phone;
45
- };
46
- const run = (tool, body) => (args, call) => answerOf(call, async () => body(phoneOf(call.hands, tool), (typeof args === "object" && args !== null ? args : {})));
47
- /** A node's class as a model reads it: the platform's, its package or iOS prefix dropped ("Button", "EditText"). */
48
- const classOf = (role) => role.replace(/^XCUIElementType/, "").split(".").pop() || role;
49
- const clip = (text) => (text.length > PHONE_TREE_TEXT_CHARS ? `${text.slice(0, PHONE_TREE_TEXT_CHARS - 1)}…` : text);
50
- /** One node, on one line: its class, its text or label (else its first inner text, marked so), its id, whether it is a
51
- * field (and in focus), its center to tap and its bounds. */
52
- function nodeLine(node) {
53
- const own = node.text || node.label;
54
- const name = own ? JSON.stringify(clip(own)) : node.inner ? `${JSON.stringify(clip(node.inner))} (inner text)` : "";
55
- const { x, y, w, h } = node.bounds;
56
- const state = node.editable ? `a field${node.focused ? ", focused" : ""}; ` : node.focused ? "focused; " : "";
57
- const center = `(${Math.round(x + w / 2)}, ${Math.round(y + h / 2)})`;
58
- return `- ${clip(classOf(node.role))}${name ? ` ${name}` : ""}${node.id ? ` [${clip(node.id)}]` : ""}: ${state}center ${center}, bounds ${x},${y} ${w}x${h}`;
59
- }
60
- /** phone_tree's answer: a head line, then a line a node, at most PHONE_TREE_MAX_NODES of them and PHONE_TREE_MAX_CHARS
61
- * characters in all; one last line counts the nodes not shown. */
62
- function treeAnswer(tree) {
63
- const nodes = tree.nodes.filter((node) => node.clickable || node.editable);
64
- const head = `${nodes.length} node${nodes.length === 1 ? "" : "s"} you can tap or type into, of ${tree.total} on the screen. Coordinates are a phone_screen screenshot's pixels.${tree.truncated ? " The phone gave only part of the screen's structure: take a phone_screen screenshot for the rest." : ""}`;
65
- const lines = [head];
66
- // Room kept for the last line, whatever it counts.
67
- let room = PHONE_TREE_MAX_CHARS - head.length - `\n${nodes.length} more nodes not shown.`.length;
68
- let shown = 0;
69
- for (const node of nodes) {
70
- if (shown >= PHONE_TREE_MAX_NODES)
71
- break;
72
- const line = nodeLine(node);
73
- if (line.length + 1 > room)
74
- break;
75
- lines.push(line);
76
- room -= line.length + 1;
77
- shown += 1;
78
- }
79
- if (shown < nodes.length)
80
- lines.push(`${nodes.length - shown} more node${nodes.length - shown === 1 ? "" : "s"} not shown.`);
81
- return lines.join("\n");
82
- }
83
- /** The phone's tools' runs, on the hands' phone. */
84
- export const PHONE_EXECUTORS = Object.freeze({
85
- phone_screen: run("phone_screen", async (phone) => {
86
- const shot = await phone.shot();
87
- return shotAnswer(`A screenshot of the phone's screen, ${shot.width}x${shot.height} pixels.`, shot);
88
- }),
89
- phone_tree: run("phone_tree", async (phone) => {
90
- if (!phone.tree)
91
- throw new Error("this phone does not offer its UI tree");
92
- return { text: treeAnswer(await phone.tree()) };
93
- }),
94
- phone_key: run("phone_key", async (phone, args) => {
95
- if (!phone.key)
96
- throw new Error("this phone does not offer its keys");
97
- const key = args.key;
98
- if (typeof key !== "string" || !PHONE_KEYS.includes(key))
99
- throw new Error(`key is ${PHONE_KEYS.slice(0, -1).join(", ")} or ${PHONE_KEYS.at(-1)}`);
100
- await phone.key(key);
101
- return { text: `Pressed ${key}.` };
102
- }),
103
- phone_tap: run("phone_tap", async (phone, args) => {
104
- const at = pointOf(args);
105
- await phone.tap(at);
106
- return { text: `Tapped at ${said(at)}.` };
107
- }),
108
- phone_swipe: run("phone_swipe", async (phone, args) => {
109
- const from = pointOf(args.from, `from: ${POINT_WORDS}`);
110
- const to = pointOf(args.to, `to: ${POINT_WORDS}`);
111
- const durationMs = args.duration_ms ?? PHONE_SWIPE_MS;
112
- if (!Number.isSafeInteger(durationMs) || durationMs < 1 || durationMs > PHONE_SWIPE_MAX_MS)
113
- throw new Error(`duration_ms is a whole number of milliseconds from 1 to ${PHONE_SWIPE_MAX_MS}`);
114
- await phone.swipe({ from, to, durationMs: durationMs });
115
- return { text: `Swiped from ${said(from)} to ${said(to)} over ${durationMs} ms.` };
116
- }),
117
- phone_type: run("phone_type", async (phone, args) => {
118
- if (typeof args.text !== "string" || args.text === "")
119
- throw new Error("text is the text to type");
120
- await phone.type(args.text);
121
- return { text: `Typed ${[...args.text].length} characters.` };
122
- }),
123
- phone_apps: run("phone_apps", async (phone) => {
124
- const { apps, foreground } = await phone.apps.list();
125
- const head = `${apps.length} app${apps.length === 1 ? "" : "s"}; ${foreground === null ? "none is in front" : `${foreground} is in front`}.`;
126
- return { text: [head, ...apps.map((app) => (app.name ? `${app.id} (${app.name})` : app.id))].join("\n") };
127
- }),
128
- phone_open: run("phone_open", async (phone, args) => {
129
- if (typeof args.id !== "string" || args.id === "")
130
- throw new Error("id is an app's id, as phone_apps lists it");
131
- await phone.apps.open(args.id);
132
- return { text: `Opened ${args.id}.` };
133
- }),
134
- [HANDOFF_TOOL]: handoffExecutor("phone"),
135
- });