@introspection-ai/recipes 0.63.1 → 0.65.0

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 (147) hide show
  1. package/dist/agent-tool/arguments.d.ts +39 -0
  2. package/dist/agent-tool/arguments.d.ts.map +1 -0
  3. package/dist/agent-tool/arguments.generated.d.ts +4 -0
  4. package/dist/agent-tool/arguments.generated.d.ts.map +1 -0
  5. package/dist/agent-tool/arguments.generated.js +60 -0
  6. package/dist/agent-tool/arguments.generated.js.map +1 -0
  7. package/dist/agent-tool/arguments.js +8 -0
  8. package/dist/agent-tool/arguments.js.map +1 -0
  9. package/dist/agents.d.ts +28 -6
  10. package/dist/agents.d.ts.map +1 -1
  11. package/dist/agents.js +280 -47
  12. package/dist/agents.js.map +1 -1
  13. package/dist/api-bindings.d.ts.map +1 -1
  14. package/dist/api-bindings.js +2 -2
  15. package/dist/api-bindings.js.map +1 -1
  16. package/dist/artifact-review-tui.js +1 -1
  17. package/dist/artifact-review-tui.js.map +1 -1
  18. package/dist/artifact-viewer-tui.js +1 -1
  19. package/dist/artifact-viewer-tui.js.map +1 -1
  20. package/dist/artifact-viewer.d.ts.map +1 -1
  21. package/dist/artifact-viewer.js +3 -3
  22. package/dist/artifact-viewer.js.map +1 -1
  23. package/dist/batch/agent-batches.d.ts +53 -0
  24. package/dist/batch/agent-batches.d.ts.map +1 -0
  25. package/dist/batch/agent-batches.js +168 -0
  26. package/dist/batch/agent-batches.js.map +1 -0
  27. package/dist/batch/index.d.ts +2 -0
  28. package/dist/batch/index.d.ts.map +1 -1
  29. package/dist/batch/index.js +2 -1
  30. package/dist/batch/index.js.map +1 -1
  31. package/dist/batch/lines.d.ts.map +1 -1
  32. package/dist/batch/lines.js +4 -2
  33. package/dist/batch/lines.js.map +1 -1
  34. package/dist/child/agent-completions.d.ts +16 -1
  35. package/dist/child/agent-completions.d.ts.map +1 -1
  36. package/dist/child/agent-completions.js +31 -5
  37. package/dist/child/agent-completions.js.map +1 -1
  38. package/dist/child/agent-store.d.ts +2 -0
  39. package/dist/child/agent-store.d.ts.map +1 -1
  40. package/dist/child/agent-store.js.map +1 -1
  41. package/dist/child/agent.d.ts +9 -0
  42. package/dist/child/agent.d.ts.map +1 -1
  43. package/dist/child/agent.js +7 -0
  44. package/dist/child/agent.js.map +1 -1
  45. package/dist/child/arguments.d.ts +32 -0
  46. package/dist/child/arguments.d.ts.map +1 -0
  47. package/dist/child/arguments.generated.d.ts +4 -0
  48. package/dist/child/arguments.generated.d.ts.map +1 -0
  49. package/dist/child/arguments.generated.js +29 -0
  50. package/dist/child/arguments.generated.js.map +1 -0
  51. package/dist/child/arguments.js +8 -0
  52. package/dist/child/arguments.js.map +1 -0
  53. package/dist/child/inboxes.d.ts +21 -0
  54. package/dist/child/inboxes.d.ts.map +1 -0
  55. package/dist/child/inboxes.js +35 -0
  56. package/dist/child/inboxes.js.map +1 -0
  57. package/dist/child/messages.d.ts +202 -0
  58. package/dist/child/messages.d.ts.map +1 -0
  59. package/dist/child/messages.js +490 -0
  60. package/dist/child/messages.js.map +1 -0
  61. package/dist/child/run-processes.d.ts +14 -0
  62. package/dist/child/run-processes.d.ts.map +1 -0
  63. package/dist/child/run-processes.js +101 -0
  64. package/dist/child/run-processes.js.map +1 -0
  65. package/dist/child/session.d.ts +10 -0
  66. package/dist/child/session.d.ts.map +1 -1
  67. package/dist/child/session.js +34 -3
  68. package/dist/child/session.js.map +1 -1
  69. package/dist/child/streaming-usage.d.ts +40 -0
  70. package/dist/child/streaming-usage.d.ts.map +1 -0
  71. package/dist/child/streaming-usage.js +101 -0
  72. package/dist/child/streaming-usage.js.map +1 -0
  73. package/dist/documents/python.d.ts.map +1 -1
  74. package/dist/documents/python.js +2 -2
  75. package/dist/documents/python.js.map +1 -1
  76. package/dist/judges/cli-main.d.ts.map +1 -1
  77. package/dist/judges/cli-main.js +1 -1
  78. package/dist/judges/cli-main.js.map +1 -1
  79. package/dist/judges/run.d.ts.map +1 -1
  80. package/dist/judges/run.js +6 -2
  81. package/dist/judges/run.js.map +1 -1
  82. package/dist/judges/verdict.d.ts.map +1 -1
  83. package/dist/judges/verdict.js +1 -1
  84. package/dist/judges/verdict.js.map +1 -1
  85. package/dist/mcp/contract.d.ts.map +1 -1
  86. package/dist/mcp/contract.js +1 -3
  87. package/dist/mcp/contract.js.map +1 -1
  88. package/dist/mcp/daemon/client.d.ts.map +1 -1
  89. package/dist/mcp/daemon/client.js +1 -2
  90. package/dist/mcp/daemon/client.js.map +1 -1
  91. package/dist/mcp/pi-mcp-runtime.js +2 -2
  92. package/dist/mcp/pi-mcp-runtime.js.map +1 -1
  93. package/dist/mcp/pi-runtime.d.ts +3 -3
  94. package/dist/mcp/pi-runtime.d.ts.map +1 -1
  95. package/dist/mcp/pi-runtime.js +11 -20
  96. package/dist/mcp/pi-runtime.js.map +1 -1
  97. package/dist/mcp/tools.d.ts.map +1 -1
  98. package/dist/mcp/tools.js +1 -1
  99. package/dist/mcp/tools.js.map +1 -1
  100. package/dist/mcp-chunks/{chunk-OHAXEQ22.js → chunk-N6QLCGHR.js} +2 -2
  101. package/dist/mcp-chunks/{chunk-3UONQ24E.js → chunk-WVHEDCS6.js} +6 -4
  102. package/dist/mcp-chunks/chunk-ZH6FNTNJ.js +34 -0
  103. package/dist/mcp-chunks/{pi-mcp-runtime-V2OMZAIR.js → pi-mcp-runtime-W5OLELOO.js} +34 -27
  104. package/dist/mcp-chunks/{server-6DQUPUFW.js → server-UZ5OMTWP.js} +3 -3
  105. package/dist/mcp-daemon.js +3 -3
  106. package/dist/mcp-run-worker.js +2 -2
  107. package/dist/pi-extension.d.ts +2 -0
  108. package/dist/pi-extension.d.ts.map +1 -1
  109. package/dist/pi-extension.js +241 -43
  110. package/dist/pi-extension.js.map +1 -1
  111. package/dist/recipe/manifest.generated.d.ts +1 -1
  112. package/dist/recipe/manifest.generated.js +1 -1
  113. package/dist/recipe/package.d.ts +2 -0
  114. package/dist/recipe/package.d.ts.map +1 -1
  115. package/dist/recipe/package.js +15 -21
  116. package/dist/recipe/package.js.map +1 -1
  117. package/dist/recipe/python.d.ts.map +1 -1
  118. package/dist/recipe/python.js +8 -5
  119. package/dist/recipe/python.js.map +1 -1
  120. package/dist/run-controller.d.ts +5 -0
  121. package/dist/run-controller.d.ts.map +1 -1
  122. package/dist/run-controller.js +89 -12
  123. package/dist/run-controller.js.map +1 -1
  124. package/dist/session.d.ts +14 -0
  125. package/dist/session.d.ts.map +1 -1
  126. package/dist/session.js +21 -3
  127. package/dist/session.js.map +1 -1
  128. package/dist/shell-quote.d.ts +3 -0
  129. package/dist/shell-quote.d.ts.map +1 -0
  130. package/dist/shell-quote.js +5 -0
  131. package/dist/shell-quote.js.map +1 -0
  132. package/dist/skill-progress.d.ts +12 -1
  133. package/dist/skill-progress.d.ts.map +1 -1
  134. package/dist/skill-progress.js +11 -4
  135. package/dist/skill-progress.js.map +1 -1
  136. package/docs/agent-batch.md +87 -0
  137. package/docs/agent-composition.md +49 -19
  138. package/docs/batch.md +7 -0
  139. package/docs/documents/README.md +1 -1
  140. package/docs/mcp-auth.md +2 -1
  141. package/docs/mcp-configuration.md +2 -3
  142. package/docs/productivity/google.md +27 -15
  143. package/docs/recipe-format.md +4 -4
  144. package/package.json +15 -14
  145. package/python/shared/pyproject.toml +2 -2
  146. package/python/shared/uv.lock +30 -30
  147. package/dist/mcp-chunks/chunk-V65N6VX7.js +0 -33
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The arguments the `agent` tool takes, as the model sees them.
3
+ * `scripts/generate-tool-schemas.mjs` turns `AgentArguments` into the JSON
4
+ * Schema in `arguments.generated.ts`: a field's doc comment is its
5
+ * description.
6
+ */
7
+ export interface AgentArguments {
8
+ /** What to do; omit it to start one child with name and prompt. */
9
+ action?: "start" | "status" | "wait" | "message" | "interrupt" | "close" | "batch";
10
+ /** The agent role to start, or to run a batch with. */
11
+ name?: string;
12
+ /** What a started child is asked. */
13
+ prompt?: string;
14
+ /** Tells concurrent runs apart. */
15
+ label?: string;
16
+ /** The run id `start` returned, or the batch id `batch` returned. */
17
+ id?: string;
18
+ /** With message: what to tell the child. */
19
+ message?: string;
20
+ /** With start: return the child's result in this call. */
21
+ wait?: boolean;
22
+ /** With batch: the rows ({ custom_id, prompt, metadata? }), or a .jsonl file of them. */
23
+ input?: string | unknown[];
24
+ /**
25
+ * With batch: rows at once, within the session's limit.
26
+ * @minimum 1
27
+ */
28
+ concurrency?: number;
29
+ /** With batch: where results.jsonl is written and resumed from. */
30
+ directory?: string;
31
+ /** With close on a batch: steer the running rows to wrap up, then close those still running after grace_seconds. Without it the running rows finish. */
32
+ stop?: boolean;
33
+ /**
34
+ * With close and stop: seconds the running rows get to reply. Default 60.
35
+ * @minimum 0
36
+ */
37
+ grace_seconds?: number;
38
+ }
39
+ //# sourceMappingURL=arguments.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"arguments.d.ts","sourceRoot":"","sources":["../../src/agent-tool/arguments.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,WAAW,cAAc;IAC7B,mEAAmE;IACnE,MAAM,CAAC,EACL,OAAO,GAAG,QAAQ,GAAG,MAAM,GAAG,SAAS,GAAG,WAAW,GAAG,OAAO,GAAG,OAAO,CAAC;IAC5E,uDAAuD;IACvD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,qCAAqC;IACrC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,mCAAmC;IACnC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,qEAAqE;IACrE,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,4CAA4C;IAC5C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,0DAA0D;IAC1D,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,yFAAyF;IACzF,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,EAAE,CAAC;IAC3B;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,mEAAmE;IACnE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wJAAwJ;IACxJ,IAAI,CAAC,EAAE,OAAO,CAAC;IACf;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB"}
@@ -0,0 +1,4 @@
1
+ import type { ArgumentsSchema } from "../command-parameters.js";
2
+ import type { AgentArguments } from "./arguments.js";
3
+ export declare const AGENT_ARGUMENTS: ArgumentsSchema<AgentArguments>;
4
+ //# sourceMappingURL=arguments.generated.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"arguments.generated.d.ts","sourceRoot":"","sources":["../../src/agent-tool/arguments.generated.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAErD,eAAO,MAAM,eAAe,EAgEvB,eAAe,CAAC,cAAc,CAAC,CAAC"}
@@ -0,0 +1,60 @@
1
+ export const AGENT_ARGUMENTS = {
2
+ type: "object",
3
+ properties: {
4
+ action: {
5
+ type: "string",
6
+ enum: [
7
+ "start",
8
+ "status",
9
+ "wait",
10
+ "message",
11
+ "interrupt",
12
+ "close",
13
+ "batch",
14
+ ],
15
+ description: "What to do; omit it to start one child with name and prompt.",
16
+ },
17
+ name: {
18
+ type: "string",
19
+ description: "The agent role to start, or to run a batch with.",
20
+ },
21
+ prompt: { type: "string", description: "What a started child is asked." },
22
+ label: { type: "string", description: "Tells concurrent runs apart." },
23
+ id: {
24
+ type: "string",
25
+ description: "The run id `start` returned, or the batch id `batch` returned.",
26
+ },
27
+ message: {
28
+ type: "string",
29
+ description: "With message: what to tell the child.",
30
+ },
31
+ wait: {
32
+ type: "boolean",
33
+ description: "With start: return the child's result in this call.",
34
+ },
35
+ input: {
36
+ anyOf: [{ type: "string" }, { type: "array", items: {} }],
37
+ description: "With batch: the rows ({ custom_id, prompt, metadata? }), or a .jsonl file of them.",
38
+ },
39
+ concurrency: {
40
+ type: "number",
41
+ description: "With batch: rows at once, within the session's limit.",
42
+ minimum: 1,
43
+ },
44
+ directory: {
45
+ type: "string",
46
+ description: "With batch: where results.jsonl is written and resumed from.",
47
+ },
48
+ stop: {
49
+ type: "boolean",
50
+ description: "With close on a batch: steer the running rows to wrap up, then close those still running after grace_seconds. Without it the running rows finish.",
51
+ },
52
+ grace_seconds: {
53
+ type: "number",
54
+ description: "With close and stop: seconds the running rows get to reply. Default 60.",
55
+ minimum: 0,
56
+ },
57
+ },
58
+ additionalProperties: false,
59
+ };
60
+ //# sourceMappingURL=arguments.generated.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"arguments.generated.js","sourceRoot":"","sources":["../../src/agent-tool/arguments.generated.ts"],"names":[],"mappings":"AAIA,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE;QACV,MAAM,EAAE;YACN,IAAI,EAAE,QAAQ;YACd,IAAI,EAAE;gBACJ,OAAO;gBACP,QAAQ;gBACR,MAAM;gBACN,SAAS;gBACT,WAAW;gBACX,OAAO;gBACP,OAAO;aACR;YACD,WAAW,EACT,8DAA8D;SACjE;QACD,IAAI,EAAE;YACJ,IAAI,EAAE,QAAQ;YACd,WAAW,EAAE,kDAAkD;SAChE;QACD,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,gCAAgC,EAAE;QACzE,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,8BAA8B,EAAE;QACtE,EAAE,EAAE;YACF,IAAI,EAAE,QAAQ;YACd,WAAW,EACT,gEAAgE;SACnE;QACD,OAAO,EAAE;YACP,IAAI,EAAE,QAAQ;YACd,WAAW,EAAE,uCAAuC;SACrD;QACD,IAAI,EAAE;YACJ,IAAI,EAAE,SAAS;YACf,WAAW,EAAE,qDAAqD;SACnE;QACD,KAAK,EAAE;YACL,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC;YACzD,WAAW,EACT,oFAAoF;SACvF;QACD,WAAW,EAAE;YACX,IAAI,EAAE,QAAQ;YACd,WAAW,EAAE,uDAAuD;YACpE,OAAO,EAAE,CAAC;SACX;QACD,SAAS,EAAE;YACT,IAAI,EAAE,QAAQ;YACd,WAAW,EACT,8DAA8D;SACjE;QACD,IAAI,EAAE;YACJ,IAAI,EAAE,SAAS;YACf,WAAW,EACT,mJAAmJ;SACtJ;QACD,aAAa,EAAE;YACb,IAAI,EAAE,QAAQ;YACd,WAAW,EACT,yEAAyE;YAC3E,OAAO,EAAE,CAAC;SACX;KACF;IACD,oBAAoB,EAAE,KAAK;CACO,CAAC"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The arguments the `agent` tool takes, as the model sees them.
3
+ * `scripts/generate-tool-schemas.mjs` turns `AgentArguments` into the JSON
4
+ * Schema in `arguments.generated.ts`: a field's doc comment is its
5
+ * description.
6
+ */
7
+ export {};
8
+ //# sourceMappingURL=arguments.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"arguments.js","sourceRoot":"","sources":["../../src/agent-tool/arguments.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
package/dist/agents.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import { type AgentSessionEvent, type ToolDefinition } from "@earendil-works/pi-coding-agent";
2
+ import { type UsagePricing } from "./child/agent-completions.js";
3
+ import { type AgentInbox, type ReportedUsage } from "./child/messages.js";
4
+ import type { AgentBatches } from "./batch/agent-batches.js";
2
5
  /** Portable lifecycle contract for Recipe agent runs. */
