@providerkit/agents 0.1.0 → 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 (291) hide show
  1. package/LICENSE-APACHE-2.0 +202 -0
  2. package/README.md +2108 -52
  3. package/THIRD_PARTY_NOTICES.md +521 -0
  4. package/dist/a2a/auth.d.ts +10 -0
  5. package/dist/a2a/auth.d.ts.map +1 -0
  6. package/dist/a2a/auth.js +52 -0
  7. package/dist/a2a/auth.js.map +1 -0
  8. package/dist/a2a/client.d.ts +74 -0
  9. package/dist/a2a/client.d.ts.map +1 -0
  10. package/dist/a2a/client.js +601 -0
  11. package/dist/a2a/client.js.map +1 -0
  12. package/dist/a2a/index.d.ts +22 -0
  13. package/dist/a2a/index.d.ts.map +1 -0
  14. package/dist/a2a/index.js +11 -0
  15. package/dist/a2a/index.js.map +1 -0
  16. package/dist/a2a/memory-runs.d.ts +62 -0
  17. package/dist/a2a/memory-runs.d.ts.map +1 -0
  18. package/dist/a2a/memory-runs.js +349 -0
  19. package/dist/a2a/memory-runs.js.map +1 -0
  20. package/dist/a2a/policy.d.ts +15 -0
  21. package/dist/a2a/policy.d.ts.map +1 -0
  22. package/dist/a2a/policy.js +114 -0
  23. package/dist/a2a/policy.js.map +1 -0
  24. package/dist/a2a/push.d.ts +34 -0
  25. package/dist/a2a/push.d.ts.map +1 -0
  26. package/dist/a2a/push.js +180 -0
  27. package/dist/a2a/push.js.map +1 -0
  28. package/dist/a2a/remote.d.ts +155 -0
  29. package/dist/a2a/remote.d.ts.map +1 -0
  30. package/dist/a2a/remote.js +1196 -0
  31. package/dist/a2a/remote.js.map +1 -0
  32. package/dist/a2a/server.d.ts +110 -0
  33. package/dist/a2a/server.d.ts.map +1 -0
  34. package/dist/a2a/server.js +1139 -0
  35. package/dist/a2a/server.js.map +1 -0
  36. package/dist/a2a/signing.d.ts +21 -0
  37. package/dist/a2a/signing.d.ts.map +1 -0
  38. package/dist/a2a/signing.js +305 -0
  39. package/dist/a2a/signing.js.map +1 -0
  40. package/dist/a2a/tasks.d.ts +88 -0
  41. package/dist/a2a/tasks.d.ts.map +1 -0
  42. package/dist/a2a/tasks.js +170 -0
  43. package/dist/a2a/tasks.js.map +1 -0
  44. package/dist/a2a/wire.d.ts +267 -0
  45. package/dist/a2a/wire.d.ts.map +1 -0
  46. package/dist/a2a/wire.js +1202 -0
  47. package/dist/a2a/wire.js.map +1 -0
  48. package/dist/background-types.d.ts +76 -0
  49. package/dist/background-types.d.ts.map +1 -0
  50. package/dist/background-types.js +2 -0
  51. package/dist/background-types.js.map +1 -0
  52. package/dist/child.d.ts +25 -0
  53. package/dist/child.d.ts.map +1 -0
  54. package/dist/child.js +129 -0
  55. package/dist/child.js.map +1 -0
  56. package/dist/code-driver.d.ts +40 -0
  57. package/dist/code-driver.d.ts.map +1 -0
  58. package/dist/code-driver.js +2 -0
  59. package/dist/code-driver.js.map +1 -0
  60. package/dist/code-mode.d.ts +3 -0
  61. package/dist/code-mode.d.ts.map +1 -0
  62. package/dist/code-mode.js +2 -0
  63. package/dist/code-mode.js.map +1 -0
  64. package/dist/code-script.d.ts +3 -0
  65. package/dist/code-script.d.ts.map +1 -0
  66. package/dist/code-script.js +149 -0
  67. package/dist/code-script.js.map +1 -0
  68. package/dist/code.d.ts +75 -0
  69. package/dist/code.d.ts.map +1 -0
  70. package/dist/code.js +326 -0
  71. package/dist/code.js.map +1 -0
  72. package/dist/compaction.d.ts +15 -0
  73. package/dist/compaction.d.ts.map +1 -0
  74. package/dist/compaction.js +168 -0
  75. package/dist/compaction.js.map +1 -0
  76. package/dist/delegation.d.ts +85 -16
  77. package/dist/delegation.d.ts.map +1 -1
  78. package/dist/delegation.js +240 -106
  79. package/dist/delegation.js.map +1 -1
  80. package/dist/evals/driver.d.ts +10 -0
  81. package/dist/evals/driver.d.ts.map +1 -0
  82. package/dist/evals/driver.js +192 -0
  83. package/dist/evals/driver.js.map +1 -0
  84. package/dist/evals/journal.d.ts +26 -0
  85. package/dist/evals/journal.d.ts.map +1 -0
  86. package/dist/evals/journal.js +483 -0
  87. package/dist/evals/journal.js.map +1 -0
  88. package/dist/evals/judge.d.ts +31 -0
  89. package/dist/evals/judge.d.ts.map +1 -0
  90. package/dist/evals/judge.js +142 -0
  91. package/dist/evals/judge.js.map +1 -0
  92. package/dist/evals/report.d.ts +38 -0
  93. package/dist/evals/report.d.ts.map +1 -0
  94. package/dist/evals/report.js +241 -0
  95. package/dist/evals/report.js.map +1 -0
  96. package/dist/evals/runner.d.ts +24 -0
  97. package/dist/evals/runner.d.ts.map +1 -0
  98. package/dist/evals/runner.js +655 -0
  99. package/dist/evals/runner.js.map +1 -0
  100. package/dist/evals/scorers.d.ts +36 -0
  101. package/dist/evals/scorers.d.ts.map +1 -0
  102. package/dist/evals/scorers.js +259 -0
  103. package/dist/evals/scorers.js.map +1 -0
  104. package/dist/evals/simulation.d.ts +7 -0
  105. package/dist/evals/simulation.d.ts.map +1 -0
  106. package/dist/evals/simulation.js +38 -0
  107. package/dist/evals/simulation.js.map +1 -0
  108. package/dist/evals/testing.d.ts +36 -0
  109. package/dist/evals/testing.d.ts.map +1 -0
  110. package/dist/evals/testing.js +87 -0
  111. package/dist/evals/testing.js.map +1 -0
  112. package/dist/evals/trajectory.d.ts +11 -0
  113. package/dist/evals/trajectory.d.ts.map +1 -0
  114. package/dist/evals/trajectory.js +180 -0
  115. package/dist/evals/trajectory.js.map +1 -0
  116. package/dist/evals/types.d.ts +431 -0
  117. package/dist/evals/types.d.ts.map +1 -0
  118. package/dist/evals/types.js +4 -0
  119. package/dist/evals/types.js.map +1 -0
  120. package/dist/evals.d.ts +14 -0
  121. package/dist/evals.d.ts.map +1 -0
  122. package/dist/evals.js +9 -0
  123. package/dist/evals.js.map +1 -0
  124. package/dist/extensions.d.ts +33 -0
  125. package/dist/extensions.d.ts.map +1 -0
  126. package/dist/extensions.js +188 -0
  127. package/dist/extensions.js.map +1 -0
  128. package/dist/handoff.d.ts +58 -0
  129. package/dist/handoff.d.ts.map +1 -0
  130. package/dist/handoff.js +160 -0
  131. package/dist/handoff.js.map +1 -0
  132. package/dist/index.d.ts +14 -0
  133. package/dist/index.d.ts.map +1 -1
  134. package/dist/index.js +8 -0
  135. package/dist/index.js.map +1 -1
  136. package/dist/input.d.ts +42 -0
  137. package/dist/input.d.ts.map +1 -0
  138. package/dist/input.js +266 -0
  139. package/dist/input.js.map +1 -0
  140. package/dist/mcp.d.ts +77 -0
  141. package/dist/mcp.d.ts.map +1 -0
  142. package/dist/mcp.js +505 -0
  143. package/dist/mcp.js.map +1 -0
  144. package/dist/memory-store.d.ts +11 -0
  145. package/dist/memory-store.d.ts.map +1 -0
  146. package/dist/memory-store.js +272 -0
  147. package/dist/memory-store.js.map +1 -0
  148. package/dist/memory.d.ts +212 -0
  149. package/dist/memory.d.ts.map +1 -0
  150. package/dist/memory.js +613 -0
  151. package/dist/memory.js.map +1 -0
  152. package/dist/otel.d.ts +74 -0
  153. package/dist/otel.d.ts.map +1 -0
  154. package/dist/otel.js +427 -0
  155. package/dist/otel.js.map +1 -0
  156. package/dist/progress.d.ts +17 -0
  157. package/dist/progress.d.ts.map +1 -0
  158. package/dist/progress.js +193 -0
  159. package/dist/progress.js.map +1 -0
  160. package/dist/quickjs.d.ts +19 -0
  161. package/dist/quickjs.d.ts.map +1 -0
  162. package/dist/quickjs.js +519 -0
  163. package/dist/quickjs.js.map +1 -0
  164. package/dist/recovery.d.ts +10 -0
  165. package/dist/recovery.d.ts.map +1 -0
  166. package/dist/recovery.js +62 -0
  167. package/dist/recovery.js.map +1 -0
  168. package/dist/request.d.ts +88 -0
  169. package/dist/request.d.ts.map +1 -0
  170. package/dist/request.js +422 -0
  171. package/dist/request.js.map +1 -0
  172. package/dist/run.d.ts +16 -4
  173. package/dist/run.d.ts.map +1 -1
  174. package/dist/run.js +2016 -245
  175. package/dist/run.js.map +1 -1
  176. package/dist/runs.d.ts +77 -34
  177. package/dist/runs.d.ts.map +1 -1
  178. package/dist/runs.js +267 -85
  179. package/dist/runs.js.map +1 -1
  180. package/dist/schema-to-ts.d.ts +4 -0
  181. package/dist/schema-to-ts.d.ts.map +1 -0
  182. package/dist/schema-to-ts.js +191 -0
  183. package/dist/schema-to-ts.js.map +1 -0
  184. package/dist/session.d.ts +23 -0
  185. package/dist/session.d.ts.map +1 -0
  186. package/dist/session.js +137 -0
  187. package/dist/session.js.map +1 -0
  188. package/dist/snapshot.d.ts +57 -8
  189. package/dist/snapshot.d.ts.map +1 -1
  190. package/dist/snapshot.js +1206 -109
  191. package/dist/snapshot.js.map +1 -1
  192. package/dist/steering.d.ts +75 -0
  193. package/dist/steering.d.ts.map +1 -0
  194. package/dist/steering.js +214 -0
  195. package/dist/steering.js.map +1 -0
  196. package/dist/subagents.d.ts +141 -0
  197. package/dist/subagents.d.ts.map +1 -0
  198. package/dist/subagents.js +746 -0
  199. package/dist/subagents.js.map +1 -0
  200. package/dist/tool-retry.d.ts +12 -0
  201. package/dist/tool-retry.d.ts.map +1 -0
  202. package/dist/tool-retry.js +53 -0
  203. package/dist/tool-retry.js.map +1 -0
  204. package/dist/tree.d.ts +62 -6
  205. package/dist/tree.d.ts.map +1 -1
  206. package/dist/tree.js +192 -23
  207. package/dist/tree.js.map +1 -1
  208. package/dist/types.d.ts +767 -52
  209. package/dist/types.d.ts.map +1 -1
  210. package/dist/workflow-snapshot.d.ts +8 -0
  211. package/dist/workflow-snapshot.d.ts.map +1 -0
  212. package/dist/workflow-snapshot.js +276 -0
  213. package/dist/workflow-snapshot.js.map +1 -0
  214. package/dist/workflow-types.d.ts +171 -0
  215. package/dist/workflow-types.d.ts.map +1 -0
  216. package/dist/workflow-types.js +2 -0
  217. package/dist/workflow-types.js.map +1 -0
  218. package/dist/workflow.d.ts +19 -0
  219. package/dist/workflow.d.ts.map +1 -0
  220. package/dist/workflow.js +1053 -0
  221. package/dist/workflow.js.map +1 -0
  222. package/examples/a2a-remote.ts +85 -0
  223. package/examples/a2a-server.ts +100 -0
  224. package/examples/background.ts +18 -4
  225. package/examples/code-mode.ts +76 -0
  226. package/examples/conversation.ts +57 -0
  227. package/examples/evals.ts +79 -0
  228. package/examples/guardrails.ts +56 -0
  229. package/examples/handoff.ts +79 -0
  230. package/examples/memory.ts +44 -0
  231. package/examples/otel.ts +99 -0
  232. package/examples/steering.ts +69 -0
  233. package/examples/structured-handoff.ts +92 -0
  234. package/examples/subagents.ts +127 -0
  235. package/examples/workflow.ts +74 -0
  236. package/package.json +58 -6
  237. package/src/a2a/auth.ts +62 -0
  238. package/src/a2a/client.ts +733 -0
  239. package/src/a2a/index.ts +74 -0
  240. package/src/a2a/memory-runs.ts +448 -0
  241. package/src/a2a/policy.ts +148 -0
  242. package/src/a2a/push.ts +251 -0
  243. package/src/a2a/remote.ts +1652 -0
  244. package/src/a2a/server.ts +1390 -0
  245. package/src/a2a/signing.ts +348 -0
  246. package/src/a2a/tasks.ts +260 -0
  247. package/src/a2a/wire.ts +1443 -0
  248. package/src/background-types.ts +86 -0
  249. package/src/child.ts +181 -0
  250. package/src/code-driver.ts +48 -0
  251. package/src/code-mode.ts +12 -0
  252. package/src/code-script.ts +149 -0
  253. package/src/code.ts +424 -0
  254. package/src/compaction.ts +212 -0
  255. package/src/delegation.ts +444 -155
  256. package/src/evals/driver.ts +222 -0
  257. package/src/evals/journal.ts +605 -0
  258. package/src/evals/judge.ts +188 -0
  259. package/src/evals/report.ts +295 -0
  260. package/src/evals/runner.ts +826 -0
  261. package/src/evals/scorers.ts +339 -0
  262. package/src/evals/simulation.ts +46 -0
  263. package/src/evals/testing.ts +126 -0
  264. package/src/evals/trajectory.ts +223 -0
  265. package/src/evals/types.ts +463 -0
  266. package/src/evals.ts +72 -0
  267. package/src/extensions.ts +247 -0
  268. package/src/handoff.ts +214 -0
  269. package/src/index.ts +51 -0
  270. package/src/input.ts +319 -0
  271. package/src/mcp.ts +690 -0
  272. package/src/memory-store.ts +366 -0
  273. package/src/memory.ts +893 -0
  274. package/src/otel.ts +568 -0
  275. package/src/progress.ts +214 -0
  276. package/src/quickjs.ts +524 -0
  277. package/src/recovery.ts +90 -0
  278. package/src/request.ts +513 -0
  279. package/src/run.ts +2678 -313
  280. package/src/runs.ts +464 -133
  281. package/src/schema-to-ts.ts +194 -0
  282. package/src/session.ts +178 -0
  283. package/src/snapshot.ts +1595 -124
  284. package/src/steering.ts +329 -0
  285. package/src/subagents.ts +1084 -0
  286. package/src/tool-retry.ts +86 -0
  287. package/src/tree.ts +223 -27
  288. package/src/types.ts +711 -52
  289. package/src/workflow-snapshot.ts +366 -0
  290. package/src/workflow-types.ts +213 -0
  291. package/src/workflow.ts +1316 -0
