@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
package/src/runs.ts ADDED
@@ -0,0 +1,696 @@
1
+ import type {
2
+ createRuns,
3
+ ChildResult,
4
+ ChildSpec,
5
+ Run,
6
+ RunEvent,
7
+ StoredRun,
8
+ } from "@gusnips/server/runs";
9
+ import { createProgress, type EventDurability } from "./progress.ts";
10
+ export type { EventDurability, ProgressGap } from "./progress.ts";
11
+ import { checkMemoryBinding, readMemoryBinding, type MemoryBinding } from "./memory.ts";
12
+ import type { RemoteAgent, RemoteOutcome } from "./a2a/remote.ts";
13
+ import { requestHash } from "./request.ts";
14
+ import type { NodeOutcome } from "./delegation.ts";
15
+ import type { Workflow, WorkflowOutcome } from "./workflow-types.ts";
16
+ import { AGENT_RUNTIME } from "./delegation.ts";
17
+ import {
18
+ checkOptions,
19
+ checkChildProgress,
20
+ copyData,
21
+ equalData,
22
+ immutableCopy,
23
+ isId,
24
+ isRecord,
25
+ isSession,
26
+ isSessionStatus,
27
+ readModelSettings,
28
+ } from "./snapshot.ts";
29
+ import { openRequests, readAnswers, untilAbort, wakeAt } from "./tree.ts";
30
+ import type {
31
+ Agent,
32
+ AgentHost,
33
+ AgentInput,
34
+ ChildEnvelope,
35
+ RecordedModelSettings,
36
+ RunOptions,
37
+ RunOutcome,
38
+ TreeNode,
39
+ ResumeOptions,
40
+ Session,
41
+ SessionStatus,
42
+ } from "./types.ts";
43
+
44
+ export type BackgroundRuns = Pick<
45
+ ReturnType<typeof createRuns>,
46
+ "create" | "read" | "tail" | "cancel"
47
+ >;
48
+
49
+ /** Minimum worker capabilities. Server 0.19/0.20 remain valid in best-effort mode,
50
+ * including their child callbacks; only awaited mode needs append. */
51
+ export interface BackgroundWorker extends Pick<
52
+ Run,
53
+ "id" | "owner" | "input" | "checkpoint" | "resumed" | "crashes" | "signal" | "save" | "emit"
54
+ > {
55
+ append?: (events: readonly { type: string; data?: unknown }[]) => Promise<void>;
56
+ child<T>(
57
+ key: string,
58
+ spec: ChildSpec,
59
+ fn: (run: BackgroundWorker) => Promise<T>,
60
+ ): Promise<ChildResult<T>>;
61
+ }
62
+
63
+ import type {
64
+ BackgroundCancelResult,
65
+ BackgroundContinuationInput,
66
+ BackgroundContinuationResult,
67
+ BackgroundContext,
68
+ BackgroundPolicy,
69
+ Continuation,
70
+ SegmentHook,
71
+ } from "./background-types.ts";
72
+ export type {
73
+ BackgroundCancelResult,
74
+ BackgroundContinuationInput,
75
+ BackgroundContinuationResult,
76
+ BackgroundContext,
77
+ BackgroundPolicy,
78
+ Continuation,
79
+ SegmentHook,
80
+ } from "./background-types.ts";
81
+
82
+ export interface BackgroundOptions<T> extends BackgroundBase {
83
+ agent: Agent<T>;
84
+ }
85
+ export interface BackgroundRemoteOptions<T> extends Omit<
86
+ BackgroundBase,
87
+ "session" | "historyLimit" | "prepareHistory" | "memory"
88
+ > {
89
+ agent: RemoteAgent<T>;
90
+ }
91
+ export interface BackgroundWorkflowOptions<I, O> extends Omit<
92
+ BackgroundBase,
93
+ "session" | "historyLimit" | "prepareHistory"
94
+ > {
95
+ workflow: Workflow<I, O>;
96
+ }
97
+ interface BackgroundBase {
98
+ /** Dedicated handler key for this agent version. */
99
+ kind: string;
100
+ /** Injected create must resolve after its transaction commits. Only then is enqueue called. */
101
+ runs: BackgroundRuns;
102
+ /** Optional durable, owner-scoped create-or-reconcile capability. Required only to cancel
103
+ * a suspended logical run. Also used for answers when supplied. Never substitute a local
104
+ * cache or an idempotency flag for atomic host storage. See BackgroundContinuationInput. */
105
+ createContinuation?: (
106
+ input: BackgroundContinuationInput,
107
+ ) => Promise<BackgroundContinuationResult>;
108
+ /** Coalesced progress uses emit by default. Awaited mode needs Run.append (server 0.21+). */
109
+ events?: EventDurability;
110
+ /** Await durable queue acceptance. A worker calls runs.drive(id, background.handlers).
111
+ * The host must also run runs.sweep on boot and periodically, and drain on shutdown. */
112
+ enqueue: (id: string) => Promise<void>;
113
+ policy: (context: BackgroundContext) => BackgroundPolicy | Promise<BackgroundPolicy>;
114
+ /** Awaited before execution and after the SDK journal settles. May repeat after worker loss;
115
+ * the host must deduplicate/reconcile external effects. This is not host-row commit proof. */
116
+ onSegment?: SegmentHook;
117
+ /** Trusted. Return the session `id` names, after checking that `owner` may use it: an id
118
+ * from a request is not authorization. `start` reads its history inside the authenticated
119
+ * request; the worker gets it again, with the stored owner, to append the turn. */
120
+ session?: (owner: string, id: string) => Session | Promise<Session>;
121
+ /** Authenticate scopes in start and again in the worker. A changed erasure revision refuses
122
+ * resume; this factory never recalls notes or ingests a completed run automatically. */
123
+ memory?: (owner: string) => MemoryBinding | Promise<MemoryBinding>;
124
+ /** How many of the session's newest messages `start` loads. */
125
+ historyLimit?: number;
126
+ /** Runs once in `start`, before the run is saved. See RunOptions.prepareHistory. */
127
+ prepareHistory?: RunOptions["prepareHistory"];
128
+ }
129
+
130
+ /** Server-side: the snapshot holds the whole conversation, prompts and tool data. Send a
131
+ * browser a projection, never this object. */
132
+ export interface BackgroundRun<T, R extends NodeOutcome<T> = RunOutcome<T>> {
133
+ id: string;
134
+ /** Host completion is not SDK completion: a successful segment can be suspended or failed. */
135
+ status: StoredRun["status"];
136
+ snapshot: R["snapshot"];
137
+ /** outcome.session says whether the worker's append saved the turn. */
138
+ outcome: R | null;
139
+ /** Earliest pending wake in the tree. The host schedules continuation. */
140
+ wakeAt?: number;
141
+ error: StoredRun["error"];
142
+ }
143
+
144
+ /** The row exists. Retry queueing this id, or let the host sweep find it; do not start again. */
145
+ export class BackgroundEnqueueError extends Error {
146
+ constructor(
147
+ readonly id: string,
148
+ cause: unknown,
149
+ ) {
150
+ super(
151
+ `Run ${id} was saved, but queueing failed. Enqueue this id again; do not create another run.`,
152
+ { cause },
153
+ );
154
+ this.name = "BackgroundEnqueueError";
155
+ }
156
+ }
157
+
158
+ interface Segment<N extends TreeNode = TreeNode> {
159
+ format: 1;
160
+ snapshot: N;
161
+ continuation?: Continuation;
162
+ }
163
+
164
+ /** A root segment's stored result. The session status is only known to the worker that
165
+ * appended, so it is kept beside the snapshot rather than derived from it. */
166
+ interface Settled {
167
+ format: 1;
168
+ snapshot: unknown;
169
+ session?: SessionStatus;
170
+ }
171
+
172
+ function settled(raw: unknown): Settled {
173
+ const invalid = () => new TypeError("This row's result is not an agent segment result.");
174
+ if (!isRecord(raw) || raw.format !== 1) throw invalid();
175
+ const session = raw.session;
176
+ if (session === undefined) return { format: 1, snapshot: raw.snapshot };
177
+ if (!isSessionStatus(session)) throw invalid();
178
+ return { format: 1, snapshot: raw.snapshot, session };
179
+ }
180
+
181
+ /** Background work uses the host's lease, queue and cancellation. Children stay in-process.
182
+ * Usage remains in stable SDK receipts; this binding never calls additive Run.spend. */
183
+ export function createBackgroundAgent<T>(
184
+ options: BackgroundOptions<T>,
185
+ ): ReturnType<typeof bindBackground<AgentInput, RunOutcome<T>>>;
186
+ export function createBackgroundAgent<T>(
187
+ options: BackgroundRemoteOptions<T>,
188
+ ): ReturnType<typeof bindBackground<AgentInput, RemoteOutcome<T>>>;
189
+ export function createBackgroundAgent<I, O>(
190
+ options: BackgroundWorkflowOptions<I, O>,
191
+ ): ReturnType<typeof bindBackground<I, WorkflowOutcome<O>>>;
192
+ export function createBackgroundAgent<I, O>(
193
+ options: BackgroundOptions<O> | BackgroundRemoteOptions<O> | BackgroundWorkflowOptions<I, O>,
194
+ ) {
195
+ if ("workflow" in options) {
196
+ const workflow = options.workflow;
197
+ return bindBackground<I, WorkflowOutcome<O>>(options, {
198
+ ...workflow[AGENT_RUNTIME],
199
+ resume: (raw, opts) => workflow.resume(raw, opts),
200
+ });
201
+ }
202
+ const agent = options.agent;
203
+ if (agent.kind === "remote")
204
+ return bindBackground<AgentInput, RemoteOutcome<O>>(options, {
205
+ ...agent[AGENT_RUNTIME],
206
+ resume: (raw, opts) => agent.resume(raw, opts),
207
+ });
208
+ const runtime = agent[AGENT_RUNTIME];
209
+ return bindBackground<AgentInput, RunOutcome<O>>(options, {
210
+ open: (input, opts, id) => runtime.open(input, opts, id),
211
+ restore: (raw) => runtime.restore(raw),
212
+ hydrate: (snapshot) => runtime.node.hydrate(snapshot),
213
+ resume: (raw, opts) => agent.resume(raw, opts),
214
+ });
215
+ }
216
+ function bindBackground<I, R extends NodeOutcome>(
217
+ options: BackgroundBase,
218
+ runtime: {
219
+ open(input: I, options: RunOptions, runId: string): Promise<R["snapshot"]>;
220
+ restore(raw: unknown): R["snapshot"];
221
+ hydrate(snapshot: TreeNode): R;
222
+ resume(raw: unknown, options: ResumeOptions): Promise<R>;
223
+ },
224
+ ) {
225
+ const { kind, runs, enqueue, historyLimit, prepareHistory, events = "best-effort" } = options;
226
+ if (events !== "best-effort" && events !== "awaited")
227
+ throw new TypeError('events must be "best-effort" or "awaited".');
228
+ if (!isId(kind) || typeof enqueue !== "function" || typeof options.policy !== "function")
229
+ throw new TypeError(
230
+ "Provide a run kind, a durable enqueue callback and a trusted policy factory.",
231
+ );
232
+ if (options.createContinuation !== undefined && typeof options.createContinuation !== "function")
233
+ throw new TypeError(
234
+ "createContinuation must atomically create or reconcile a saved continuation.",
235
+ );
236
+ if (options.onSegment !== undefined && typeof options.onSegment !== "function")
237
+ throw new TypeError("onSegment must be a function.");
238
+ if (options.session !== undefined && typeof options.session !== "function")
239
+ throw new TypeError("The session option must be a factory: (owner, id) => Session.");
240
+ checkOptions({ historyLimit, prepareHistory });
241
+ if (options.memory !== undefined && typeof options.memory !== "function")
242
+ throw new TypeError("The memory option must be a trusted owner-to-binding factory.");
243
+ async function memoryFor(owner: string, signal: AbortSignal) {
244
+ return options.memory
245
+ ? readMemoryBinding(await untilAbort(Promise.resolve(options.memory(owner)), signal))
246
+ : undefined;
247
+ }
248
+ async function sessionFor(owner: string, id: string, signal: AbortSignal): Promise<Session> {
249
+ const factory = options.session;
250
+ if (!factory)
251
+ throw new TypeError(
252
+ "This run uses a session. Pass a session factory to createBackgroundAgent.",
253
+ );
254
+ const session: unknown = await untilAbort(Promise.resolve(factory(owner, id)), signal);
255
+ if (!isSession(session) || session.id !== id)
256
+ throw new TypeError("The session factory must return the session with that id.");
257
+ return session;
258
+ }
259
+
260
+ async function policy(context: BackgroundContext): Promise<BackgroundPolicy> {
261
+ const value = await options.policy(immutableCopy(context));
262
+ for (const key of [
263
+ "authorizeResume",
264
+ "prepareRequest",
265
+ "resolveRequest",
266
+ "beforeTool",
267
+ "claimContinuation",
268
+ ] as const)
269
+ if (typeof value?.[key] !== "function")
270
+ throw new TypeError(`Background policy must implement ${key}.`);
271
+ return value;
272
+ }
273
+
274
+ function segment(raw: unknown): Segment<R["snapshot"]> {
275
+ if (!isRecord(raw) || raw.format !== 1)
276
+ throw new TypeError("This row is not an agent background segment.");
277
+ const snapshot = runtime.restore(raw.snapshot);
278
+ if (raw.continuation === undefined) return { format: 1, snapshot };
279
+ const continuation = raw.continuation;
280
+ if (
281
+ !isRecord(continuation) ||
282
+ snapshot.state.status !== "suspended" ||
283
+ !isId(continuation.id) ||
284
+ !isId(continuation.sourceId) ||
285
+ !isRecord(continuation.answers) ||
286
+ !["answers", "cancel"].includes(String(continuation.kind)) ||
287
+ Object.keys(continuation).some(
288
+ (key) => !["id", "sourceId", "kind", "answers", "wakeAt"].includes(key),
289
+ ) ||
290
+ (continuation.kind === "cancel" &&
291
+ (Object.keys(continuation.answers).length !== 0 ||
292
+ continuation.wakeAt !== undefined ||
293
+ continuation.id !== `cancel/${continuation.sourceId}`)) ||
294
+ (continuation.kind === "answers" &&
295
+ (Object.keys(continuation.answers).length === 0
296
+ ? continuation.wakeAt === undefined
297
+ : continuation.wakeAt !== undefined)) ||
298
+ (continuation.wakeAt !== undefined &&
299
+ (typeof continuation.wakeAt !== "number" || continuation.wakeAt !== wakeAt(snapshot)))
300
+ )
301
+ throw new TypeError("The saved continuation is invalid.");
302
+ return {
303
+ format: 1,
304
+ snapshot,
305
+ continuation:
306
+ continuation.kind === "cancel"
307
+ ? {
308
+ kind: "cancel",
309
+ id: continuation.id,
310
+ sourceId: continuation.sourceId,
311
+ answers: {},
312
+ }
313
+ : {
314
+ kind: "answers",
315
+ id: continuation.id,
316
+ sourceId: continuation.sourceId,
317
+ ...(typeof continuation.wakeAt === "number" ? { wakeAt: continuation.wakeAt } : {}),
318
+ answers: readAnswers(snapshot, continuation.answers),
319
+ },
320
+ };
321
+ }
322
+
323
+ function restore(raw: unknown, initial: TreeNode): R["snapshot"] {
324
+ const saved = runtime.restore(raw);
325
+ checkChildProgress(initial, saved);
326
+ return saved;
327
+ }
328
+
329
+ async function load(owner: string, id: string) {
330
+ if (!isId(owner) || !isId(id))
331
+ throw new TypeError("Provide an authenticated owner and run id.");
332
+ const row = await runs.read(id, owner);
333
+ if (!row || row.owner !== owner || row.kind !== kind)
334
+ throw new Error("This background run was not found for this owner and agent.");
335
+ const initial = segment(row.input);
336
+ const result = row.status === "succeeded" ? settled(row.result) : undefined;
337
+ const snapshot = restore(
338
+ result ? result.snapshot : (row.checkpoint ?? initial.snapshot),
339
+ initial.snapshot,
340
+ );
341
+ if (row.status === "succeeded" && snapshot.state.status === "running")
342
+ throw new TypeError("The host segment ended without a settled agent journal.");
343
+ return { row, initial, snapshot, session: result?.session };
344
+ }
345
+
346
+ async function read(owner: string, id: string): Promise<BackgroundRun<unknown, R>> {
347
+ const { row, snapshot, session } = await load(owner, id);
348
+ return {
349
+ id: row.id,
350
+ status: row.status,
351
+ snapshot,
352
+ wakeAt: wakeAt(snapshot),
353
+ outcome:
354
+ snapshot.state.status === "running"
355
+ ? null
356
+ : { ...runtime.hydrate(snapshot), ...(session ? { session } : {}) },
357
+ error: row.error,
358
+ };
359
+ }
360
+
361
+ async function create(owner: string, initial: Segment): Promise<{ id: string }> {
362
+ // Input is stored in the create transaction, before any id is acknowledged or queued.
363
+ const spec = { kind, owner, restart: "resume" as const, input: copyData(initial) };
364
+ const created =
365
+ options.createContinuation && initial.continuation
366
+ ? await options.createContinuation(
367
+ immutableCopy({ ...spec, input: { ...initial, continuation: initial.continuation } }),
368
+ )
369
+ : await runs.create(spec);
370
+ if (options.createContinuation && initial.continuation) {
371
+ const saved = await runs.read(created.id, owner);
372
+ if (
373
+ !saved ||
374
+ saved.owner !== owner ||
375
+ saved.kind !== kind ||
376
+ !equalData(saved.input, initial)
377
+ )
378
+ throw new Error(
379
+ "The continuation host must commit the exact input before returning its id.",
380
+ );
381
+ }
382
+ try {
383
+ await enqueue(created.id);
384
+ } catch (cause) {
385
+ throw new BackgroundEnqueueError(created.id, cause);
386
+ }
387
+ return created;
388
+ }
389
+
390
+ async function drive(run: BackgroundWorker): Promise<Settled> {
391
+ run.signal.throwIfAborted();
392
+ // Capability refusal happens before policy, model or tool work. No timer survives drive.
393
+ const progress = createProgress(run, events);
394
+ try {
395
+ return await execute(run, progress);
396
+ } finally {
397
+ try {
398
+ await progress.flush();
399
+ } finally {
400
+ await progress.dispose();
401
+ }
402
+ }
403
+ }
404
+
405
+ async function execute(
406
+ run: BackgroundWorker,
407
+ progress: ReturnType<typeof createProgress>,
408
+ ): Promise<Settled> {
409
+ const signal = AbortSignal.any([run.signal, progress.signal]);
410
+ const initial = segment(run.input);
411
+ const snapshot = restore(run.checkpoint ?? initial.snapshot, initial.snapshot);
412
+ const trusted = await untilAbort(
413
+ policy({
414
+ owner: run.owner,
415
+ runId: snapshot.runId,
416
+ segmentId: run.id,
417
+ continuation: initial.continuation,
418
+ }),
419
+ run.signal,
420
+ );
421
+ run.signal.throwIfAborted();
422
+ // From the stored owner, never from the request that queued this segment.
423
+ const session =
424
+ snapshot.kind === "agent" && snapshot.session
425
+ ? await sessionFor(run.owner, snapshot.session.id, run.signal)
426
+ : undefined;
427
+ const memory = await memoryFor(run.owner, signal);
428
+ checkMemoryBinding(snapshot, memory);
429
+ run.signal.throwIfAborted();
430
+ if (initial.continuation?.wakeAt !== undefined && Date.now() < initial.continuation.wakeAt)
431
+ throw new Error("The saved workflow wake is not due yet.");
432
+ if (initial.continuation) {
433
+ await untilAbort(Promise.resolve(trusted.authorizeResume(immutableCopy(snapshot))), signal);
434
+ await untilAbort(
435
+ Promise.resolve(
436
+ trusted.claimContinuation(
437
+ immutableCopy(initial.snapshot),
438
+ immutableCopy(initial.continuation),
439
+ ),
440
+ ),
441
+ run.signal,
442
+ );
443
+ }
444
+ if (run.resumed) await progress.resync(run.crashes);
445
+ const parents = new Map<string, BackgroundWorker>([[snapshot.runId, run]]);
446
+ const host: AgentHost & { authorizeResume: BackgroundPolicy["authorizeResume"] } = {
447
+ progress,
448
+ authorizeResume(saved) {
449
+ run.signal.throwIfAborted();
450
+ return untilAbort(Promise.resolve(trusted.authorizeResume(saved)), run.signal);
451
+ },
452
+ prepareRequest: (request) => trusted.prepareRequest(request),
453
+ resolveRequest: (request, evidence) => trusted.resolveRequest(request, evidence),
454
+ beforeTool: (request, decided) => trusted.beforeTool(request, decided),
455
+ ...(trusted.beforeStep ? { beforeStep: trusted.beforeStep } : {}),
456
+ ...(trusted.reconcileStep ? { reconcileStep: trusted.reconcileStep } : {}),
457
+ ...(trusted.reconcileToolRetry ? { reconcileToolRetry: trusted.reconcileToolRetry } : {}),
458
+ ...(trusted.needsApproval ? { needsApproval: trusted.needsApproval } : {}),
459
+ ...(trusted.answerNow ? { answerNow: trusted.answerNow } : {}),
460
+ canRunConcurrently: (request) => trusted.canRunConcurrently?.(request) === true,
461
+ ...(trusted.loadMedia ? { loadMedia: trusted.loadMedia } : {}),
462
+ ...(trusted.inbox ? { inbox: trusted.inbox } : {}),
463
+ async checkpoint(saved) {
464
+ run.signal.throwIfAborted();
465
+ await run.save(saved);
466
+ },
467
+ async child(request, execute) {
468
+ const parent = parents.get(request.parentRunId);
469
+ if (!parent) throw new Error("The child's active host parent is missing.");
470
+ let key = request.snapshot.runId;
471
+ for (;;) {
472
+ let executed = false;
473
+ const result = await parent.child<ChildEnvelope>(
474
+ key,
475
+ {
476
+ kind,
477
+ input: { format: 1, snapshot: request.snapshot },
478
+ restart: "resume",
479
+ },
480
+ async (child) => {
481
+ executed = true;
482
+ parents.set(request.snapshot.runId, child);
483
+ try {
484
+ const envelope = await execute();
485
+ run.signal.throwIfAborted();
486
+ return { ...envelope, reference: child.id };
487
+ } finally {
488
+ parents.delete(request.snapshot.runId);
489
+ }
490
+ },
491
+ );
492
+ run.signal.throwIfAborted();
493
+ if (!result.ok) throw new Error(`The host child failed: ${result.error.code}.`);
494
+ const envelope = result.value;
495
+ if (executed || envelope.snapshot.state.status !== "suspended") return envelope;
496
+ // A successful host row cannot reopen. Walk past cached suspensions to a new
497
+ // keyed segment. Completed receipts still return without invoking execute.
498
+ if (!isId(envelope.reference))
499
+ throw new Error("The suspended child has no host reference.");
500
+ key = JSON.stringify([request.snapshot.runId, "after", envelope.reference]);
501
+ }
502
+ },
503
+ };
504
+ // A recovered segment may already have saved some decisions. Reuse only still-open
505
+ // ids from this exact claim; never apply the old evidence to a replacement request.
506
+ const pending = new Set(openRequests(snapshot).map((request) => request.id));
507
+ const answers = Object.fromEntries(
508
+ Object.entries(initial.continuation?.answers ?? {}).filter(([id]) => pending.has(id)),
509
+ );
510
+ async function notifySegment(phase: "start" | "end", saved: TreeNode): Promise<void> {
511
+ if (!options.onSegment) return;
512
+ signal.throwIfAborted();
513
+ const journal = immutableCopy(saved);
514
+ await untilAbort(Promise.resolve(host.authorizeResume(journal)), signal);
515
+ signal.throwIfAborted();
516
+ await untilAbort(
517
+ Promise.resolve(
518
+ options.onSegment(
519
+ Object.freeze({
520
+ phase,
521
+ owner: run.owner,
522
+ id: run.id,
523
+ runId: journal.runId,
524
+ signal,
525
+ state: journal.state,
526
+ snapshot: journal,
527
+ }),
528
+ ),
529
+ ),
530
+ signal,
531
+ );
532
+ signal.throwIfAborted();
533
+ }
534
+ await notifySegment("start", snapshot);
535
+ const result = await runtime.resume(snapshot, {
536
+ // The host lease remains live so authorization, checkpoints and segment end still run.
537
+ // This signal stops local execution only; it does not grant a remote CancelTask.
538
+ signal:
539
+ initial.continuation?.kind === "cancel"
540
+ ? AbortSignal.any([signal, AbortSignal.abort()])
541
+ : signal,
542
+ context: trusted.context,
543
+ onEvent: trusted.onEvent,
544
+ onLifecycle: trusted.onLifecycle,
545
+ bindModelProvider: trusted.bindModelProvider,
546
+ memory,
547
+ host,
548
+ ...(session ? { session } : {}),
549
+ answers,
550
+ });
551
+ // The portable loop reports cancellation as data. The run service needs its control
552
+ // exception back, or a cancelled/lost/draining worker could record a successful job.
553
+ run.signal.throwIfAborted();
554
+ await notifySegment("end", result.snapshot);
555
+ return {
556
+ format: 1,
557
+ snapshot: result.snapshot,
558
+ ...("session" in result && result.session ? { session: result.session } : {}),
559
+ };
560
+ }
561
+
562
+ const handlers: Readonly<Record<string, (run: BackgroundWorker) => Promise<unknown>>> =
563
+ Object.freeze({ [kind]: drive });
564
+ return Object.freeze({
565
+ handlers,
566
+ /** Saves the run before returning its id. With `sessionId`, the session's history is read
567
+ * here, inside the authenticated request, and frozen into the run. `context` is only for
568
+ * resolving instructions and tools here; worker tools use policy.context. `signal` stops
569
+ * creation; it does not cancel the run once it is saved. */
570
+ async start(
571
+ owner: string,
572
+ input: I,
573
+ start: Pick<RunOptions, "runId" | "signal" | "context" | "enabledTools"> & {
574
+ sessionId?: string;
575
+ modelSettings?: RecordedModelSettings;
576
+ } = {},
577
+ ): Promise<{ id: string }> {
578
+ if (!isId(owner)) throw new TypeError("Provide an authenticated owner.");
579
+ if (
580
+ !isRecord(start) ||
581
+ (start.runId !== undefined && !isId(start.runId)) ||
582
+ (start.sessionId !== undefined && !isId(start.sessionId)) ||
583
+ (start.signal !== undefined && !(start.signal instanceof AbortSignal))
584
+ )
585
+ throw new TypeError("Use non-empty run/session ids and an AbortSignal when supplied.");
586
+ checkOptions(start);
587
+ const modelSettings = readModelSettings(start.modelSettings);
588
+ if (modelSettings.onActivity || modelSettings.onRateLimit)
589
+ throw new TypeError(
590
+ "Background modelSettings cannot keep observers. Set onActivity and onRateLimit on the agent instead.",
591
+ );
592
+ const signal = start.signal ?? new AbortController().signal;
593
+ signal.throwIfAborted();
594
+ const session =
595
+ start.sessionId === undefined
596
+ ? undefined
597
+ : await sessionFor(owner, start.sessionId, signal);
598
+ const memory = await memoryFor(owner, signal);
599
+ const snapshot = await runtime.open(
600
+ input,
601
+ { ...start, memory, session, historyLimit, prepareHistory, signal },
602
+ start.runId ?? crypto.randomUUID(),
603
+ );
604
+ signal.throwIfAborted();
605
+ return create(owner, { format: 1, snapshot: runtime.restore(snapshot) });
606
+ },
607
+ read,
608
+ async *observe(
609
+ owner: string,
610
+ id: string,
611
+ afterSeq = 0,
612
+ signal?: AbortSignal,
613
+ ): AsyncGenerator<RunEvent> {
614
+ await load(owner, id);
615
+ for await (const event of runs.tail(id, afterSeq, signal)) {
616
+ if (signal?.aborted) return;
617
+ yield event;
618
+ }
619
+ },
620
+ async wait(
621
+ owner: string,
622
+ id: string,
623
+ signal?: AbortSignal,
624
+ ): Promise<BackgroundRun<unknown, R>> {
625
+ await load(owner, id);
626
+ for await (const _event of runs.tail(id, 0, signal)) signal?.throwIfAborted();
627
+ signal?.throwIfAborted();
628
+ return read(owner, id);
629
+ },
630
+ async cancel(owner: string, id: string): Promise<BackgroundCancelResult> {
631
+ const { row, snapshot, initial } = await load(owner, id);
632
+ // A second Stop must not abort the worker that still needs to save logical cancellation.
633
+ if (initial.continuation?.kind === "cancel") return { id, requested: true };
634
+ if (row.status === "succeeded" && snapshot.state.status === "suspended") {
635
+ if (!options.createContinuation)
636
+ throw new TypeError(
637
+ "Cancelling a suspended run requires the host's durable createContinuation capability. No segment was created.",
638
+ );
639
+ const continuation: Continuation = {
640
+ id: `cancel/${id}`,
641
+ sourceId: id,
642
+ kind: "cancel",
643
+ answers: {},
644
+ };
645
+ // The new worker must claim the current logical segment under its owner's policy.
646
+ // A repeated command has the same claim; a different worker cannot consume it again.
647
+ const created = await create(owner, { format: 1, snapshot, continuation });
648
+ return { id: created.id, requested: true };
649
+ }
650
+ if (row.status !== "queued" && row.status !== "running") return { id, requested: false };
651
+ return { id, requested: await runs.cancel(id) };
652
+ },
653
+ /** Queues decision evidence, not permission. The leased worker claims it; read or wait
654
+ * for that segment's outcome to learn whether the host accepted it. */
655
+ async resume(
656
+ owner: string,
657
+ id: string,
658
+ answers: Readonly<Record<string, unknown>>,
659
+ ): Promise<{ id: string }> {
660
+ const { row, snapshot } = await load(owner, id);
661
+ if (row.status !== "succeeded" || snapshot.state.status !== "suspended")
662
+ throw new Error("Only a settled, suspended agent segment can accept a decision.");
663
+ const submitted = readAnswers(snapshot, answers);
664
+ if (!Object.keys(submitted).length) {
665
+ const at = wakeAt(snapshot);
666
+ if (at === undefined || at > Date.now())
667
+ throw new TypeError(
668
+ at === undefined
669
+ ? "Provide at least one answer by request id."
670
+ : `This workflow wakes at ${at}. Continue at or after that time.`,
671
+ );
672
+ }
673
+ if (
674
+ openRequests(snapshot).some(
675
+ (request) =>
676
+ Object.hasOwn(submitted, request.id) && request.scope.expiresAt <= Date.now(),
677
+ )
678
+ )
679
+ throw new Error("A request expired. Ask the host to renew it before continuing.");
680
+ const evidence = {
681
+ sourceId: id,
682
+ answers: submitted,
683
+ ...(!Object.keys(submitted).length ? { wakeAt: wakeAt(snapshot) } : {}),
684
+ };
685
+ const continuation: Continuation = {
686
+ kind: "answers",
687
+ // With durable admission an uncertain response must reconcile the same exact claim.
688
+ id: options.createContinuation
689
+ ? await requestHash({ owner, ...evidence })
690
+ : crypto.randomUUID(),
691
+ ...evidence,
692
+ };
693
+ return create(owner, { format: 1, snapshot, continuation });
694
+ },
695
+ });
696
+ }