3
6
  export type AgentRunStatus = "running" | "completed" | "failed" | "interrupted" | "closed";
4
7
  export interface AgentNestedToolSummary {
@@ -14,6 +17,7 @@ export interface AgentRunUsage {
14
17
  cache_read_tokens: number;
15
18
  cache_write_tokens: number;
16
19
  cost_usd: number;
20
+ pricing?: UsagePricing;
17
21
  }
18
22
  export interface AgentRunSummary {
19
23
  agent_run_id: string;
@@ -22,23 +26,32 @@ export interface AgentRunSummary {
22
26
  label: string;
23
27
  prompt: string;
24
28
  status: AgentRunStatus;
29
+ /** A running run still waiting for a slot under the session's subagent limit. */
30
+ queued?: boolean;
25
31
  started_at: number;
26
32
  completed_at?: number;
27
33
  last_activity_at: number;
28
34
  current_tool?: string;
35
+ /** The run's latest `send_message` status note. */
36
+ status_text?: string;
37
+ /** The latest total it reported for work it ran elsewhere, apart from `usage`. */
38
+ reported_usage?: ReportedUsage;
39
+ /** What the running tool is doing, for display: a bash call's command; the tool's name otherwise. */
40
+ current_activity?: string;
29
41
  nested_tools?: AgentNestedToolSummary[];
30
42
  output_preview?: string;
31
43
  output?: string;
32
44
  error?: string;
33
45
  usage?: AgentRunUsage;
34
46
  }
35
- /** `2.3k` for 2300 tokens, the count as it is under a thousand. */
36
- export declare function compactTokens(count: number): string;
37
47
  /**
38
- * A run's progress in one line: `↓ 2.3k tokens · $0.09 · 00:40 · edit`, its
39
- * output tokens, cost, its time on the footer's clock and, while it runs, the
40
- * tool it is in.
48
+ * What a running tool is doing, for a run's progress line: a `bash` call's
49
+ * command, its first line without a leading `cd … &&` or `set -e;`, cut to
50
+ * about 40 characters; any other tool's name.
41
51
  */
52
+ export declare function toolActivity(name: string, args: unknown): string;
53
+ /** A run's line in the agents widget: `▸ explorer (a) · ↑1k ↓200 · $0.010 · 00:12 · sleep 3`. */
54
+ export declare function agentLine(run: AgentRunSummary): string;
42
55
  export declare function runProgress(run: AgentRunSummary, now?: number): string;
43
56
  /**
44
57
  * Deepest delegated run. The root session is depth 0, its children depth 1,
@@ -88,6 +101,10 @@ export interface AgentRunController {
88
101
  }
89
102
  export declare function createAgentTool(controller: AgentRunController, agents: ReadonlyMap<string, unknown>, opts?: {
90
103
  acknowledgeCompletions?(ids: readonly string[]): void;
104
+ /** This agent's messages: one arriving ends a wait in progress. */
105
+ inbox?: AgentInbox;
106
+ /** Batches of runs, where the host offers them. */
107
+ batches?: AgentBatches;
91
108
  }): ToolDefinition;