package/src/runs.ts CHANGED
@@ -1,14 +1,44 @@
1
- import type { createRuns, Run, RunEvent, RunHandler, StoredRun } from "@gusnips/server/runs";
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";
2
16
  import { AGENT_RUNTIME } from "./delegation.ts";
3
- import { copyData, equalData, immutableCopy, isId, isRecord } from "./snapshot.ts";
4
- import { untilAbort } from "./tree.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";
5
30
  import type {
6
31
  Agent,
7
32
  AgentHost,
33
+ AgentInput,
8
34
  ChildEnvelope,
35
+ RecordedModelSettings,
9
36
  RunOptions,
10
37
  RunOutcome,
11
- RunSnapshot,
38
+ TreeNode,
39
+ ResumeOptions,
40
+ Session,
41
+ SessionStatus,
12
42
  } from "./types.ts";
13
43
 
14
44
  export type BackgroundRuns = Pick<
@@ -16,54 +46,98 @@ export type BackgroundRuns = Pick<
16
46
  "create" | "read" | "tail" | "cancel"
17
47
  >;
18
48
 
19
- export interface Continuation {
20
- /** Unique authorization claim, distinct from both the logical run and the host row. */
21
- id: string;
22
- sourceId: string;
23
- decision: unknown;
24
- }
25
-
26
- export interface BackgroundContext {
27
- /** From the authenticated caller, or from Run.owner inside a worker. */
28
- owner: string;
29
- segmentId: string;
30
- continuation?: Continuation;
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>>;
31
61
  }
