@providerkit/agents 0.0.0-stage → 0.2.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 (296) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/README.md +2328 -2
  4. package/THIRD_PARTY_NOTICES.md +521 -0
  5. package/dist/a2a/auth.d.ts +10 -0
  6. package/dist/a2a/auth.d.ts.map +1 -0
  7. package/dist/a2a/auth.js +52 -0
  8. package/dist/a2a/auth.js.map +1 -0
  9. package/dist/a2a/client.d.ts +74 -0
  10. package/dist/a2a/client.d.ts.map +1 -0
  11. package/dist/a2a/client.js +601 -0
  12. package/dist/a2a/client.js.map +1 -0
  13. package/dist/a2a/index.d.ts +22 -0
  14. package/dist/a2a/index.d.ts.map +1 -0
  15. package/dist/a2a/index.js +11 -0
  16. package/dist/a2a/index.js.map +1 -0
  17. package/dist/a2a/memory-runs.d.ts +62 -0
  18. package/dist/a2a/memory-runs.d.ts.map +1 -0
  19. package/dist/a2a/memory-runs.js +349 -0
  20. package/dist/a2a/memory-runs.js.map +1 -0
  21. package/dist/a2a/policy.d.ts +15 -0
  22. package/dist/a2a/policy.d.ts.map +1 -0
  23. package/dist/a2a/policy.js +114 -0
  24. package/dist/a2a/policy.js.map +1 -0
  25. package/dist/a2a/push.d.ts +34 -0
  26. package/dist/a2a/push.d.ts.map +1 -0
  27. package/dist/a2a/push.js +180 -0
  28. package/dist/a2a/push.js.map +1 -0
  29. package/dist/a2a/remote.d.ts +155 -0
  30. package/dist/a2a/remote.d.ts.map +1 -0
  31. package/dist/a2a/remote.js +1196 -0
  32. package/dist/a2a/remote.js.map +1 -0
  33. package/dist/a2a/server.d.ts +110 -0
  34. package/dist/a2a/server.d.ts.map +1 -0
  35. package/dist/a2a/server.js +1139 -0
  36. package/dist/a2a/server.js.map +1 -0
  37. package/dist/a2a/signing.d.ts +21 -0
  38. package/dist/a2a/signing.d.ts.map +1 -0
  39. package/dist/a2a/signing.js +305 -0
  40. package/dist/a2a/signing.js.map +1 -0
  41. package/dist/a2a/tasks.d.ts +88 -0
  42. package/dist/a2a/tasks.d.ts.map +1 -0
  43. package/dist/a2a/tasks.js +170 -0
  44. package/dist/a2a/tasks.js.map +1 -0
  45. package/dist/a2a/wire.d.ts +267 -0
  46. package/dist/a2a/wire.d.ts.map +1 -0
  47. package/dist/a2a/wire.js +1202 -0
  48. package/dist/a2a/wire.js.map +1 -0
  49. package/dist/background-types.d.ts +76 -0
  50. package/dist/background-types.d.ts.map +1 -0
  51. package/dist/background-types.js +2 -0
  52. package/dist/background-types.js.map +1 -0
  53. package/dist/child.d.ts +25 -0
  54. package/dist/child.d.ts.map +1 -0
  55. package/dist/child.js +129 -0
  56. package/dist/child.js.map +1 -0
  57. package/dist/code-driver.d.ts +40 -0
  58. package/dist/code-driver.d.ts.map +1 -0
  59. package/dist/code-driver.js +2 -0
  60. package/dist/code-driver.js.map +1 -0
  61. package/dist/code-mode.d.ts +3 -0
  62. package/dist/code-mode.d.ts.map +1 -0
  63. package/dist/code-mode.js +2 -0
  64. package/dist/code-mode.js.map +1 -0
  65. package/dist/code-script.d.ts +3 -0
  66. package/dist/code-script.d.ts.map +1 -0
  67. package/dist/code-script.js +149 -0
  68. package/dist/code-script.js.map +1 -0
  69. package/dist/code.d.ts +75 -0
  70. package/dist/code.d.ts.map +1 -0
  71. package/dist/code.js +326 -0
  72. package/dist/code.js.map +1 -0
  73. package/dist/compaction.d.ts +15 -0
  74. package/dist/compaction.d.ts.map +1 -0
  75. package/dist/compaction.js +168 -0
  76. package/dist/compaction.js.map +1 -0
  77. package/dist/delegation.d.ts +135 -0
  78. package/dist/delegation.d.ts.map +1 -0
  79. package/dist/delegation.js +401 -0
  80. package/dist/delegation.js.map +1 -0
  81. package/dist/evals/driver.d.ts +10 -0
  82. package/dist/evals/driver.d.ts.map +1 -0
  83. package/dist/evals/driver.js +192 -0
  84. package/dist/evals/driver.js.map +1 -0
  85. package/dist/evals/journal.d.ts +26 -0
  86. package/dist/evals/journal.d.ts.map +1 -0
  87. package/dist/evals/journal.js +483 -0
  88. package/dist/evals/journal.js.map +1 -0
  89. package/dist/evals/judge.d.ts +31 -0
  90. package/dist/evals/judge.d.ts.map +1 -0
  91. package/dist/evals/judge.js +142 -0
  92. package/dist/evals/judge.js.map +1 -0
  93. package/dist/evals/report.d.ts +38 -0
  94. package/dist/evals/report.d.ts.map +1 -0
  95. package/dist/evals/report.js +241 -0
  96. package/dist/evals/report.js.map +1 -0
  97. package/dist/evals/runner.d.ts +24 -0
  98. package/dist/evals/runner.d.ts.map +1 -0
  99. package/dist/evals/runner.js +655 -0
  100. package/dist/evals/runner.js.map +1 -0
  101. package/dist/evals/scorers.d.ts +36 -0
  102. package/dist/evals/scorers.d.ts.map +1 -0
  103. package/dist/evals/scorers.js +259 -0
  104. package/dist/evals/scorers.js.map +1 -0
  105. package/dist/evals/simulation.d.ts +7 -0
  106. package/dist/evals/simulation.d.ts.map +1 -0
  107. package/dist/evals/simulation.js +38 -0
  108. package/dist/evals/simulation.js.map +1 -0
  109. package/dist/evals/testing.d.ts +36 -0
  110. package/dist/evals/testing.d.ts.map +1 -0
  111. package/dist/evals/testing.js +87 -0
  112. package/dist/evals/testing.js.map +1 -0
  113. package/dist/evals/trajectory.d.ts +11 -0
  114. package/dist/evals/trajectory.d.ts.map +1 -0
  115. package/dist/evals/trajectory.js +180 -0
  116. package/dist/evals/trajectory.js.map +1 -0
  117. package/dist/evals/types.d.ts +431 -0
  118. package/dist/evals/types.d.ts.map +1 -0
  119. package/dist/evals/types.js +4 -0
  120. package/dist/evals/types.js.map +1 -0
  121. package/dist/evals.d.ts +14 -0
  122. package/dist/evals.d.ts.map +1 -0
  123. package/dist/evals.js +9 -0
  124. package/dist/evals.js.map +1 -0
  125. package/dist/extensions.d.ts +33 -0
  126. package/dist/extensions.d.ts.map +1 -0
  127. package/dist/extensions.js +188 -0
  128. package/dist/extensions.js.map +1 -0
  129. package/dist/handoff.d.ts +58 -0
  130. package/dist/handoff.d.ts.map +1 -0
  131. package/dist/handoff.js +160 -0
  132. package/dist/handoff.js.map +1 -0
  133. package/dist/index.d.ts +19 -0
  134. package/dist/index.d.ts.map +1 -0
  135. package/dist/index.js +11 -0
  136. package/dist/index.js.map +1 -0
  137. package/dist/input.d.ts +42 -0
  138. package/dist/input.d.ts.map +1 -0
  139. package/dist/input.js +266 -0
  140. package/dist/input.js.map +1 -0
  141. package/dist/mcp.d.ts +77 -0
  142. package/dist/mcp.d.ts.map +1 -0
  143. package/dist/mcp.js +505 -0
  144. package/dist/mcp.js.map +1 -0
  145. package/dist/memory-store.d.ts +11 -0
  146. package/dist/memory-store.d.ts.map +1 -0
  147. package/dist/memory-store.js +272 -0
  148. package/dist/memory-store.js.map +1 -0
  149. package/dist/memory.d.ts +212 -0
  150. package/dist/memory.d.ts.map +1 -0
  151. package/dist/memory.js +613 -0
  152. package/dist/memory.js.map +1 -0
  153. package/dist/otel.d.ts +74 -0
  154. package/dist/otel.d.ts.map +1 -0
  155. package/dist/otel.js +427 -0
  156. package/dist/otel.js.map +1 -0
  157. package/dist/progress.d.ts +17 -0
  158. package/dist/progress.d.ts.map +1 -0
  159. package/dist/progress.js +193 -0
  160. package/dist/progress.js.map +1 -0
  161. package/dist/quickjs.d.ts +19 -0
  162. package/dist/quickjs.d.ts.map +1 -0
  163. package/dist/quickjs.js +519 -0
  164. package/dist/quickjs.js.map +1 -0
  165. package/dist/recovery.d.ts +10 -0
  166. package/dist/recovery.d.ts.map +1 -0
  167. package/dist/recovery.js +62 -0
  168. package/dist/recovery.js.map +1 -0
  169. package/dist/request.d.ts +88 -0
  170. package/dist/request.d.ts.map +1 -0
  171. package/dist/request.js +422 -0
  172. package/dist/request.js.map +1 -0
  173. package/dist/run.d.ts +20 -0
  174. package/dist/run.d.ts.map +1 -0
  175. package/dist/run.js +2407 -0
  176. package/dist/run.js.map +1 -0
  177. package/dist/runs.d.ts +110 -0
  178. package/dist/runs.d.ts.map +1 -0
  179. package/dist/runs.js +438 -0
  180. package/dist/runs.js.map +1 -0
  181. package/dist/schema-to-ts.d.ts +4 -0
  182. package/dist/schema-to-ts.d.ts.map +1 -0
  183. package/dist/schema-to-ts.js +191 -0
  184. package/dist/schema-to-ts.js.map +1 -0
  185. package/dist/session.d.ts +23 -0
  186. package/dist/session.d.ts.map +1 -0
  187. package/dist/session.js +137 -0
  188. package/dist/session.js.map +1 -0
  189. package/dist/snapshot.d.ts +75 -0
  190. package/dist/snapshot.d.ts.map +1 -0
  191. package/dist/snapshot.js +1607 -0
  192. package/dist/snapshot.js.map +1 -0
  193. package/dist/steering.d.ts +75 -0
  194. package/dist/steering.d.ts.map +1 -0
  195. package/dist/steering.js +214 -0
  196. package/dist/steering.js.map +1 -0
  197. package/dist/subagents.d.ts +141 -0
  198. package/dist/subagents.d.ts.map +1 -0
  199. package/dist/subagents.js +746 -0
  200. package/dist/subagents.js.map +1 -0
  201. package/dist/tool-retry.d.ts +12 -0
  202. package/dist/tool-retry.d.ts.map +1 -0
  203. package/dist/tool-retry.js +53 -0
  204. package/dist/tool-retry.js.map +1 -0
  205. package/dist/tree.d.ts +98 -0
  206. package/dist/tree.d.ts.map +1 -0
  207. package/dist/tree.js +320 -0
  208. package/dist/tree.js.map +1 -0
  209. package/dist/types.d.ts +1007 -0
  210. package/dist/types.d.ts.map +1 -0
  211. package/dist/types.js +2 -0
  212. package/dist/types.js.map +1 -0
  213. package/dist/workflow-snapshot.d.ts +8 -0
  214. package/dist/workflow-snapshot.d.ts.map +1 -0
  215. package/dist/workflow-snapshot.js +276 -0
  216. package/dist/workflow-snapshot.js.map +1 -0
  217. package/dist/workflow-types.d.ts +171 -0
  218. package/dist/workflow-types.d.ts.map +1 -0
  219. package/dist/workflow-types.js +2 -0
  220. package/dist/workflow-types.js.map +1 -0
  221. package/dist/workflow.d.ts +19 -0
  222. package/dist/workflow.d.ts.map +1 -0
  223. package/dist/workflow.js +1053 -0
  224. package/dist/workflow.js.map +1 -0
  225. package/examples/a2a-remote.ts +85 -0
  226. package/examples/a2a-server.ts +100 -0
  227. package/examples/background.ts +59 -0
  228. package/examples/basic.ts +44 -0
  229. package/examples/code-mode.ts +76 -0
  230. package/examples/conversation.ts +57 -0
  231. package/examples/evals.ts +79 -0
  232. package/examples/guardrails.ts +56 -0
  233. package/examples/handoff.ts +79 -0
  234. package/examples/memory.ts +44 -0
  235. package/examples/otel.ts +99 -0
  236. package/examples/specialists.ts +99 -0
  237. package/examples/steering.ts +69 -0
  238. package/examples/structured-handoff.ts +92 -0
  239. package/examples/subagents.ts +127 -0
  240. package/examples/workflow.ts +74 -0
  241. package/package.json +114 -4
  242. package/src/a2a/auth.ts +62 -0
  243. package/src/a2a/client.ts +733 -0
  244. package/src/a2a/index.ts +74 -0
  245. package/src/a2a/memory-runs.ts +448 -0
  246. package/src/a2a/policy.ts +148 -0
  247. package/src/a2a/push.ts +251 -0
  248. package/src/a2a/remote.ts +1652 -0
  249. package/src/a2a/server.ts +1390 -0
  250. package/src/a2a/signing.ts +348 -0
  251. package/src/a2a/tasks.ts +260 -0
  252. package/src/a2a/wire.ts +1443 -0
  253. package/src/background-types.ts +86 -0
  254. package/src/child.ts +181 -0
  255. package/src/code-driver.ts +48 -0
  256. package/src/code-mode.ts +12 -0
  257. package/src/code-script.ts +149 -0
  258. package/src/code.ts +424 -0
  259. package/src/compaction.ts +212 -0
  260. package/src/delegation.ts +694 -0
  261. package/src/evals/driver.ts +222 -0
  262. package/src/evals/journal.ts +605 -0
  263. package/src/evals/judge.ts +188 -0
  264. package/src/evals/report.ts +295 -0
  265. package/src/evals/runner.ts +826 -0
  266. package/src/evals/scorers.ts +339 -0
  267. package/src/evals/simulation.ts +46 -0
  268. package/src/evals/testing.ts +126 -0
  269. package/src/evals/trajectory.ts +223 -0
  270. package/src/evals/types.ts +463 -0
  271. package/src/evals.ts +72 -0
  272. package/src/extensions.ts +247 -0
  273. package/src/handoff.ts +214 -0
  274. package/src/index.ts +62 -0
  275. package/src/input.ts +319 -0
  276. package/src/mcp.ts +690 -0
  277. package/src/memory-store.ts +366 -0
  278. package/src/memory.ts +893 -0
  279. package/src/otel.ts +568 -0
  280. package/src/progress.ts +214 -0
  281. package/src/quickjs.ts +524 -0
  282. package/src/recovery.ts +90 -0
  283. package/src/request.ts +513 -0
  284. package/src/run.ts +3199 -0
  285. package/src/runs.ts +696 -0
  286. package/src/schema-to-ts.ts +194 -0
  287. package/src/session.ts +178 -0
  288. package/src/snapshot.ts +2099 -0
  289. package/src/steering.ts +329 -0
  290. package/src/subagents.ts +1084 -0
  291. package/src/tool-retry.ts +86 -0
  292. package/src/tree.ts +366 -0
  293. package/src/types.ts +944 -0
  294. package/src/workflow-snapshot.ts +366 -0
  295. package/src/workflow-types.ts +213 -0
  296. package/src/workflow.ts +1316 -0