92
109
  /**
93
110
  * The runs a delegated session starts, settled before its result is read.
@@ -103,6 +120,7 @@ export declare function createAgentTool(controller: AgentRunController, agents:
103
120
  export interface DelegatedRuns {
104
121
  readonly agentToolOptions: {
105
122
  acknowledgeCompletions(ids: readonly string[]): void;
123
+ inbox?: AgentInbox;
106
124
  };
107
125
  /**
108
126
  * `send` prompts the session once; returning `false` ends the loop (a turn
@@ -116,5 +134,9 @@ export interface DelegatedRuns {
116
134
  agentRuns?: AgentRunController;
117
135
  }): Promise<void>;
118
136
  }
119
- export declare function createDelegatedRuns(): DelegatedRuns;
137
+ /**
138
+ * `inbox` is the session's messages: one arriving while the session waits
139
+ * between turns for its runs prompts it with the message.
140
+ */
141
+ export declare function createDelegatedRuns(inbox?: AgentInbox): DelegatedRuns;
120
142
  //# sourceMappingURL=agents.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"agents.d.ts","sourceRoot":"","sources":["../src/agents.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACpB,MAAM,iCAAiC,CAAC;AASzC,yDAAyD;AACzD,MAAM,MAAM,cAAc,GACxB,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,aAAa,GAAG,QAAQ,CAAC;AAEhE,MAAM,WAAW,sBAAsB;IACrC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACrC;AAED,iEAAiE;AACjE,MAAM,WAAW,aAAa;IAC5B,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,kBAAkB,EAAE,MAAM,CAAC;IAC3B,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,eAAe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C,IAAI,CAAC,CAAC;CACvE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,CAAC,EAAE,UAAU,GAAG,aAAa,CAuGrE"}