32
62
 
33
- export interface BackgroundPolicy
34
- extends
35
- Required<
36
- Pick<AgentHost, "authorizeResume" | "approvalContext" | "resolveApproval" | "beforeTool">
37
- >,
38
- Pick<AgentHost, "canRunConcurrently"> {
39
- /** Worker-only values for tools, such as the authenticated actor or a database handle.
40
- * Never serialized. The SDK supplies reserved operation IDs and cancellation signals. */
41
- context?: RunOptions["context"];
42
- /** Called under the worker's lease, after its row exists. Authenticate the decision,
43
- * recheck resource version/expiry and atomically reserve this approval for continuation.id
44
- * AND context.segmentId. Repeating that exact claim must succeed; any other claim or segment
45
- * must fail. authorizeResume checks ownership on every attempt. resolveApproval may reuse a
46
- * consumed decision only for this same claim/segment. These guarantees need durable host state. */
47
- claimContinuation: (snapshot: RunSnapshot, continuation: Continuation) => void | Promise<void>;
48
- }
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";
49
81
 
50
- export interface BackgroundOptions<T> {
82
+ export interface BackgroundOptions<T> extends BackgroundBase {
51
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 {
52
98
  /** Dedicated handler key for this agent version. */
53
99
  kind: string;
100
+ /** Injected create must resolve after its transaction commits. Only then is enqueue called. */
54
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;
55
110
  /** Await durable queue acceptance. A worker calls runs.drive(id, background.handlers).
56
111
  * The host must also run runs.sweep on boot and periodically, and drain on shutdown. */
57
112
  enqueue: (id: string) => Promise<void>;
58
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"];
59
128
  }
60
129
 
61
- export interface BackgroundRun<T> {
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>> {
62
133
  id: string;
63
134
  /** Host completion is not SDK completion: a successful segment can be suspended or failed. */
64
135
  status: StoredRun["status"];
65
- snapshot: RunSnapshot;
66
- outcome: RunOutcome<T> | null;
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;
67
141
  error: StoredRun["error"];
68
142
  }
69
143
 
@@ -81,62 +155,114 @@ export class BackgroundEnqueueError extends Error {
81
155
  }
82
156
  }
83
157
 
84
- interface Segment {
158
+ interface Segment<N extends TreeNode = TreeNode> {
85
159
  format: 1;
86
- snapshot: RunSnapshot;
160
+ snapshot: N;
87
161
  continuation?: Continuation;
88
162
  }
89
163
 
90
- /** Restore only the original pending route, using the latest receipts throughout.
91
- * Ancestors become running during coordination, before the leaf consumes its decision. */
92
- function restoreApprovalRoute(snapshot: RunSnapshot, initial: RunSnapshot): boolean {
93
- const pending = initial.state;
94
- if (pending.status !== "suspended") return false;
95
- const route = [snapshot];
96
- let node = snapshot;
97
- for (const step of pending.path) {
98
- const child = node.delegations
99
- .find((journal) => journal.operationId === step.operationId)
100
- ?.children.find((child) => child.key === step.key && child.snapshot.runId === step.runId);
101
- if (!child) return false;
102
- node = child.snapshot;
103
- route.push(node);
104
- }
105
- if (node.state.status !== "suspended" || !equalData(node.state.approval, pending.approval))
106
- return false;
107
- for (const [index, ancestor] of route.entries()) {
108
- const state = ancestor.state;
109
- if (
110
- state.status !== "running" &&
111
- !(
112
- state.status === "suspended" &&
113
- equalData(state.approval, pending.approval) &&
114
- equalData(state.path, pending.path.slice(index))
115
- )
116
- )
117
- return false;
118
- }
119
- for (const [index, ancestor] of route.entries())
120
- ancestor.state = { ...copyData(pending), path: pending.path.slice(index) };
121
- return true;
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 };
122
179
  }
123
180
 
124
181
  /** Background work uses the host's lease, queue and cancellation. Children stay in-process.
125
182
  * Usage remains in stable SDK receipts; this binding never calls additive Run.spend. */
126
- export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
127
- const { agent, kind, runs, enqueue } = options;
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".');
128
228
  if (!isId(kind) || typeof enqueue !== "function" || typeof options.policy !== "function")
129
229
  throw new TypeError(
130
230
  "Provide a run kind, a durable enqueue callback and a trusted policy factory.",
131
231
  );
132
- const runtime = agent[AGENT_RUNTIME];
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
+ }
133
259
 
134
260
  async function policy(context: BackgroundContext): Promise<BackgroundPolicy> {
135
261
  const value = await options.policy(immutableCopy(context));
136
262
  for (const key of [
137
263
  "authorizeResume",
138
- "approvalContext",
139
- "resolveApproval",
264
+ "prepareRequest",
265
+ "resolveRequest",
140
266
  "beforeTool",
141
267
  "claimContinuation",
142
268
  ] as const)
@@ -145,7 +271,7 @@ export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
145
271
  return value;
146
272
  }
147
273
 
148
- function segment(raw: unknown): Segment {
274
+ function segment(raw: unknown): Segment<R["snapshot"]> {
149
275
  if (!isRecord(raw) || raw.format !== 1)
150
276
  throw new TypeError("This row is not an agent background segment.");
151
277
  const snapshot = runtime.restore(raw.snapshot);
@@ -153,30 +279,50 @@ export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
153
279
  const continuation = raw.continuation;
154
280
  if (
155
281
  !isRecord(continuation) ||
282
+ snapshot.state.status !== "suspended" ||
156
283
  !isId(continuation.id) ||
157
284
  !isId(continuation.sourceId) ||
158
- continuation.decision === undefined
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)))
159
300
  )
