@ftrdotdev/pi-delegates 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 (138) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +130 -0
  4. package/README.md +456 -2
  5. package/ROADMAP.md +179 -0
  6. package/TESTING.md +896 -0
  7. package/agents.ts +8 -0
  8. package/examples/README.md +114 -0
  9. package/examples/gated.ts +28 -0
  10. package/index.ts +9 -0
  11. package/package.json +94 -4
  12. package/skills/pi-delegates/SKILL.md +176 -0
  13. package/skills/pi-delegates/references/control.md +159 -0
  14. package/skills/pi-delegates/references/definitions.md +163 -0
  15. package/skills/pi-delegates/references/gates.md +175 -0
  16. package/skills/pi-delegates/references/launch.md +184 -0
  17. package/src/docs-contract.test.ts +106 -0
  18. package/src/domain/definitions.test.ts +41 -0
  19. package/src/domain/definitions.ts +163 -0
  20. package/src/domain/failure.ts +33 -0
  21. package/src/domain/ids.ts +13 -0
  22. package/src/domain/model-source.ts +30 -0
  23. package/src/domain/names.ts +35 -0
  24. package/src/domain/orchestration/admission.ts +78 -0
  25. package/src/domain/orchestration/control.test.ts +1332 -0
  26. package/src/domain/orchestration/control.ts +457 -0
  27. package/src/domain/orchestration/fanout.test.ts +524 -0
  28. package/src/domain/orchestration/fanout.ts +372 -0
  29. package/src/domain/orchestration/gates.test.ts +685 -0
  30. package/src/domain/orchestration/gates.ts +360 -0
  31. package/src/domain/orchestration/launch.test.ts +372 -0
  32. package/src/domain/orchestration/launch.ts +691 -0
  33. package/src/domain/orchestration/requests.test.ts +695 -0
  34. package/src/domain/orchestration/requests.ts +782 -0
  35. package/src/domain/orchestration/review.test.ts +292 -0
  36. package/src/domain/orchestration/review.ts +168 -0
  37. package/src/domain/orchestration/run-wait.test.ts +265 -0
  38. package/src/domain/orchestration/run-wait.ts +256 -0
  39. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  40. package/src/domain/orchestration/workflow-section.ts +99 -0
  41. package/src/domain/orchestration/workflow.test.ts +1566 -0
  42. package/src/domain/orchestration/workflow.ts +778 -0
  43. package/src/domain/run-records.test.ts +27 -0
  44. package/src/domain/run-records.ts +689 -0
  45. package/src/domain/settlement.test.ts +186 -0
  46. package/src/domain/settlement.ts +137 -0
  47. package/src/domain/shapes.test.ts +185 -0
  48. package/src/domain/skills.test.ts +477 -0
  49. package/src/domain/skills.ts +114 -0
  50. package/src/domain/tool-schema.test.ts +46 -0
  51. package/src/domain/tool-schema.ts +20 -0
  52. package/src/domain/toolkit.test.ts +215 -0
  53. package/src/domain/toolkit.ts +374 -0
  54. package/src/domain/turn-budget.test.ts +37 -0
  55. package/src/domain/turn-budget.ts +23 -0
  56. package/src/domain/view.test.ts +803 -0
  57. package/src/domain/view.ts +491 -0
  58. package/src/example.test.ts +15 -0
  59. package/src/extension/commands.test.ts +485 -0
  60. package/src/extension/commands.ts +230 -0
  61. package/src/extension/entry.test.ts +1276 -0
  62. package/src/extension/entry.ts +380 -0
  63. package/src/extension/gate-alerts.test.ts +237 -0
  64. package/src/extension/gate-alerts.ts +143 -0
  65. package/src/extension/guard.test.ts +48 -0
  66. package/src/extension/guard.ts +31 -0
  67. package/src/extension/host-signals.test.ts +20 -0
  68. package/src/extension/host-signals.ts +13 -0
  69. package/src/extension/inspector-command.test.ts +1343 -0
  70. package/src/extension/inspector-command.ts +685 -0
  71. package/src/extension/prompt.test.ts +108 -0
  72. package/src/extension/prompt.ts +50 -0
  73. package/src/extension/request-alerts.test.ts +183 -0
  74. package/src/extension/request-alerts.ts +181 -0
  75. package/src/extension/retry-observer.test.ts +292 -0
  76. package/src/extension/retry-observer.ts +150 -0
  77. package/src/extension/revocation.test.ts +81 -0
  78. package/src/extension/revocation.ts +84 -0
  79. package/src/extension/settle-alerts.test.ts +579 -0
  80. package/src/extension/settle-alerts.ts +175 -0
  81. package/src/extension/shortcut.test.ts +62 -0
  82. package/src/extension/shortcut.ts +105 -0
  83. package/src/extension/tools.test.ts +1294 -0
  84. package/src/extension/tools.ts +553 -0
  85. package/src/extension/version.test.ts +115 -0
  86. package/src/extension/version.ts +97 -0
  87. package/src/goldens.test.ts +294 -0
  88. package/src/harness-policy.test.ts +76 -0
  89. package/src/layers.test.ts +309 -0
  90. package/src/layers.ts +405 -0
  91. package/src/package-manifest.test.ts +170 -0
  92. package/src/presentation/actions.test.ts +221 -0
  93. package/src/presentation/actions.ts +85 -0
  94. package/src/presentation/activity.test.ts +386 -0
  95. package/src/presentation/activity.ts +66 -0
  96. package/src/presentation/close.test.ts +359 -0
  97. package/src/presentation/inspector.test.ts +682 -0
  98. package/src/presentation/inspector.ts +442 -0
  99. package/src/presentation/overlay.test.ts +553 -0
  100. package/src/presentation/overlay.ts +229 -0
  101. package/src/presentation/repaint.test.ts +365 -0
  102. package/src/presentation/shortcut.ts +2 -0
  103. package/src/presentation/snapshot.test.ts +535 -0
  104. package/src/presentation/snapshot.ts +306 -0
  105. package/src/presentation/status.test.ts +43 -0
  106. package/src/presentation/status.ts +30 -0
  107. package/src/presentation/strip.test.ts +203 -0
  108. package/src/presentation/strip.ts +67 -0
  109. package/src/presentation/wording.test.ts +388 -0
  110. package/src/presentation/wording.ts +294 -0
  111. package/src/runtime/bridge.test.ts +131 -0
  112. package/src/runtime/bridge.ts +128 -0
  113. package/src/runtime/clock.test.ts +31 -0
  114. package/src/runtime/clock.ts +31 -0
  115. package/src/runtime/config.test.ts +63 -0
  116. package/src/runtime/config.ts +92 -0
  117. package/src/runtime/context.test.ts +19 -0
  118. package/src/runtime/context.ts +9 -0
  119. package/src/runtime/execution-env.test.ts +33 -0
  120. package/src/runtime/execution-env.ts +15 -0
  121. package/src/runtime/extensions.test.ts +86 -0
  122. package/src/runtime/extensions.ts +152 -0
  123. package/src/runtime/handle.ts +54 -0
  124. package/src/runtime/log.test.ts +140 -0
  125. package/src/runtime/log.ts +91 -0
  126. package/src/runtime/mcp.test.ts +1450 -0
  127. package/src/runtime/mcp.ts +1005 -0
  128. package/src/runtime/models.test.ts +145 -0
  129. package/src/runtime/models.ts +259 -0
  130. package/src/runtime/observe.test.ts +50 -0
  131. package/src/runtime/observe.ts +150 -0
  132. package/src/runtime/runtime-state.test.ts +25 -0
  133. package/src/runtime/runtime-state.ts +36 -0
  134. package/src/runtime/session-tag.ts +11 -0
  135. package/src/runtime/session.test.ts +352 -0
  136. package/src/runtime/session.ts +263 -0
  137. package/src/runtime/storage.ts +29 -0
  138. package/src/test-hygiene.test.ts +97 -0
