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

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 (38) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/dist/host/proxy.d.ts +20 -4
  3. package/dist/host/proxy.js +53 -4
  4. package/dist/index.d.ts +1 -1
  5. package/dist/kernel/cap/index.d.ts +2 -2
  6. package/dist/kernel/cap/index.js +2 -2
  7. package/dist/kernel/cap/port.js +6 -3
  8. package/dist/kernel/cap/price.d.ts +6 -0
  9. package/dist/kernel/cap/price.js +14 -0
  10. package/dist/kernel/cap/rule.d.ts +8 -0
  11. package/dist/kernel/cap/rule.js +9 -0
  12. package/dist/kernel/cap/types.d.ts +2 -0
  13. package/dist/kernel/registry/computer-surface.generated.d.ts +9 -0
  14. package/dist/kernel/registry/computer-surface.generated.js +611 -0
  15. package/dist/kernel/registry/computer.d.ts +14 -0
  16. package/dist/kernel/registry/computer.js +67 -0
  17. package/dist/kernel/registry/defs.d.ts +1 -4
  18. package/dist/kernel/registry/defs.js +1 -13
  19. package/dist/kernel/registry/handoff.js +4 -4
  20. package/dist/kernel/registry/hands.d.ts +22 -115
  21. package/dist/kernel/registry/hands.js +0 -2
  22. package/dist/kernel/registry/index.d.ts +4 -4
  23. package/dist/kernel/registry/index.js +5 -5
  24. package/dist/kernel/registry/registry.d.ts +4 -5
  25. package/dist/kernel/registry/registry.js +27 -29
  26. package/dist/kernel/types.d.ts +2 -1
  27. package/dist/process/tools.d.ts +3 -1
  28. package/dist/process/tools.js +3 -3
  29. package/dist/run-booking.d.ts +3 -0
  30. package/dist/run-booking.js +7 -0
  31. package/dist/runner.d.ts +21 -2
  32. package/dist/runner.js +27 -10
  33. package/dist/types.d.ts +16 -1
  34. package/package.json +2 -2
  35. package/dist/kernel/registry/desktop.d.ts +0 -11
  36. package/dist/kernel/registry/desktop.js +0 -90
  37. package/dist/kernel/registry/phone.d.ts +0 -15
  38. package/dist/kernel/registry/phone.js +0 -135
package/dist/runner.js CHANGED
@@ -88,6 +88,10 @@ export function sessionSpendOf(records) {
88
88
  if (r.kind !== RUNNER_RECORDS.turn)
89
89
  continue;
90
90
  const data = r.data;
91
+ // A request is booked once: a second runner.turn of a turn already answered (two bookings of one session that each
92
+ // read it open, a cut written twice) counts no money and no request again.
93
+ if (typeof data.turn === "number" && answered.has(data.turn))
94
+ continue;
91
95
  const turn = data.turn ?? turns.find((t) => !answered.has(t)) ?? 0;
92
96
  answered.add(turn);
93
97
  // The figure it was booked at (bookRequest), as written. A record from before that has none: a request cut off with
@@ -122,9 +126,11 @@ export function sessionSpendOf(records) {
122
126
  }
123
127
  return { turns, held, bounds, hosts, answered, openHolds, spentUsd, figures, cost: { usd: unpriced > 0 ? null : soFarUsd, soFarUsd, unpriced } };
124
128
  }
125
- /** Whether a request answered with no price of its own (bookRequest's rule `answered`, or `answered:<label>`, its usd
126
- * null): booked at its hold for the cap, its cost unknown. */
127
- export const answeredUnpriced = (data) => data.usd === null && typeof data.rule === "string" && (data.rule === "answered" || data.rule.startsWith("answered:"));
129
+ /** Whether a request ended with no price of its own (usd null) under a rule that books it at a figure of the host's: an
130
+ * answer with no cost (bookRequest's rule `answered`, or `answered:<label>`: its hold), or one our side stopped
131
+ * (`stopped`: what streamed, an estimate) or lost (`lost`, `lost:<label>`: its hold). Each counts for the cap at that
132
+ * figure, but as a cost it is unknown, never an estimate stored as a known charge (the provider may bill otherwise). */
133
+ export const answeredUnpriced = (data) => data.usd === null && typeof data.rule === "string" && (data.rule === "answered" || data.rule.startsWith("answered:") || data.rule === "stopped" || data.rule === "lost" || data.rule.startsWith("lost:"));
128
134
  /** Whether a request was booked lost (bookRequest's rule `lost`, or `lost:<label>`): billed or not, no cost came in. */
129
135
  const bookedLost = (rule) => typeof rule === "string" && (rule === "lost" || rule.startsWith("lost:"));