160
301
  throw new TypeError("The saved continuation is invalid.");
161
302
  return {
162
303
  format: 1,
163
304
  snapshot,
164
- continuation: {
165
- id: continuation.id,
166
- sourceId: continuation.sourceId,
167
- decision: copyData(continuation.decision),
168
- },
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
+ },
169
320
  };
170
321
  }
171
322
 
172
- function restore(raw: unknown, initial: RunSnapshot): RunSnapshot {
323
+ function restore(raw: unknown, initial: TreeNode): R["snapshot"] {
173
324
  const saved = runtime.restore(raw);
174
- if (
175
- saved.runId !== initial.runId ||
176
- saved.input !== initial.input ||
177
- !equalData(saved.tree, initial.tree)
178
- )
179
- throw new TypeError("The saved journal belongs to another logical run.");
325
+ checkChildProgress(initial, saved);
180
326
  return saved;
181
327
  }
182
328
 
@@ -187,29 +333,52 @@ export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
187
333
  if (!row || row.owner !== owner || row.kind !== kind)
188
334
  throw new Error("This background run was not found for this owner and agent.");
189
335
  const initial = segment(row.input);
336
+ const result = row.status === "succeeded" ? settled(row.result) : undefined;
190
337
  const snapshot = restore(
191
- row.status === "succeeded" ? row.result : (row.checkpoint ?? initial.snapshot),
338
+ result ? result.snapshot : (row.checkpoint ?? initial.snapshot),
192
339
  initial.snapshot,
193
340
  );
194
341
  if (row.status === "succeeded" && snapshot.state.status === "running")
195
342
  throw new TypeError("The host segment ended without a settled agent journal.");
196
- return { row, initial, snapshot };
343
+ return { row, initial, snapshot, session: result?.session };
197
344
  }