@@ -0,0 +1,457 @@
1
+ import { Match, Option, Predicate, Result, Schema } from "effect";
2
+ import type { SessionRuntime } from "../../runtime/session.ts";
3
+ import { RunDoc, RunInputSchema, type RunInput } from "../run-records.ts";
4
+ import { FanoutInputSchema, type FanoutInput } from "./fanout.ts";
5
+ import { statusOf, viewRun, declaredSkills, type RunView } from "../view.ts";
6
+ import { resolverFor } from "../run-records.ts";
7
+ import { resolveStoredToolkit } from "../toolkit.ts";
8
+ import { AgentDoc, type TaskId, type Tx } from "@earendil-works/pi-durable";
9
+ import { decideGate } from "./gates.ts";
10
+ import { answerRequest, cancelRequests, declineRequest } from "./requests.ts";
11
+ import { waitForRun, waitForTask } from "./run-wait.ts";
12
+ import { conversationId, taskId } from "../ids.ts";
13
+
14
+ export class RunNotFound extends Schema.TaggedError<
15
+ RunNotFound,
16
+ { readonly brand: unique symbol }
17
+ >()("RunNotFound", {
18
+ message: Schema.String,
19
+ }) {}
20
+ export class RunNotRunning extends Schema.TaggedError<
21
+ RunNotRunning,
22
+ { readonly brand: unique symbol }
23
+ >()("RunNotRunning", {
24
+ message: Schema.String,
25
+ }) {}
26
+ export class RunNotResumable extends Schema.TaggedError<
27
+ RunNotResumable,
28
+ { readonly brand: unique symbol }
29
+ >()("RunNotResumable", {
30
+ message: Schema.String,
31
+ }) {}
32
+ export class InvalidControlRequest extends Schema.TaggedError<
33
+ InvalidControlRequest,
34
+ { readonly brand: unique symbol }
35
+ >()("InvalidControlRequest", { message: Schema.String }) {}
36
+
37
+ export const ControlRequest = Schema.Union([
38
+ Schema.Struct({
39
+ action: Schema.Literal("steer"),
40
+ run: Schema.String,
41
+ message: Schema.String,
42
+ }),
43
+ Schema.Struct({ action: Schema.Literal("stop"), run: Schema.String }),
44
+ Schema.Struct({ action: Schema.Literal("resume"), run: Schema.String }),
45
+ Schema.Struct({
46
+ action: Schema.Literals(["approve", "deny"]),
47
+ run: Schema.String,
48
+ gate: Schema.String,
49
+ note: Schema.optional(Schema.String),
50
+ }),
51
+ Schema.Struct({
52
+ action: Schema.Literal("answer"),
53
+ run: Schema.String,
54
+ request: Schema.String,
55
+ answer: Schema.String,
56
+ }),
57
+ Schema.Struct({
58
+ action: Schema.Literal("decline"),
59
+ run: Schema.String,
60
+ request: Schema.String,
61
+ }),
62
+ ]);
63
+ export type ControlRequest = typeof ControlRequest.Type;
64
+
65
+ const missingFieldFor = (input: unknown): string | undefined => {
66
+ const record = Predicate.isObject(input) ? input : {};
67
+ if (record.action === "steer" && typeof record.message !== "string") return "message";
68
+ if (
69
+ (record.action === "approve" || record.action === "deny") &&
70
+ typeof record.gate !== "string"
71
+ ) {
72
+ return "gate";
73
+ }
74
+ if (
75
+ (record.action === "answer" || record.action === "decline") &&
76
+ typeof record.request !== "string"
77
+ ) {
78
+ return "request";
79
+ }
80
+ if (record.action === "answer" && typeof record.answer !== "string") return "answer";
81
+ if (typeof record.run !== "string") return "run";
82
+ return undefined;
83
+ };
84
+
85
+ /** Decode at the boundary: a bad request names its action and the field it misses. */
86
+ export const decodeControl = (input: unknown): ControlRequest => {
87
+ const decoded = Schema.decodeUnknownResult(ControlRequest)(input);
88
+ if (Result.isSuccess(decoded)) return decoded.success;
89
+ const record = Predicate.isObject(input) ? input : {};
90
+ const action = typeof record.action === "string" ? record.action : "unknown";
91
+ const missing = missingFieldFor(input);
92
+ throw InvalidControlRequest.make({
93
+ message:
94
+ `Control action "${action}" is invalid: ` +
95
+ (missing === undefined ? "check its fields." : `${missing} is required.`),
96
+ });
97
+ };
98
+
99
+ /**
100
+ * `settle`: wait for the run to settle, as the tools do.
101
+ * `commit`: return at the write — no settlement race, no settlement log, no post-write view read.
102
+ */
103
+ export type ControlWait =
104
+ | { readonly policy: "settle"; readonly waitMs: number }
105
+ | { readonly policy: "commit" };
106
+
107
+ export interface ControlDeps {
108
+ readonly runtime: SessionRuntime;
109
+ readonly wait: ControlWait;
110
+ readonly signal?: AbortSignal;
111
+ }
112
+
113
+ export interface GateOutcome {
114
+ readonly gate: string;
115
+ readonly decision: "approve" | "deny";
116
+ readonly deliveredTaskIds: readonly number[];
117
+ readonly endedTaskIds: readonly number[];
118
+ }
119
+
120
+ export interface ControlResult {
121
+ /** Absent under the `commit` policy, which performs no post-write read. */
122
+ readonly view?: RunView;
123
+ readonly gate?: GateOutcome;
124
+ /** The line a surface prints; absent means the caller builds it from the view. */
125
+ readonly text?: string;
126
+ }
127
+
128
+ const load = async (request: ControlRequest, runtime: SessionRuntime) => {
129
+ const doc = await runtime.snapshot(RunDoc, request.run);
130
+ if (doc === undefined) {
131
+ throw RunNotFound.make({ message: `Run ${request.run} not found.` });
132
+ }
133
+ const taskNumber = doc.taskId;
134
+ const task =
135
+ taskNumber === null
136
+ ? undefined
137
+ : await runtime.run((context) => runtime.harness.getTask(taskId(taskNumber), context));
138
+ return { doc, task };
139
+ };
140
+
141
+ const awaitSettled = async (runId: string, taskId: number, deps: ControlDeps): Promise<void> => {
142
+ if (deps.wait.policy !== "settle") return;
143
+ const outcome = await waitForTask(
144
+ { runtime: deps.runtime, timers: deps.runtime.timers },
145
+ {
146
+ taskId,
147
+ waitMs: deps.wait.waitMs,
148
+ ...(deps.signal === undefined ? {} : { signal: deps.signal }),
149
+ },
150
+ );
151
+ if (outcome !== "settled") {
152
+ deps.runtime.log.write("info", `wait.${outcome}`, { runId });
153
+ }
154
+ };
155
+
156
+ /** The answer line: the run's status, or its next request when one waits. */
157
+ export const answerText = (
158
+ run: string,
159
+ status: RunView["status"],
160
+ requests: readonly string[],
161
+ ): string =>
162
+ requests.length === 0
163
+ ? `answer ${run}: ${status}`
164
+ : `answer ${run}: waits for request ${requests.join(", ")}`;
165
+
166
+ /** The settle policy's view; the commit policy performs no post-write read. */
167
+ const resultOf = async (
168
+ runId: string,
169
+ deps: ControlDeps,
170
+ gate?: GateOutcome,
171
+ ): Promise<ControlResult> => {
172
+ const result: { view?: RunView; gate?: GateOutcome } = {};
173
+ if (deps.wait.policy === "settle") result.view = await viewRun(runId, deps.runtime);
174
+ if (gate !== undefined) result.gate = gate;
175
+ return result;
176
+ };
177
+
178
+ const missingFor = async (
179
+ runId: string,
180
+ runtime: SessionRuntime,
181
+ ): Promise<{ readonly missing: readonly string[]; readonly available: string }> => {
182
+ const doc = await runtime.snapshot(RunDoc, runId);
183
+ const childNumber = doc?.childConversationId;
184
+ const agent =
185
+ childNumber === null || childNumber === undefined
186
+ ? undefined
187
+ : await runtime.run((context) =>
188
+ runtime.harness.snapshot(AgentDoc, conversationId(childNumber), context),
189
+ );
190
+ const resolved = resolveStoredToolkit(
191
+ agent,
192
+ resolverFor({
193
+ registry: runtime.registry.snapshot(),
194
+ skills: runtime.skills,
195
+ presence: runtime.mcpPresence,
196
+ }),
197
+ await declaredSkills(runtime, doc?.childConversationId),
198
+ );
199
+ return {
200
+ missing: resolved.missing,
201
+ available:
202
+ `extensions: ${resolved.available.extensions.join(", ") || "(none)"}; ` +
203
+ `tools: ${resolved.available.tools.join(", ") || "(none)"}`,
204
+ };
205
+ };
206
+
207
+ /** A refusal writes what no longer resolves; the list is append-only and never duplicated. */
208
+ const recordMissing = async (
209
+ runId: string,
210
+ doc: { readonly definition: string; readonly lane: string },
211
+ missing: readonly string[],
212
+ runtime: SessionRuntime,
213
+ ): Promise<void> => {
214
+ if (missing.length === 0) return;
215
+ const seed = { definition: doc.definition, lane: doc.lane };
216
+ await runtime.run((context) =>
217
+ runtime.harness.commit(async (tx) => {
218
+ const record = await tx.doc(RunDoc, runId, seed);
219
+ for (const name of missing) {
220
+ if (!record.diagnostics.includes(name)) record.diagnostics.push(name);
221
+ }
222
+ }, context),
223
+ );
224
+ runtime.log.write("warn", "control.missing_names", { runId, missing: missing.join(", ") });
225
+ };
226
+
227
+ /** Three user verbs over durable primitives. */
228
+ const unresumable = (run: string): RunNotResumable =>
229
+ RunNotResumable.make({ message: `Run ${run} has a stored input this version cannot resume.` });
230
+
231
+ /** Decode at the resume boundary: a stored input the current build cannot read is a refusal. */
232
+ export const decodeStoredInput = <A>(
233
+ schema: Schema.ConstraintDecoder<A>,
234
+ input: unknown,
235
+ run: string,
236
+ ): A => {
237
+ const decoded = Schema.decodeUnknownOption(schema)(input);
238
+ if (Option.isNone(decoded)) throw unresumable(run);
239
+ return decoded.value;
240
+ };
241
+
242
+ /** The seven action literals, narrowed, so each branch receives only its own fields. */
243
+ type SteerRequest = Extract<ControlRequest, { readonly action: "steer" }>;
244
+ type StopRequest = Extract<ControlRequest, { readonly action: "stop" }>;
245
+ type GateRequest = Extract<ControlRequest, { readonly action: "approve" | "deny" }>;
246
+ type AnswerRequest = Extract<ControlRequest, { readonly action: "answer" }>;
247
+ type DeclineRequest = Extract<ControlRequest, { readonly action: "decline" }>;
248
+ type ResumeRequest = Extract<ControlRequest, { readonly action: "resume" }>;
249
+
250
+ export const control = async (input: unknown, deps: ControlDeps): Promise<ControlResult> => {
251
+ const decoded = decodeControl(input);
252
+ const { runtime } = deps;
253
+ const { doc, task } = await load(decoded, runtime);
254
+ const status = statusOf(task);
255
+
256
+ const steerBranch = async (request: SteerRequest): Promise<ControlResult> => {
257
+ const missing = await missingFor(request.run, runtime);
258
+ if (missing.missing.length > 0) {
259
+ await recordMissing(request.run, doc, missing.missing, runtime);
260
+ throw RunNotRunning.make({
261
+ message: `Run ${request.run} is missing ${missing.missing.join(", ")}; ${missing.available}.`,
262
+ });
263
+ }
264
+ if (status !== "running" && status !== "waiting") {
265
+ throw RunNotRunning.make({
266
+ message: `Run ${request.run} is ${status}, not running; nothing to steer.`,
267
+ });
268
+ }
269
+ if (doc.childConversationId === null) {
270
+ throw RunNotRunning.make({
271
+ message: `Run ${request.run} has no child conversation to steer.`,
272
+ });
273
+ }
274
+ const childNumber = doc.childConversationId;
275
+ const conversation = await runtime.run((context) =>
276
+ runtime.harness.conversation(conversationId(childNumber), context),
277
+ );
278
+ if (conversation === undefined) {
279
+ throw RunNotRunning.make({
280
+ message: `Run ${request.run}: child conversation is missing.`,
281
+ });
282
+ }
283
+ await runtime.run((context) =>
284
+ conversation.submit({ type: "input", content: request.message, whenBusy: "steer" }, context),
285
+ );
286
+ return resultOf(request.run, deps);
287
+ };
288
+
289
+ const stopBranch = async (request: StopRequest): Promise<ControlResult> => {
290
+ if (doc.taskId !== null) {
291
+ const ownTask = taskId(doc.taskId);
292
+ await runtime.run((context) => runtime.harness.abortTask(ownTask, context));
293
+ }
294
+ // The cancel hook and the sweep are idempotent; cancel before the settling read so no
295
+ // request stays pending after the abort.
296
+ await cancelRequests(request.run, runtime);
297
+ if (doc.taskId !== null) await awaitSettled(request.run, doc.taskId, deps);
298
+ return resultOf(request.run, deps);
299
+ };
300
+
301
+ const gateBranch = async (request: GateRequest): Promise<ControlResult> => {
302
+ const decided = await decideGate(
303
+ {
304
+ run: request.run,
305
+ gate: request.gate,
306
+ decision: request.action,
307
+ ...(request.note === undefined ? {} : { note: request.note }),
308
+ },
309
+ runtime,
310
+ );
311
+ if (doc.taskId !== null) {
312
+ await awaitSettled(request.run, doc.taskId, deps);
313
+ }
314
+ return resultOf(request.run, deps, {
315
+ gate: request.gate,
316
+ decision: request.action,
317
+ deliveredTaskIds: decided.deliveredTaskIds,
318
+ endedTaskIds: decided.endedTaskIds,
319
+ });
320
+ };
321
+
322
+ const answerBranch = async (request: AnswerRequest): Promise<ControlResult> => {
323
+ const decided = await answerRequest(
324
+ {
325
+ run: request.run,
326
+ request: request.request,
327
+ answer: request.answer,
328
+ sessionId: runtime.sessionId,
329
+ },
330
+ runtime,
331
+ );
332
+ // The commit policy performs no post-write read; the caller builds its own text.
333
+ if (deps.wait.policy === "commit") return {};
334
+ if (doc.taskId === null) {
335
+ const view = await viewRun(request.run, runtime);
336
+ return { view, text: `answer ${request.run}: ${view.status}` };
337
+ }
338
+ // A request records the run that owns its gates; a child id addresses the child, so the
339
+ // attention watch reads the owner while the settling watch keeps the addressed task.
340
+ const outcome = await waitForRun(
341
+ { runtime, timers: runtime.timers },
342
+ {
343
+ runId: decided.record.runId,
344
+ taskId: doc.taskId,
345
+ waitMs: deps.wait.waitMs,
346
+ ...(deps.signal === undefined ? {} : { signal: deps.signal }),
347
+ },
348
+ );
349
+ if (outcome !== "settled") runtime.log.write("info", `wait.${outcome}`, { runId: request.run });
350
+ const view = await viewRun(request.run, runtime);
351
+ return { view, text: answerText(request.run, view.status, view.requests) };
352
+ };
353
+
354
+ const declineBranch = async (request: DeclineRequest): Promise<ControlResult> => {
355
+ await declineRequest(
356
+ { run: request.run, request: request.request, sessionId: runtime.sessionId },
357
+ runtime,
358
+ );
359
+ return { text: `decline ${request.run}: cancelled` };
360
+ };
361
+
362
+ const resumeBranch = async (request: ResumeRequest): Promise<ControlResult> => {
363
+ if (doc.mode === "workflow") {
364
+ throw RunNotResumable.make({
365
+ message:
366
+ `Run ${request.run} is a workflow; a script cannot resume. ` +
367
+ `Launch a new workflow to run it again.`,
368
+ });
369
+ }
370
+
371
+ if (status !== "failed" && status !== "stopped") {
372
+ throw RunNotResumable.make({
373
+ message: `Run ${request.run} is ${status}; only a failed or stopped run can resume.`,
374
+ });
375
+ }
376
+
377
+ const missing = await missingFor(request.run, runtime);
378
+ if (missing.missing.length > 0) {
379
+ await recordMissing(request.run, doc, missing.missing, runtime);
380
+ throw RunNotResumable.make({
381
+ message: `Run ${request.run} is missing ${missing.missing.join(", ")}; ${missing.available}.`,
382
+ });
383
+ }
384
+ const previousTask = task;
385
+ if (previousTask === undefined) {
386
+ throw RunNotResumable.make({
387
+ message: `Run ${request.run} has no recorded input to resume.`,
388
+ });
389
+ }
390
+ const previousTaskId = previousTask.id;
391
+ const seed = { definition: doc.definition, lane: doc.lane };
392
+ /** One commit creates the resumed task and points the run document at it. */
393
+ const commitResumed = async (create: (tx: Tx) => Promise<TaskId>): Promise<number> =>
394
+ runtime.run((context) =>
395
+ runtime.harness.commit(async (tx) => {
396
+ const created = await create(tx);
397
+ const run = await tx.doc(RunDoc, request.run, seed);
398
+ run.taskId = created;
399
+ return created;
400
+ }, context),
401
+ );
402
+ let resumedTaskId: number;
403
+
404
+ if (previousTask.kind === "delegates.fanout") {
405
+ const previous = decodeStoredInput(FanoutInputSchema, previousTask.input, request.run);
406
+ const answeredChildren: { child: number; taskId: number }[] = [];
407
+ for (const [child, childRunId] of doc.childRunIds.entries()) {
408
+ const childDoc = await runtime.snapshot(RunDoc, childRunId);
409
+ if (childDoc?.taskId === null || childDoc?.taskId === undefined) continue;
410
+ const childTaskNumber = childDoc.taskId;
411
+ const childTask = await runtime.run((context) =>
412
+ runtime.harness.getTask(taskId(childTaskNumber), context),
413
+ );
414
+ if (statusOf(childTask) === "answered") {
415
+ answeredChildren.push({ child, taskId: childDoc.taskId });
416
+ }
417
+ }
418
+ const resumed: FanoutInput = {
419
+ ...previous,
420
+ submissionKeyPrefix: `${request.run}:resume:${previousTaskId}`,
421
+ ...(answeredChildren.length === 0 ? {} : { answeredChildren }),
422
+ };
423
+ resumedTaskId = await commitResumed((tx) =>
424
+ tx.createTask(runtime.tasks.fanout, resumed, {
425
+ ownership: { kind: "conversation" },
426
+ conversationId: runtime.root.id,
427
+ }),
428
+ );
429
+ } else {
430
+ const previous = decodeStoredInput(RunInputSchema, previousTask.input, request.run);
431
+ const resumed: RunInput = {
432
+ ...previous,
433
+ submissionKey: `${request.run}:resume:${previousTaskId}`,
434
+ };
435
+ resumedTaskId = await commitResumed((tx) =>
436
+ tx.createTask(runtime.tasks.run, resumed, {
437
+ ownership: { kind: "conversation" },
438
+ conversationId: runtime.root.id,
439
+ }),
440
+ );
441
+ }
442
+
443
+ await awaitSettled(request.run, resumedTaskId, deps);
444
+ return resultOf(request.run, deps);
445
+ };
446
+
447
+ // Every action literal has one branch; `Match.exhaustive` refuses a missing one.
448
+ return await Match.value(decoded).pipe(
449
+ Match.when({ action: "steer" }, steerBranch),
450
+ Match.when({ action: "stop" }, stopBranch),
451
+ Match.whenOr({ action: "approve" }, { action: "deny" }, gateBranch),
452
+ Match.when({ action: "answer" }, answerBranch),
453
+ Match.when({ action: "decline" }, declineBranch),
454
+ Match.when({ action: "resume" }, resumeBranch),
455
+ Match.exhaustive,
456
+ );
457
+ };