130
136
  function bookingFor(writer, options) {
@@ -179,7 +185,7 @@ function bookingFor(writer, options) {
179
185
  // A paid request whose cost couldn't be recorded stops the booking itself, whether or not the host gave it a stop.
180
186
  let failed;
181
187
  const end = (reason, message, code) => options.stop ? options.stop(reason, message, code) : new HarnessRunError(reason, turns, 0, { maxTurns: limit, ...(message === undefined ? {} : { message }), ...(code === undefined ? {} : { refusal: code }) });
182
- const admit = async ({ model, inputTokensMax: measured, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, noted, inputTokensMaxWithoutNote, host, route }) => {
188
+ const admit = async ({ model, inputTokensMax: measured, inputTokensCounted, outputTokensAsked, outputTokensLeast, feeUsd, paid, side, unanswered, noted, inputTokensMaxWithoutNote, host, route }) => {
183
189
  let inputTokensMax = measured;
184
190
  const stopped = options.stopped?.(host === undefined ? {} : { host }) ?? failed;
185
191
  if (stopped)
@@ -189,8 +195,8 @@ function bookingFor(writer, options) {
189
195
  throw pausing;
190
196
  if (limit !== null && turns >= limit)
191
197
  throw end("turn_limit");
192
- const verdict = await options.beforeRequest?.({ ...node, model, turn: turns + 1, maxTurns: limit, ...(options.budgetUsd === undefined ? {} : { budgetUsd: options.budgetUsd }), spentUsd, inFlight: open.map((f) => ({ ...f })), inputTokensMax,
193
- ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }), ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }), ...(feeUsd === undefined ? {} : { feeUsd }), ...(paid ? { paid } : {}), ...(side ? { side } : {}), ...(noted ? { noted, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
198
+ const verdict = await options.beforeRequest?.({ ...node, model, turn: turns + 1, maxTurns: limit, ...(options.budgetUsd === undefined ? {} : { budgetUsd: options.budgetUsd }), spentUsd, inFlight: open.map((f) => ({ ...f })), inputTokensMax, ...(inputTokensCounted ? { inputTokensCounted } : {}),
199
+ ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }), ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }), ...(feeUsd === undefined ? {} : { feeUsd }), ...(paid ? { paid } : {}), ...(side ? { side } : {}), ...(unanswered ? { unanswered } : {}), ...(noted ? { noted, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
194
200
  if (verdict && "refuse" in verdict)
195
201
  throw end("refused", verdict.refuse, typeof verdict.code === "string" ? verdict.code : undefined);
196
202
  const hold = verdict && "holdUsd" in verdict ? heldFigure(verdict.holdUsd) : undefined;
@@ -254,14 +260,15 @@ function bookingFor(writer, options) {
254
260
  if (stoppedLate) {
255
261
  answered.add(turn);
256
262
  await write([{ kind: RUNNER_RECORDS.turn, data: { turn, usd: 0, unsent: true } }]).catch(() => undefined);
257
- emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: 0 }, ...(host === undefined ? {} : { host }), ended: { end: "nothing", label: "never_left" } });
263
+ await emit({ type: "request_end", turn, usage: { input: 0, output: 0, cacheRead: 0, usd: 0 }, ...(host === undefined ? {} : { host }), ended: { end: "nothing", label: "never_left" } });
258
264
  throw stoppedLate;
259
265
  }
260
- open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
266
+ open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(bound ? { boundUsd: bound } : {}), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }) });
261
267
  return { turn, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(withoutNote ? { noteDropped: true } : {}) };
262
268
  };
263
269
  const models = {
264
270
  ...(options.note ? { note: options.note } : {}),
271
+ ...(options.noteReturned ? { noteReturned: options.noteReturned } : {}),
265
272
  beforeRequest: (request) => {
266
273
  const admitted = admitting.then(() => admit(request));
267
274
  admitting = admitted.catch(() => { });
@@ -325,7 +332,9 @@ function bookingFor(writer, options) {
325
332
  }
326
333
  answered.add(turn);
327
334
  const hosted = hosts.get(turn);
328
- emit({ type: "request_end", turn, usage, ...(hosted === undefined ? {} : { host: hosted }), ...(ended ? { ended } : {}) });
335
+ // Awaited: a host that marks the request's end on its record writes it before the booking counts as settled, so a
336
+ // run's end never lands ahead of the mark that says its request was cut.
337
+ await emit({ type: "request_end", turn, usage, ...(hosted === undefined ? {} : { host: hosted }), ...(ended ? { ended } : {}) });
329
338
  },
330
339
  };
331
340
  // One booking of the cut requests at a time: a call made while one is writing waits for it, never books them again.