198
345
 
199
- async function read(owner: string, id: string): Promise<BackgroundRun<T>> {
200
- const { row, snapshot } = await load(owner, id);
346
+ async function read(owner: string, id: string): Promise<BackgroundRun<unknown, R>> {
347
+ const { row, snapshot, session } = await load(owner, id);
201
348
  return {
202
349
  id: row.id,
203
350
  status: row.status,
204
351
  snapshot,
205
- outcome: snapshot.state.status === "running" ? null : runtime.hydrate(snapshot),
352
+ wakeAt: wakeAt(snapshot),
353
+ outcome:
354
+ snapshot.state.status === "running"
355
+ ? null
356
+ : { ...runtime.hydrate(snapshot), ...(session ? { session } : {}) },
206
357
  error: row.error,
207
358
  };
208
359
  }
209
360
 
210
361
  async function create(owner: string, initial: Segment): Promise<{ id: string }> {
211
362
  // Input is stored in the create transaction, before any id is acknowledged or queued.
212
- const created = await runs.create({ kind, owner, restart: "resume", input: copyData(initial) });
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
+ }
213
382
  try {
214
383
  await enqueue(created.id);
215
384
  } catch (cause) {
@@ -218,20 +387,50 @@ export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
218
387
  return created;
219
388
  }
220
389
 
221
- async function drive(run: Run): Promise<RunSnapshot> {
390
+ async function drive(run: BackgroundWorker): Promise<Settled> {
222
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]);
223
410
  const initial = segment(run.input);
224
411
  const snapshot = restore(run.checkpoint ?? initial.snapshot, initial.snapshot);
225
412
  const trusted = await untilAbort(
226
413
  policy({
227
414
  owner: run.owner,
415
+ runId: snapshot.runId,
228
416
  segmentId: run.id,
229
417
  continuation: initial.continuation,
230
418
  }),
231
419
  run.signal,
232
420
  );
233
421
  run.signal.throwIfAborted();
234
- if (initial.continuation)
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);
235
434
  await untilAbort(
236
435
  Promise.resolve(
237
436
  trusted.claimContinuation(
@@ -241,16 +440,26 @@ export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
241
440
  ),
242
441
  run.signal,
243
442
  );
244
- const parents = new Map<string, Run>([[snapshot.runId, run]]);
443
+ }
444
+ if (run.resumed) await progress.resync(run.crashes);
445
+ const parents = new Map<string, BackgroundWorker>([[snapshot.runId, run]]);
245
446
  const host: AgentHost & { authorizeResume: BackgroundPolicy["authorizeResume"] } = {
447
+ progress,
246
448
  authorizeResume(saved) {
247
449
  run.signal.throwIfAborted();
248
450
  return untilAbort(Promise.resolve(trusted.authorizeResume(saved)), run.signal);
249
451
  },
250
- approvalContext: (request) => trusted.approvalContext(request),
251
- resolveApproval: (approval, decision) => trusted.resolveApproval(approval, decision),
252
- beforeTool: (request, approval) => trusted.beforeTool(request, approval),
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 } : {}),
253
460
  canRunConcurrently: (request) => trusted.canRunConcurrently?.(request) === true,