package/dist/agents.js CHANGED
@@ -1,25 +1,77 @@
1
1
  import { defineTool, } from "@earendil-works/pi-coding-agent";
2
- import { Type } from "typebox";
3
- import { OUTPUT_PREVIEW_CHARS, renderCompletionNotice, } from "./child/agent-completions.js";
2
+ import { costText, tokenText, OUTPUT_PREVIEW_CHARS, renderCompletionNotice, } from "./child/agent-completions.js";
3
+ import { renderAgentMessages, } from "./child/messages.js";
4
+ import { AGENT_ARGUMENTS } from "./agent-tool/arguments.generated.js";
4
5
  import { elapsed } from "./skill-progress.js";
5
- /** `2.3k` for 2300 tokens, the count as it is under a thousand. */
6
- export function compactTokens(count) {
7
- return count < 1000 ? String(count) : `${(count / 1000).toFixed(1)}k`;
6
+ const ACTIVITY_CHARS = 40;
7
+ /**
8
+ * What a running tool is doing, for a run's progress line: a `bash` call's
9
+ * command, its first line without a leading `cd … &&` or `set -e;`, cut to
10
+ * about 40 characters; any other tool's name.
11
+ */
12
+ export function toolActivity(name, args) {
13
+ const command = args && typeof args === "object" && !Array.isArray(args)
14
+ ? args.command
15
+ : undefined;
16
+ if (name !== "bash" || typeof command !== "string")
17
+ return name;
18
+ let line = command.trim().split("\n")[0].trim();
19
+ for (;;) {
20
+ const next = line
21
+ .replace(/^set -e\s*;\s*/, "")
22
+ .replace(/^cd\s+[^;&|]*?\s*&&\s*/, "")
23
+ .trim();
24
+ if (next === line)
25
+ break;
26
+ line = next;
27
+ }
28
+ if (!line)
29
+ return name;
30
+ return line.length > ACTIVITY_CHARS
31
+ ? `${line.slice(0, ACTIVITY_CHARS - 1).trimEnd()}…`
32
+ : line;
8
33
  }
9
34
  /**
10
35
  * A run's progress in one line: `↓ 2.3k tokens · $0.09 · 00:40 · edit`, its
11
- * output tokens, cost, its time on the footer's clock and, while it runs, the
12
- * tool it is in.
36
+ * output tokens, cost, its time on the footer's clock and, while it runs, its
37
+ * the command or tool it is in, else its latest status note.
13
38
  */
39
+ const STATUS_LINE_CHARS = 60;
40
+ /** A status note's first line, cut to fit a progress line. */
41
+ function statusLine(text) {
42
+ const line = text.trim().split("\n")[0] ?? "";
43
+ return line.length > STATUS_LINE_CHARS
44
+ ? `${line.slice(0, STATUS_LINE_CHARS - 1)}…`
45
+ : line;
46
+ }
47
+ /** A run's line in the agents widget: `▸ explorer (a) · ↑1k ↓200 · $0.010 · 00:12 · sleep 3`. */
48
+ export function agentLine(run) {
49
+ const label = run.label && run.label !== run.agent_name ? ` (${run.label})` : "";
50
+ return `▸ ${run.agent_name}${label} · ${runProgress(run)}`;
51
+ }
14
52
  export function runProgress(run, now = Date.now()) {
53
+ if (run.queued)
54
+ return "queued";
15
55
  const parts = [];
16
56
  if (run.usage) {
17
- parts.push(`↓ ${compactTokens(run.usage.output_tokens)} tokens`);
18
- parts.push(`$${run.usage.cost_usd.toFixed(2)}`);
57
+ parts.push(tokenText(run.usage.input_tokens, run.usage.output_tokens));
58
+ const cost = costText(run.usage.cost_usd, run.usage.pricing);
59
+ if (cost)
60
+ parts.push(cost);
61
+ }
62
+ const reported = run.reported_usage;
63
+ if (reported) {
64
+ const tokens = tokenText(reported.input_tokens, reported.output_tokens);
65
+ parts.push(["reported", tokens, costText(reported.cost_usd)]
66
+ .filter(Boolean)
67
+ .join(" "));
19
68
  }
20
69
  parts.push(elapsed((run.completed_at ?? now) - run.started_at));
21
- if (run.status === "running" && run.current_tool)
22
- parts.push(run.current_tool);
70
+ const activity = run.current_activity ??
71
+ run.current_tool ??
72
+ (run.status_text ? statusLine(run.status_text) : undefined);
73
+ if (run.status === "running" && activity)
74
+ parts.push(activity);
23
75
  return parts.join(" · ");
24
76
  }
25
77
  /**
@@ -56,24 +108,6 @@ export function notifyAgentRunEvent(observer, event) {
56
108
  // successful child event into a failed delegated run.
57
109
  }
58
110
  }
59
- const AgentToolParams = Type.Object({
60
- action: Type.Optional(Type.Union([
61
- Type.Literal("start"),
62
- Type.Literal("status"),
63
- Type.Literal("wait"),
64
- Type.Literal("message"),
65
- Type.Literal("interrupt"),
66
- Type.Literal("close"),
67
- ])),
68
- name: Type.Optional(Type.String()),
69
- prompt: Type.Optional(Type.String()),
70
- label: Type.Optional(Type.String()),
71
- id: Type.Optional(Type.String({ description: "The run id `start` returned." })),
72
- message: Type.Optional(Type.String()),
73
- wait: Type.Optional(Type.Boolean({
74
- description: "With start: return the child's result in this call.",
75
- })),
76
- });
77
111
  function terminal(run) {
78
112
  return run.status !== "running";
79
113
  }
@@ -129,6 +163,44 @@ function errorResult(text, controller) {
129
163
  function unknownRun(id, controller) {
130
164
  return errorResult(`Unknown agent run ${id}: use the run id \`start\` returned.`, controller);
131
165
  }
166
+ /** `batch batch-1a2b (explorer) [6 rows · 2 running · 1 queued] → <results>`, or its outcome once it ends. */
167
+ function batchLine(batch) {
168
+ const state = batch.error
169
+ ? `failed: ${batch.error}`
170
+ : batch.outcome
171
+ ? `${batch.outcome.completed} succeeded · ${batch.outcome.failed} failed · ${batch.outcome.already_completed} already done${batch.outcome.not_started ? ` · ${batch.outcome.not_started} not started` : ""}`
172
+ : `${batch.running} running · ${batch.queued} queued`;
173
+ return `batch ${batch.batch_id} (${batch.agent}) [${batch.rows} rows · ${state}] results: ${batch.results_path}`;
174
+ }
175
+ const WHILE_YOU_WAITED = "Messages while you waited, in the order they were sent:";
176
+ /** A wait's result for messages that ended it before what it waited on. */
177
+ function stillRunning(messages, line) {
178
+ return [
179
+ ...(messages.length > 0
180
+ ? [WHILE_YOU_WAITED, renderAgentMessages(messages), ""]
181
+ : ["A message arrived while you waited; it follows this result.", ""]),
182
+ `${line} is still running; wait again to keep waiting.`,
183
+ ].join("\n");
184
+ }
185
+ /** Resolves when `signal` aborts, at once when it already has; never without one. */
186
+ function untilAborted(signal) {
187
+ return new Promise((resolve) => {
188
+ if (!signal)
189
+ return;
190
+ if (signal.aborted)
191
+ resolve(undefined);
192
+ else
193
+ signal.addEventListener("abort", () => resolve(undefined), {
194
+ once: true,
195
+ });
196
+ });
197
+ }
198
+ function batchResult(batch, text) {
199
+ return {
200
+ content: [{ type: "text", text }],
201
+ details: { batch },
202
+ };
203
+ }
132
204
  const UNKNOWN_RUN = /unknown agent run|agent run not found/i;
133
205
  export function createAgentTool(controller, agents, opts = {}) {
134
206
  const closedRunIds = new Set();
@@ -146,8 +218,13 @@ export function createAgentTool(controller, agents, opts = {}) {
146
218
  `Available agent roles: ${[...agents.keys()].join(", ")}. Pass a role as name; use label to distinguish concurrent runs.`,
147
219
  "Use status, message, interrupt, or close with the run id `start` returned.",
148
220
  "Message steers a running child at the next message boundary; on a settled child it resumes the same session.",
221
+ ...(opts.batches
222
+ ? [
223
+ "Batch runs one child per row with name and input, each labelled by its custom_id; wait, status or close take the batch id it returns.",
224
+ ]
225
+ : []),
149
226
  ].join(" "),
150
- parameters: AgentToolParams,
227
+ parameters: AGENT_ARGUMENTS,
151
228
  async execute(_callId, rawParams, signal, onUpdate) {
152
229
  const params = rawParams;
153
230
  try {
@@ -173,6 +250,41 @@ export function createAgentTool(controller, agents, opts = {}) {
173
250
  return await waitFor(run, signal);
174
251
  return result(run, `Started ${runLine(run)}`);
175
252
  }
253
+ if (params.action === "batch") {
254
+ if (!opts.batches) {
255
+ return errorResult("This session runs no batches.", controller);
256
+ }
257
+ if (!params.name || params.input === undefined) {
258
+ return errorResult("A batch requires name and input.", controller);
259
+ }
260
+ if (!agents.has(params.name)) {
261
+ return errorResult(`Unknown agent "${params.name}". Available: ${[...agents.keys()].join(", ")}`, controller);
262
+ }
263
+ const batch = opts.batches.start({
264
+ name: params.name,
265
+ input: params.input,
266
+ ...(params.concurrency !== undefined
267
+ ? { concurrency: params.concurrency }
268
+ : {}),
269
+ ...(params.directory ? { directory: params.directory } : {}),
270
+ });
271
+ return batchResult(batch, `Started ${batchLine(batch)}`);
272
+ }
273
+ if (params.id && opts.batches?.has(params.id)) {
274
+ if (params.action === "wait") {
275
+ return await waitForBatch(params.id, signal);
276
+ }
277
+ if (params.action === "close" && params.stop) {
278
+ const batch = await opts.batches.stopNow(params.id, (params.grace_seconds ?? 60) * 1000);
279
+ return batchResult(batch, `Stopped ${batchLine(batch)}`);
280
+ }
281
+ if (params.action === "close") {
282
+ const batch = opts.batches.stop(params.id);
283
+ return batchResult(batch, `Stopping ${batchLine(batch)}: no new row starts, and the rows running finish.`);
284
+ }
285
+ const batch = opts.batches.summary(params.id);
286
+ return batchResult(batch, batchLine(batch));
287
+ }
176
288
  if (params.action === "status" && !params.id) {
177
289
  const runs = controller.list();
178
290
  runs.forEach(acknowledge);
@@ -232,42 +344,125 @@ export function createAgentTool(controller, agents, opts = {}) {
232
344
  }
233
345
  },
234
346
  });
347
+ /**
348
+ * Wait for `settle`, which ends when its signal aborts, unless a message
349
+ * arrives first and `onMessage` answers with it. Either way the wait ends
350
+ * with what the inbox held, in send order.
351
+ */
352
+ async function waitOrMessage(settle, signal, onMessage,
353
+ // Whether what it waited on settled as a failure: its messages then stay in the inbox.
354
+ failed = () => false) {
355
+ const inbox = opts.inbox;
356
+ // Without an inbox nothing else ends the wait, so `settle` gets the caller's signal as it is.
357
+ if (!inbox)
358
+ return { value: await settle(signal), held: [] };
359
+ const listening = new AbortController();
360
+ const stopListening = () => listening.abort();
361
+ signal?.addEventListener("abort", stopListening, { once: true });
362
+ // A listener added to an aborted signal never fires.
363
+ if (signal?.aborted)
364
+ listening.abort();
365
+ const wait = inbox.waitStarted(listening.signal);
366
+ const arrived = wait.arrived.then(() => ({ arrived: true }));
367
+ const settled = settle(listening.signal);
368
+ try {
369
+ const first = await Promise.race([
370
+ settled.then((value) => ({ value })),
371
+ arrived,
372
+ ]);
373
+ if ("value" in first && failed(first.value)) {
374
+ await wait.end({ keep: true });
375
+ return { value: first.value, held: [] };
376
+ }
377
+ const held = await wait.end();
378
+ if ("value" in first)
379
+ return { value: first.value, held };
380
+ const reply = signal?.aborted ? undefined : onMessage(held);
381
+ if (reply === undefined)
382
+ return { value: await settled, held };
383
+ return { reply };
384
+ }
385
+ finally {
386
+ signal?.removeEventListener("abort", stopListening);
387
+ listening.abort();
388
+ }
389
+ }
390
+ /** The follow-ups held during a wait, in send order, to end its result with. */
391
+ function heldMessages(held) {
392
+ return held.length
393
+ ? `\n\n${WHILE_YOU_WAITED}\n${renderAgentMessages(held)}`
394
+ : "";
395
+ }
396
+ /** Block until the batch ends, or a message arrives; an abort stops the wait, never the batch. */
397
+ async function waitForBatch(id, signal) {
398
+ const batches = opts.batches;
399
+ const end = await waitOrMessage((stop) => Promise.race([batches.settled(id), untilAborted(stop)]), signal, (messages) => {
400
+ const batch = batches.summary(id);
401
+ return batchResult(batch, stillRunning(messages, batchLine(batch)));
402
+ });
403
+ if ("reply" in end)
404
+ return end.reply;
405
+ if (end.value)
406
+ return batchResult(end.value, `${batchLine(end.value)}${heldMessages(end.held)}`);
407
+ const batch = batches.summary(id);
408
+ return batchResult(batch, `Stopped waiting: ${batchLine(batch)} keeps running.${heldMessages(end.held)}`);
409
+ }
235
410
  /**
236
411
  * Block until the run settles. An abort stops the wait, never the run: it
237
412
  * keeps working and its result is pushed when it finishes.
238
413
  */
239
414
  async function waitFor(target, signal, onUpdate) {
240
415
  const id = typeof target === "string" ? target : target.agent_run_id;
416
+ const current = () => controller.get(id) ?? (typeof target === "string" ? null : target);
241
417
  // The wait is the row on screen while it lasts, so it shows the run's progress.
242
418
  const showProgress = () => {
243
- const current = controller.get(id);
244
- if (current && !terminal(current))
245
- onUpdate?.(result(current, `Waiting for ${runLine(current)}`));
419
+ const run = controller.get(id);
420
+ if (run && !terminal(run))
421
+ onUpdate?.(result(run, `Waiting for ${runLine(run)}`));
246
422
  };
247
423
  const progress = onUpdate ? setInterval(showProgress, 1000) : undefined;
248
424
  progress?.unref?.();
249
425
  showProgress();
250
- let run;
426
+ let end;
251
427
  try {
252
- run = await controller.wait(id, signal);
428
+ // A message ends the wait whichever run it is on: Pi would steer it only
429
+ // after this call returns, and the run may take far longer.
430
+ end = await waitOrMessage((stop) => controller.wait(id, stop).then((summary) => ({ summary }), (error) => ({ error })), signal, (messages) => {
431
+ const run = current();
432
+ return run
433
+ ? result(run, stillRunning(messages, runLine(run)))
434
+ : undefined;
435
+ },
436
+ // The wait fails (it throws below), so what it took stays for the next one.
437
+ (outcome) => "error" in outcome && (!signal?.aborted || !current()));
253
438
  }
254
- catch (error) {
255
- const fallback = controller.get(id) ?? (typeof target === "string" ? null : target);
439
+ finally {
440
+ clearInterval(progress);
441
+ }
442
+ if ("reply" in end)
443
+ return end.reply;
444
+ let run;
445
+ if ("error" in end.value) {
446
+ const fallback = current();
256
447
  if (!signal?.aborted || !fallback)
257
- throw error;
448
+ throw end.value.error;
258
449
  run = fallback;
259
450
  }
260
- finally {
261
- clearInterval(progress);
451
+ else {
452
+ run = end.value.summary;
262
453
  }
263
454
  if (!terminal(run)) {
264
- return result(run, `Stopped waiting: ${runLine(run)} keeps working; its result reaches you when it finishes.`);
455
+ return result(run, `Stopped waiting: ${runLine(run)} keeps working; its result reaches you when it finishes.${heldMessages(end.held)}`);
265
456
  }
266
457
  acknowledge(run);
267
- return result(run, statusBlock(run));
458
+ return result(run, `${statusBlock(run)}${heldMessages(end.held)}`);
268
459
  }
269
460
  }
270
- export function createDelegatedRuns() {
461
+ /**
462
+ * `inbox` is the session's messages: one arriving while the session waits
463
+ * between turns for its runs prompts it with the message.
464
+ */
465
+ export function createDelegatedRuns(inbox) {
271
466
  // A run resumed with `message` keeps its id, and its next result is new: a
272
467
  // result is keyed by run and by when the run last did anything, which every
273
468
  // controller reports and new work always moves.
@@ -290,6 +485,7 @@ export function createDelegatedRuns() {
290
485
  seen.add(completion(run));
291
486
  }
292
487
  },
488
+ ...(inbox ? { inbox } : {}),
293
489
  },
294
490
  async run(session, prompt, send) {
295
491
  runs = session.agentRuns;
@@ -298,23 +494,60 @@ export function createDelegatedRuns() {
298
494
  let settled = false;
299
495
  try {
300
496
  while (next !== null) {
301
- const input = next;
497
+ // What arrived since the last turn opens this one, after what it was given.
498
+ const opening = (await inbox?.turnStarted()) ?? [];
499
+ const input = [
500
+ next,
501
+ ...(opening.length > 0 ? [renderAgentMessages(opening)] : []),
502
+ ]
503
+ .filter((part) => part.length > 0)
504
+ .join("\n\n");
302
505
  next = null;
303
- if ((await send(input)) === false || stopped)
506
+ if (stopped) {
507
+ await inbox?.turnEnded(opening);
508
+ return;
509
+ }
510
+ const sent = await send(input);
511
+ // Messages it was handed and did not read come back, ahead of what is held.
512
+ const held = (await inbox?.turnEnded()) ?? [];
513
+ if (sent === false || stopped)
304
514
  return;
515
+ if (held.length > 0) {
516
+ next = "";
517
+ continue;
518
+ }
305
519
  let running = own().filter((run) => run.status === "running");
306
520
  while (running.length > 0) {
307
- await Promise.all(running.map((run) => runs.wait(run.agent_run_id).catch(() => undefined)));
521
+ const listening = new AbortController();
522
+ const settledAll = Promise.all(running.map((run) => runs
523
+ .wait(run.agent_run_id, listening.signal)
524
+ .catch(() => undefined))).then(() => undefined);
525
+ const wait = inbox?.waitStarted(listening.signal);
526
+ await Promise.race([settledAll, ...(wait ? [wait.arrived] : [])]);
527
+ listening.abort();
528
+ const received = (await wait?.end()) ?? [];
308
529
  if (stopped)
309
530
  return;
531
+ if (received.length > 0) {
532
+ next = renderAgentMessages(received);
533
+ break;
534
+ }
310
535
  running = own().filter((run) => run.status === "running");
311
536
  }
537
+ if (next !== null)
538
+ continue;
312
539
  const unseen = own().filter((run) => (run.status === "completed" || run.status === "failed") &&
313
540
  !seen.has(completion(run)));
314
541
  for (const run of unseen)
315
542
  seen.add(completion(run));
316
- if (unseen.length > 0)
543
+ if (unseen.length > 0) {
317
544
  next = renderCompletionNotice(unseen.map(completionEnvelope));
545
+ continue;
546
+ }
547
+ // Finishing closes the inbox unless something is held, so nothing is accepted unread.
548
+ const late = (await inbox?.finish()) ?? [];
549
+ if (late.length > 0)
550
+ next = renderAgentMessages(late);
318
551
  }
319
552
  settled = true;
320
553
  }