@@ -334,7 +343,13 @@ function bookingFor(writer, options) {
334
343
  // A paid request a crash cut off kept its runner.request and has no runner.turn: the provider may have billed it.
335
344
  // Each is booked once, as cut, at an unknown price, and the host is told as for any answered request, so its ledger
336
345
  // shows the possible spend instead of nothing. Booked, it is answered: a later attempt never books it again.
337
- // Only requests an earlier process admitted: one this process has in flight is not cut.
346
+ // Only requests an earlier process admitted: one this process has in flight is not cut. Read again here, just before
347
+ // the cut is written: another booking of this session (an earlier pass of this claim, or one racing it) may have
348
+ // booked it since this one opened, and a request is booked once.
349
+ const bookedSince = sessionSpendOf(await writer.read().catch(() => options.records)).answered;
350
+ for (const t of inherited)
351
+ if (bookedSince.has(t))
352
+ answered.add(t);
338
353
  const left = inherited.filter((t) => !answered.has(t));
339
354
  if (left.length === 0)
340
355
  return;
@@ -385,6 +400,8 @@ function bookingFor(writer, options) {
385
400
  models,
386
401
  turns: () => turns,
387
402
  spentUsd: () => spentUsd,
403
+ heldUsd: () => open.reduce((sum, flight) => (sum === null || flight.holdUsd === undefined ? null : sum + flight.holdUsd), 0),
404
+ boundUsd: () => open.reduce((sum, flight) => sum + (flight.boundUsd ?? 0), 0),
388
405
  bookCut() {
389
406
  cutting ??= bookCut().catch((error) => {
390
407
  cutting = undefined;
package/dist/types.d.ts CHANGED
@@ -60,7 +60,8 @@ export interface HostTool {
60
60
  }): Promise<{
61
61
  text: string;
62
62
  isError?: boolean;
63
- images?: readonly ToolImage[];
63
+ 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. */
64
+ structured?: JsonValue;
64
65
  parked?: true;
65
66
  }>;
66
67
  }
@@ -178,6 +179,9 @@ export interface ModelRequest {
178
179
  /** A side call, never its turn's own: on another model than the session's (a client's title, a summary), or the
179
180
  * host's own request beside the harness's (`host`). */
180
181
  side?: true;
182
+ /** On the session's model but no answer of the turn (a title, a summary, a child's request): booked as any request, but
183
+ * never the session's previous request for the cap's expected pricing, read or replaced. */
184
+ unanswered?: true;
181
185
  /** It carries the host's note (ModelPort.note) in its body: the note is delivered once this request is admitted.
182
186
  * `inputTokensMaxWithoutNote`: its input measured as its client sent it, before the note was placed. */
183
187
  noted?: true;
@@ -239,6 +243,9 @@ export interface ModelPort {
239
243
  * session's model proxy adds it to that request's body (ModelProxyHooks.note). `request`: that request as its client
240
244
  * sent it, measured before the note is placed (NoteRequest), so the host can price it as its admission will. */
241
245
  note?(model: string, request?: NoteRequest): string | undefined;
246
+ /** The note `note` gave back: the request that took it left before its admission (its client gone, a refusal or an
247
+ * error before `beforeRequest`), so it was never sent, and the host may give it to the next request at once. */
248
+ noteReturned?(note: string): void;
242
249
  }
243
250
  /** 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
251
  * at least, as the model proxy reads them (ModelRequest's figures, without the note). */
@@ -276,6 +283,12 @@ export interface SessionIO {
276
283
  * runs nothing; a park holds the call, writing nothing, until the session's signal is aborted (the run parks on a
277
284
  * person). Absent: every call runs. */
278
285
  gate?(call: GateCall, context?: unknown): Promise<GateAnswer>;
286
+ /** 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
287
+ * again at each ask, so a permission set while the session runs reaches its next request. For a tool no call of which
288
+ * reaches the gate before it runs: a provider-hosted search runs inside a model request, so the session offers it only
289
+ * while this says "allow" (a throw reads as "deny"). Absent: the host keeps no per-tool permissions, and what the
290
+ * session was opened with stands. */
291
+ permission?(tool: string): Promise<ToolPermission>;
279
292
  /** 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
293
  * 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
294
  * a side effect, the host's hooks on the result). An adapter hands every tool it adds through it. Absent: the host
@@ -299,6 +312,8 @@ export type GateAnswer = "allow" | {
299
312
  } | {
300
313
  readonly park: true;
301
314
  };
315
+ /** A tool's setting on the host (SessionIO.permission): it runs, it waits for a person's answer, or it is refused. */
316
+ export type ToolPermission = "allow" | "ask" | "deny";
302
317
  /** 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
318
  * only once its outcome is durable in the session's records, so a host never shows a result its store does not have;
304
319
  * `result` is the text recorded, when the adapter reports it. A call stopped before its outcome was recorded gets no
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.37",
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.37",
64
64
  "ajv": "8.18.0",
65
65
  "typebox": "1.3.27"
66
66
  },
@@ -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
- });