461
+ ...(trusted.loadMedia ? { loadMedia: trusted.loadMedia } : {}),
462
+ ...(trusted.inbox ? { inbox: trusted.inbox } : {}),
254
463
  async checkpoint(saved) {
255
464
  run.signal.throwIfAborted();
256
465
  await run.save(saved);
@@ -292,38 +501,108 @@ export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
292
501
  }
293
502
  },
294
503
  };
295
- const continuation = initial.continuation;
296
- // Never reapply old evidence to a later approval or roll back a running effect marker.
297
- const pending = initial.snapshot.state;
298
- const decision =
299
- continuation && restoreApprovalRoute(snapshot, initial.snapshot)
300
- ? continuation.decision
301
- : undefined;
302
- const result = await agent.resume(snapshot, {
303
- signal: run.signal,
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,
304
542
  context: trusted.context,
543
+ onEvent: trusted.onEvent,
544
+ onLifecycle: trusted.onLifecycle,
545
+ bindModelProvider: trusted.bindModelProvider,
546
+ memory,
305
547
  host,
306
- ...(decision !== undefined
307
- ? { decision, approvalPath: pending.status === "suspended" ? pending.path : [] }
308
- : {}),
309
- onEvent: (event) => run.emit("agent", event),
548
+ ...(session ? { session } : {}),
549
+ answers,
310
550
  });