@@ -0,0 +1,86 @@
1
+ import type { AgentHost, RunOptions, RunState, TreeNode } from "./types.ts";
2
+
3
+ /** Portable host policy contracts. No optional server package is imported here. */
4
+ export type Continuation = {
5
+ /** Authorization claim, distinct from both the logical run and the host row. */
6
+ id: string;
7
+ sourceId: string;
8
+ } & (
9
+ | { kind: "answers"; answers: Readonly<Record<string, unknown>>; wakeAt?: number }
10
+ /** Control command, never an answer, approval or scheduled wake. */
11
+ | { kind: "cancel"; answers: Readonly<Record<string, never>>; wakeAt?: never }
12
+ );
13
+
14
+ /** Portable input to the host's atomic continuation admission. The host must authenticate
15
+ * owner, lock the current source and create OR reconcile (owner, sourceId, continuation.id).
16
+ * Save this exact input and commit before returning. A repeated claim returns the same
17
+ * physical id, including after a lost reply. A different input for that claim must fail. */
18
+ export interface BackgroundContinuationInput {
19
+ kind: string;
20
+ owner: string;
21
+ restart: "resume";
22
+ input: { format: 1; snapshot: TreeNode; continuation: Continuation };
23
+ }
24
+ export interface BackgroundContinuationResult {
25
+ id: string;
26
+ }
27
+
28
+ /** Queue acceptance is not cancellation proof. Observe id, which can be a fresh segment. */
29
+ export interface BackgroundCancelResult {
30
+ id: string;
31
+ requested: boolean;
32
+ }
33
+
34
+ export interface BackgroundContext {
35
+ /** From the authenticated caller, or from the stored worker owner. */
36
+ owner: string;
37
+ /** Logical execution identity, retained across physical segments. Not ownership proof. */
38
+ runId: string;
39
+ segmentId: string;
40
+ continuation?: Continuation;
41
+ }
42
+
43
+ export interface BackgroundPolicy
44
+ extends
45
+ Pick<RunOptions, "onEvent" | "onLifecycle" | "bindModelProvider">,
46
+ Required<
47
+ Pick<AgentHost, "authorizeResume" | "prepareRequest" | "resolveRequest" | "beforeTool">
48
+ >,
49
+ Pick<
50
+ AgentHost,
51
+ | "canRunConcurrently"
52
+ | "needsApproval"
53
+ | "answerNow"
54
+ | "inbox"
55
+ | "reconcileToolRetry"
56
+ | "beforeStep"
57
+ | "reconcileStep"
58
+ > {
59
+ /** Worker-only values for tools. Never serialized; the SDK supplies reserved IDs/signals. */
60
+ context?: RunOptions["context"];
61
+ /** Check that the current owner may read each media reference. */
62
+ loadMedia?: AgentHost["loadMedia"];
63
+ /** Under the worker's lease, authenticate every answer and atomically reserve each exact
64
+ * request for continuation.id AND context.segmentId. Repeating that claim succeeds; another
65
+ * claim or segment fails. Empty answers must claim the exact due wake, except an explicit
66
+ * cancel command: claim that command against the current logical segment without granting
67
+ * any pending request. The host owns the durable state. authorizeResume rechecks ownership,
68
+ * and resolveRequest may reuse a consumed
69
+ * answer only within this same claim and segment. */
70
+ claimContinuation(snapshot: TreeNode, continuation: Continuation): void | Promise<void>;
71
+ }
72
+
73
+ /** Awaited root-segment boundary. Snapshot data is private, never a browser or peer response.
74
+ * End means the SDK journal settled, NOT that the host marked its worker row successful.
75
+ * A worker restart can repeat a hook. Persist/reconcile external effects before sending them. */
76
+ export type SegmentHook = (event: {
77
+ phase: "start" | "end";
78
+ owner: string;
79
+ /** Physical host segment. */
80
+ id: string;
81
+ runId: string;
82
+ /** Worker lifetime. Observe it when waiting or making an external request. */
83
+ signal: AbortSignal;
84
+ state: RunState;
85
+ snapshot: TreeNode;
86
+ }) => void | Promise<void>;
package/src/child.ts ADDED
@@ -0,0 +1,181 @@
1
+ import { AGENT_RUNTIME, type NodeRuntime, type Specialist } from "./delegation.ts";
2
+ import type { SubagentCreation } from "./subagents.ts";
3
+ import { readInput } from "./input.ts";
4
+ import type { ChildEnvelope, RunOptions, TreeNode } from "./types.ts";
5
+ import { checkChildProgress, checkTree, immutableCopy, isId, isRecord } from "./snapshot.ts";
6
+ import { emitEvent, fail, untilAbort, type ExecutionScope } from "./tree.ts";
7
+
8
+ /** Capture input before asynchronous admission so callers cannot change the saved identity. */
9
+ export function prepareChild(
10
+ node: Specialist,
11
+ input: unknown,
12
+ subagent?: SubagentCreation,
13
+ root?: TreeNode,
14
+ ) {
15
+ if (node.kind === "remote") {
16
+ const start = node[AGENT_RUNTIME].prepare(input);
17
+ return {
18
+ input: start,
19
+ create: (runId: string, tree: TreeNode["tree"], options: RunOptions): Promise<TreeNode> =>
20
+ node[AGENT_RUNTIME].create(start, runId, tree, options, root),
21
+ };
22
+ }
23
+ if (node.kind === "agent") {
24
+ const start = node[AGENT_RUNTIME].freeze(readInput(input, "trusted"));
25
+ return {
26
+ input: start,
27
+ create: (runId: string, tree: TreeNode["tree"], options: RunOptions): Promise<TreeNode> =>
28
+ node[AGENT_RUNTIME].create(start, runId, tree, options, subagent),
29
+ };
30
+ }
31
+ const start = immutableCopy(input);
32
+ return {
33
+ input: start,
34
+ create: (runId: string, tree: TreeNode["tree"], options: RunOptions): Promise<TreeNode> =>
35
+ node[AGENT_RUNTIME].create(start, runId, tree, options),
36
+ };
37
+ }
38
+
39
+ /** Insert and validate without yielding, so competing coordinators cannot consume one handle.
40
+ * A refused child must never reach a checkpoint or leave an invalid admission behind. */
41
+ export function admitChild(
42
+ children: (ChildEnvelope & { key: string })[],
43
+ child: ChildEnvelope & { key: string },
44
+ scope: ExecutionScope,
45
+ ): ChildEnvelope & { key: string } {
46
+ scope.tree.reserveChild(scope.depth + 1);
47
+ children.push(child);
48
+ try {
49
+ checkTree(scope.tree.root);
50
+ } catch (error) {
51
+ children.pop();
52
+ throw error;
53
+ }
54
+ return child;
55
+ }
56
+
57
+ /** Shared leased child execution. Admission belongs to the caller's journal, never the host. */
58
+ export async function startChild(
59
+ saved: ChildEnvelope & { key: string },
60
+ parent: TreeNode,
61
+ operationId: string,
62
+ runtime: NodeRuntime,
63
+ options: RunOptions,
64
+ scope: ExecutionScope,
65
+ signal: AbortSignal,
66
+ active: () => void,
67
+ resume: boolean,
68
+ before?: () => void | Promise<void>,
69
+ handoffInput?: ExecutionScope["handoffInput"],
70
+ ): Promise<void> {
71
+ if (saved.snapshot.state.status !== "running" && saved.snapshot.state.status !== "suspended")
72
+ return;
73
+ await scope.tree.save();
74
+ active();
75
+ const step = { operationId, key: saved.key, runId: saved.snapshot.runId };
76
+ let execution: Promise<ChildEnvelope> | undefined;
77
+ let hookOpen = true;
78
+ let executionSettled = false;
79
+ const execute = () => {
80
+ if (!hookOpen || execution)
81
+ throw new Error("A host child may execute once, before its hook returns.");
82
+ execution = (async () => {
83
+ await before?.();
84
+ active();
85
+ if (resume) saved.snapshot.attemptId = crypto.randomUUID();
86
+ const identity =
87
+ saved.snapshot.kind === "agent"
88
+ ? {
89
+ kind: "agent" as const,
90
+ agentId: saved.snapshot.agentId,
91
+ ...(saved.snapshot.subagent ? { subagent: true as const } : {}),
92
+ }
93
+ : saved.snapshot.kind === "remote"
94
+ ? { kind: "remote" as const, agentId: saved.snapshot.agentId }
95
+ : { kind: "workflow" as const, workflowId: saved.snapshot.workflowId };
96
+ emitEvent(options, {
97
+ type: "child",
98
+ parentRunId: parent.runId,
99
+ ...step,
100
+ ...identity,
101
+ version: saved.snapshot.version,
102
+ });
103
+ const result = await runtime.execute(
104
+ saved.snapshot,
105
+ { ...options, signal },
106
+ {
107
+ tree: scope.tree,
108
+ depth: scope.depth + 1,
109
+ path: [...scope.path, step],
110
+ handoffInput,
111
+ },
112
+ );
113
+ executionSettled = true;
114
+ return { snapshot: result.snapshot };
115
+ })();
116
+ void execution.catch(() => {});
117
+ return execution;
118
+ };
119
+ let envelope: ChildEnvelope;
120
+ try {
121
+ envelope = options.host?.child
122
+ ? await untilAbort(
123
+ Promise.resolve(
124
+ options.host.child(
125
+ immutableCopy({
126
+ ...saved,
127
+ parentRunId: parent.runId,
128
+ operationId,
129
+ resume,
130
+ }),
131
+ execute,
132
+ ),
133
+ ),
134
+ signal,
135
+ )
136
+ : await execute();
137
+ if (execution && !executionSettled)
138
+ fail(
139
+ "invalid_child_host",
140
+ "The child hook returned before its execution settled.",
141
+ operationId,
142
+ );
143
+ } finally {
144
+ hookOpen = false;
145
+ if (execution) await execution;
146
+ }
147
+ active();
148
+ if (!isRecord(envelope) || (envelope.reference !== undefined && !isId(envelope.reference)))
149
+ fail("invalid_child_host", "The child hook must return a snapshot envelope.", operationId);
150
+ const restored = runtime.restore(
151
+ envelope.snapshot,
152
+ parent.tree,
153
+ saved.snapshot.kind === "agent" ? saved.snapshot.subagent : undefined,
154
+ );
155
+ checkChildProgress(saved.snapshot, restored);
156
+ if (restored.state.status === "running")
157
+ fail("invalid_child_host", "The child hook returned an unfinished child.", operationId);
158
+ const previous = saved.snapshot;
159
+ saved.snapshot = restored;
160
+ try {
161
+ checkTree(scope.tree.root);
162
+ } catch (error) {
163
+ saved.snapshot = previous;
164
+ throw error;
165
+ }
166
+ saved.reference = envelope.reference ?? saved.reference;
167
+ await scope.tree.save();
168
+ }
169
+
170
+ /** A child never inherits conversation storage or its parent's resolved provider policy. */
171
+ export function childOptions(options: RunOptions): RunOptions {
172
+ const {
173
+ session: _session,
174
+ historyLimit: _history,
175
+ prepareHistory: _prepare,
176
+ modelSettings: _settings,
177
+ enabledTools: _tools,
178
+ ...inherited
179
+ } = options;
180
+ return inherited;
181
+ }
@@ -0,0 +1,48 @@
1
+ /** The engine boundary. This contract does not load an optional runtime. */
2
+ export interface CodeDriver {
3
+ /** Run once in a fresh sandbox and free it before settling. Program failures never reject. */
4
+ run(job: CodeJob): Promise<CodeJobResult>;
5
+ }
6
+
7
+ export interface CodeJob {
8
+ /** SDK-built JavaScript. Its value must be a string or a promise of a JSON envelope string. */
9
+ script: string;
10
+ /**
11
+ * Exposed as __pk_call(name, input). Both arguments and the reply are strings.
12
+ * The SDK checks tool names, JSON, byte limits, permissions and call budgets.
13
+ * Return an error envelope for tool failures, not a rejected promise. Never retried.
14
+ */
15
+ call(name: string, input: string): Promise<string>;
16
+ /** Exposed as __pk_log(text). The SDK caps and records the text. */
17
+ log(text: string): void;
18
+ /** Maximum guest heap allocation in bytes. */
19
+ memoryBytes: number;
20
+ /** Maximum guest stack in bytes. A driver may refuse an unsafe size. */
21
+ stackBytes: number;
22
+ /** Cumulative execution time in milliseconds, excluding asynchronous host waits. */
23
+ cpuMs: number;
24
+ /** Absolute wall deadline in epoch milliseconds, including admission and tool waits. */
25
+ deadline: number;
26
+ /** The SDK aborts its tool calls when this job ends. Cancellation cannot undo an effect. */
27
+ signal: AbortSignal;
28
+ }
29
+
30
+ export type CodeJobResult =
31
+ | { ok: true; envelope: string }
32
+ | {
33
+ ok: false;
34
+ error: {
35
+ name:
36
+ | "SyntaxError"
37
+ | "ProgramError"
38
+ | "TimeoutError"
39
+ | "CpuLimitError"
40
+ | "MemoryLimitError"
41
+ | "StackLimitError"
42
+ | "AbortError"
43
+ | "EngineError";
44
+ message: string;
45
+ /** Line in the SDK-built script. The SDK maps it back to the submitted code. */
46
+ line?: number;
47
+ };
48
+ };
@@ -0,0 +1,12 @@
1
+ export { codeMode, CODE_LIMITS, toolTypings } from "./code.ts";
2
+ export type {
3
+ CodeLimits,
4
+ CodeModeOptions,
5
+ CodeTool,
6
+ CodeDriver,
7
+ CodeJob,
8
+ CodeJobResult,
9
+ ProgramBridge,
10
+ ProgramOutcome,
11
+ ProgramCall,
12
+ } from "./code.ts";
@@ -0,0 +1,149 @@
1
+ // Async result wrapping adapted from TanStack AI's ai-code-mode/src/code-wrapper.ts
2
+ // (MIT, Copyright (c) 2025 Tanner Linsley). Changes: indirect evaluation, hidden
3
+ // string bridges, JSON-only values and closed bridges before result/error inspection.
4
+ // See THIRD_PARTY_NOTICES.md.
5
+
6
+ /** Build the guest side only. The host bridge still owns permission checks, limits and receipts. */
7
+ export function codeScript(expression: string, toolNames: readonly string[]): string {
8
+ return `(() => {
9
+ "use strict";
10
+ const call = globalThis.__pk_call;
11
+ const log = globalThis.__pk_log;
12
+ delete globalThis.__pk_call;
13
+ delete globalThis.__pk_log;
14
+ const evaluate = eval;
15
+ const stringify = JSON.stringify;
16
+ const parse = JSON.parse;
17
+ const create = Object.create;
18
+ const define = Object.defineProperty;
19
+ const freeze = Object.freeze;
20
+ const prototype = Object.getPrototypeOf;
21
+ const setPrototype = Object.setPrototypeOf;
22
+ const descriptor = Object.getOwnPropertyDescriptor;
23
+ const owns = Object.hasOwn;
24
+ const keys = Reflect.ownKeys;
25
+ const isArray = Array.isArray;
26
+ const finite = Number.isFinite;
27
+ const number = Number;
28
+ const matchLine = Function.prototype.call.bind(RegExp.prototype.exec, /<input>:(\\d+)/);
29
+ const PlainObject = Object.prototype;
30
+ const ErrorClass = Error;
31
+ const promise = Promise.resolve.bind(Promise);
32
+ const then = Function.prototype.call.bind(Promise.prototype.then);
33
+ const slice = Function.prototype.call.bind(String.prototype.slice);
34
+ const join = Function.prototype.call.bind(Array.prototype.join);
35
+ const names = ${JSON.stringify(toolNames)};
36
+ let open = true;
37
+
38
+ function requireOpen() {
39
+ if (!open) throw new ErrorClass("The program has finished. No more tool calls can start.");
40
+ }
41
+
42
+ function json(value, parents = []) {
43
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
44
+ if (typeof value === "number" && finite(value)) return value;
45
+ if (typeof value !== "object") throw new ErrorClass("Use JSON values only.");
46
+ for (const parent of parents) {
47
+ if (parent === value) throw new ErrorClass("A JSON value cannot contain a cycle.");
48
+ }
49
+ const array = isArray(value);
50
+ if (!array && prototype(value) !== PlainObject && prototype(value) !== null) {
51
+ throw new ErrorClass("Use plain objects and arrays, not class instances.");
52
+ }
53
+ const next = [...parents, value];
54
+ const result = array ? setPrototype([], null) : create(null);
55
+ let count = 0;
56
+ for (const key of keys(value)) {
57
+ if (typeof key !== "string") throw new ErrorClass("JSON objects cannot have symbol keys.");
58
+ if (array && key === "length") continue;
59
+ if (array && (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= value.length)) {
60
+ throw new ErrorClass("JSON arrays cannot have extra properties.");
61
+ }
62
+ const field = descriptor(value, key);
63
+ if (!field || !owns(field, "value")) throw new ErrorClass("JSON values cannot have getters or setters.");
64
+ define(result, key, { value: json(field.value, next), enumerable: true });
65
+ count++;
66
+ }
67
+ if (array && count !== value.length) throw new ErrorClass("JSON arrays cannot have missing entries.");
68
+ return result;
69
+ }
70
+
71
+ function encode(value) {
72
+ return stringify(json(value));
73
+ }
74
+
75
+ const bindings = create(null);
76
+ for (const name of names) {
77
+ define(bindings, name, { enumerable: true, value: async (input) => {
78
+ requireOpen();
79
+ if (!input || typeof input !== "object" || isArray(input)) {
80
+ throw new ErrorClass("Pass one JSON object to a tool.");
81
+ }
82
+ const encoded = encode(input);
83
+ requireOpen();
84
+ const reply = parse(await call(name, encoded));
85
+ if (reply.ok) return reply.value;
86
+ const error = new ErrorClass(reply.error.message);
87
+ error.name = "ToolError";
88
+ error.tool = name;
89
+ error.kind = reply.error.kind;
90
+ throw error;
91
+ }});
92
+ }
93
+ const tools = new Proxy(freeze(bindings), { get(target, name) {
94
+ if (typeof name === "symbol") return undefined;
95
+ if (owns(target, name)) return target[name];
96
+ throw new ErrorClass("Unknown tool. Choose one of: " + join(names, ", ") + ".");
97
+ }});
98
+ define(globalThis, "tools", { value: tools, enumerable: true });
99
+ define(globalThis, "console", { value: freeze({ log(...values) {
100
+ requireOpen();
101
+ const parts = [];
102
+ for (const value of values) {
103
+ parts.push(typeof value === "string" ? value : value === undefined ? "undefined" : encode(value));
104
+ }
105
+ requireOpen();
106
+ log(join(parts, " "));
107
+ }}) });
108
+
109
+ function failure(error, invalidResult = false) {
110
+ open = false;
111
+ const result = create(null);
112
+ result.name = "ProgramError";
113
+ result.message = "The program threw an error.";
114
+ try {
115
+ if (error && error.name === "SyntaxError") result.name = "SyntaxError";
116
+ if (error && typeof error.message === "string") result.message = slice(error.message, 0, 2048);
117
+ else if (typeof error === "string") result.message = slice(error, 0, 2048);
118
+ if (error && typeof error.stack === "string") {
119
+ const found = matchLine(error.stack);
120
+ const line = found && number(found[1]) - 1;
121
+ if (finite(line) && line > 0) result.line = line;
122
+ }
123
+ } catch {}
124
+ const envelope = create(null);
125
+ envelope.ok = false;
126
+ envelope.error = result;
127
+ if (invalidResult) envelope.invalidResult = true;
128
+ return stringify(envelope);
129
+ }
130
+
131
+ try {
132
+ // Indirect eval gives the program global scope, not access to this closure's bridges.
133
+ // The expression may end in a semicolon after host TypeScript transpilation.
134
+ const program = evaluate(${JSON.stringify(expression)});
135
+ if (typeof program !== "function") throw new ErrorClass("The program must be an async function.");
136
+ return then(promise(program()), (value) => {
137
+ open = false;
138
+ try {
139
+ const envelope = create(null);
140
+ envelope.ok = true;
141
+ if (value !== undefined) {
142
+ envelope.value = json(value);
143
+ }
144
+ return stringify(envelope);
145
+ } catch (error) { return failure(error, true); }
146
+ }, failure);
147
+ } catch (error) { return failure(error); }
148
+ })()`;
149
+ }