311
551
  // The portable loop reports cancellation as data. The run service needs its control
312
552
  // exception back, or a cancelled/lost/draining worker could record a successful job.
313
553
  run.signal.throwIfAborted();
314
- return result.snapshot;
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
+ };
315
560
  }
316
561
 
317
- const handlers: Readonly<Record<string, RunHandler>> = Object.freeze({ [kind]: drive });
562
+ const handlers: Readonly<Record<string, (run: BackgroundWorker) => Promise<unknown>>> =
563
+ Object.freeze({ [kind]: drive });
318
564
  return Object.freeze({
319
565
  handlers,
320
- async start(owner: string, input: string): Promise<{ id: string }> {
321
- if (!isId(owner) || !isId(input))
322
- throw new TypeError("Provide an authenticated owner and non-empty input.");
323
- return create(owner, {
324
- format: 1,
325
- snapshot: runtime.restore(runtime.create(input, crypto.randomUUID())),
326
- });
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) });
327
606
  },
328
607
  read,
329
608
  async *observe(
@@ -338,27 +617,79 @@ export function createBackgroundAgent<T>(options: BackgroundOptions<T>) {
338
617
  yield event;
339
618
  }
340
619
  },
341
- async wait(owner: string, id: string, signal?: AbortSignal): Promise<BackgroundRun<T>> {
620
+ async wait(
621
+ owner: string,
622
+ id: string,
623
+ signal?: AbortSignal,
624
+ ): Promise<BackgroundRun<unknown, R>> {
342
625
  await load(owner, id);
343
626
  for await (const _event of runs.tail(id, 0, signal)) signal?.throwIfAborted();
344
627
  signal?.throwIfAborted();
345
628
  return read(owner, id);
346
629
  },
347
- async cancel(owner: string, id: string): Promise<boolean> {
348
- await load(owner, id);
349
- return runs.cancel(id);
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) };
350
652
  },
351
653
  /** Queues decision evidence, not permission. The leased worker claims it; read or wait
352
654
  * for that segment's outcome to learn whether the host accepted it. */
353
- async resume(owner: string, id: string, decision: unknown): Promise<{ id: string }> {
655
+ async resume(
656
+ owner: string,
657
+ id: string,
658
+ answers: Readonly<Record<string, unknown>>,
659
+ ): Promise<{ id: string }> {
354
660
  const { row, snapshot } = await load(owner, id);
355
661
  if (row.status !== "succeeded" || snapshot.state.status !== "suspended")
356
662
  throw new Error("Only a settled, suspended agent segment can accept a decision.");
357
- if (snapshot.state.approval.scope.expiresAt <= Date.now())
358
- throw new Error("The approval expired. Request a new decision before continuing.");
359
- if (decision === undefined)
360
- throw new TypeError("Provide decision evidence from the authenticated caller.");
361
- const continuation = copyData({ id: crypto.randomUUID(), sourceId: id, 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
+ };
362
693
  return create(owner, { format: 1, snapshot, continuation });
363
694
  },
364
695
  });