@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,689 @@
1
+ import type { AssistantMessage, Message } from "@earendil-works/pi-ai";
2
+ import { MODEL_THINKING_LEVELS } from "@earendil-works/pi-ai/providers/model-schema";
3
+ import {
4
+ defineDoc,
5
+ defineDocFamily,
6
+ defineTask,
7
+ SubmissionSettled,
8
+ type JsonObject,
9
+ type RegistrySnapshot,
10
+ type RunningTask,
11
+ type TaskRecord,
12
+ type TaskRuntime,
13
+ type Tx,
14
+ } from "@earendil-works/pi-durable";
15
+ import { Effect, Option, Schema } from "effect";
16
+ import type { DelegatesConfig } from "../runtime/config.ts";
17
+ import { AgentDefinition } from "./definitions.ts";
18
+ import type { SkillsCatalogue } from "./skills.ts";
19
+ import { available, liveCounts, type AdmissionHost } from "./orchestration/admission.ts";
20
+ import {
21
+ bindToolkit,
22
+ createBoundChild,
23
+ conversationNumber,
24
+ type McpServerTools,
25
+ type ToolkitResolver,
26
+ } from "./toolkit.ts";
27
+ import type { Context } from "@earendil-works/chord/context";
28
+ import { conversationId, taskId } from "./ids.ts";
29
+ import { nullLogSink, reasonOf, type LogSink } from "../runtime/log.ts";
30
+ import {
31
+ logRunFailed,
32
+ nullSettleSignal,
33
+ reasonFor,
34
+ recordSettlement,
35
+ type SettleSignal,
36
+ } from "./settlement.ts";
37
+ import type { FailureReason } from "./failure.ts";
38
+ import type { McpPresence } from "../runtime/mcp.ts";
39
+ import type { SessionRuntime } from "../runtime/session.ts";
40
+ import { GateDoc, GateIndexDoc, type GateRecord } from "./orchestration/gates.ts";
41
+ import { RequestDoc, RequestIndexDoc, type RequestRecord } from "./orchestration/requests.ts";
42
+ import { Execution, FailureFact, Resolution } from "./failure.ts";
43
+
44
+ export const RunMode = Schema.Literals(["single", "fanout", "review", "workflow"]);
45
+ export type RunMode = typeof RunMode.Type;
46
+
47
+ export const RunMetadata = Schema.Struct({
48
+ definition: Schema.String,
49
+ mode: RunMode,
50
+ lane: Schema.String,
51
+ requestedAgent: Schema.String,
52
+ task: Schema.String,
53
+ requestId: Schema.String,
54
+ attempt: Schema.Finite,
55
+ childConversationId: Schema.NullOr(Schema.Finite),
56
+ taskId: Schema.NullOr(Schema.Finite),
57
+ gateRunId: Schema.String,
58
+ /** The run that launched this one: a fanout group or a workflow. `null` for a root run. */
59
+ parentRunId: Schema.NullOr(Schema.String),
60
+ childRunIds: Schema.Array(Schema.String),
61
+ diagnostics: Schema.Array(Schema.String),
62
+ /** The launch kind; `wait` for a document written before version 3. */
63
+ execution: Execution,
64
+ /** The budget the child ran with; `null` while no claim resolved one. */
65
+ maxTurns: Schema.NullOr(Schema.Finite),
66
+ /** The settle outcome, one per task; `null` until the task ends. */
67
+ resolution: Schema.NullOr(Resolution),
68
+ /** `null` unless the run failed. */
69
+ failure: Schema.NullOr(FailureFact),
70
+ /** The task whose settlement was announced; `null` until a notice is delivered. */
71
+ settledTaskId: Schema.NullOr(Schema.Finite),
72
+ /** Durable retries observed on the child conversation. */
73
+ retryCount: Schema.Finite,
74
+ });
75
+ export type RunMetadata = typeof RunMetadata.Type;
76
+
77
+ export interface RunDocSeed {
78
+ readonly definition: string;
79
+ /** Absent: `single`. */
80
+ readonly mode?: RunMode;
81
+ readonly lane: string;
82
+ /** Absent: a root run. */
83
+ readonly parentRunId?: string;
84
+ /** Absent: `wait`. */
85
+ readonly execution?: Execution;
86
+ }
87
+
88
+ const VERSION_WITH_MODE = 2;
89
+ const VERSION_WITH_TERMINAL_FACTS = 3;
90
+
91
+ /**
92
+ * Two migrations: version 1 may predate the run mode and the parent run id, or
93
+ * already carry them; a version 2 document predates every terminal fact.
94
+ */
95
+ export const migrateRun = (value: JsonObject, fromVersion: number): RunMetadata & JsonObject =>
96
+ ({
97
+ ...value,
98
+ ...(fromVersion < VERSION_WITH_MODE
99
+ ? { mode: value.mode ?? "single", parentRunId: value.parentRunId ?? null }
100
+ : {}),
101
+ ...(fromVersion < VERSION_WITH_TERMINAL_FACTS
102
+ ? {
103
+ execution: value.execution ?? "wait",
104
+ maxTurns: value.maxTurns ?? null,
105
+ resolution: value.resolution ?? null,
106
+ failure: value.failure ?? null,
107
+ settledTaskId: value.settledTaskId ?? null,
108
+ retryCount: value.retryCount ?? 0,
109
+ }
110
+ : {}),
111
+ }) as unknown as RunMetadata & JsonObject;
112
+
113
+ export const RunDoc = defineDocFamily<RunMetadata & JsonObject, RunDocSeed & JsonObject>({
114
+ kind: "delegates.run",
115
+ version: VERSION_WITH_TERMINAL_FACTS,
116
+ scope: "session",
117
+ family: true,
118
+ initial: (seed) => ({
119
+ definition: seed.definition,
120
+ mode: seed.mode ?? "single",
121
+ lane: seed.lane,
122
+ requestedAgent: "",
123
+ task: "",
124
+ requestId: "",
125
+ attempt: 1,
126
+ childConversationId: null,
127
+ taskId: null,
128
+ gateRunId: "",
129
+ parentRunId: seed.parentRunId ?? null,
130
+ childRunIds: [],
131
+ diagnostics: [],
132
+ execution: seed.execution ?? "wait",
133
+ maxTurns: null,
134
+ resolution: null,
135
+ failure: null,
136
+ settledTaskId: null,
137
+ retryCount: 0,
138
+ }),
139
+ migrate: migrateRun,
140
+ checkpointWhen: () => true,
141
+ });
142
+
143
+ /** The session's run ids, in creation order; the only enumeration a viewer needs. */
144
+ export const RunIndexDoc = defineDoc<{ runIds: string[] } & JsonObject>({
145
+ kind: "delegates.run-index",
146
+ version: 1,
147
+ scope: "session",
148
+ initial: () => ({ runIds: [] }),
149
+ checkpointWhen: () => true,
150
+ });
151
+
152
+ /** The stored host defaults; the levels are pi-ai's own runtime list, never a copy. */
153
+ export const HostDefaultsSchema = Schema.Struct({
154
+ model: Schema.Struct({ provider: Schema.String, modelId: Schema.String }),
155
+ thinkingLevel: Schema.Literals(MODEL_THINKING_LEVELS),
156
+ });
157
+
158
+ export const RunInputSchema = Schema.Struct({
159
+ runId: Schema.String,
160
+ /** The launch run that owns gates: the run id itself, or a fanout parent's id. */
161
+ gateRunId: Schema.String,
162
+ requestId: Schema.String,
163
+ attempt: Schema.Finite,
164
+ definition: AgentDefinition,
165
+ task: Schema.String,
166
+ host: HostDefaultsSchema,
167
+ lane: Schema.String,
168
+ maxTurns: Schema.Finite,
169
+ /** The key of this task's submission; a resume uses a fresh one so it continues the child. */
170
+ submissionKey: Schema.String,
171
+ });
172
+ export type RunInput = typeof RunInputSchema.Type;
173
+
174
+ export const RunResultSchema = Schema.Union([
175
+ Schema.Struct({ status: Schema.Literal("answered"), answer: Schema.String }),
176
+ Schema.Struct({ status: Schema.Literal("failed"), diagnostic: Schema.String }),
177
+ Schema.Struct({
178
+ status: Schema.Literal("denied"),
179
+ /** Names the request or gate that was refused, when one is known. */
180
+ diagnostic: Schema.optional(Schema.String),
181
+ }),
182
+ Schema.Struct({ status: Schema.Literal("stopped") }),
183
+ ]);
184
+ export type RunResult = typeof RunResultSchema.Type;
185
+
186
+ /** A stored outcome result as the run result it claims to be; a malformed value reads as absent. */
187
+ export const runResultOf = (value: unknown): RunResult | undefined =>
188
+ Option.getOrUndefined(Schema.decodeUnknownOption(RunResultSchema)(value));
189
+
190
+ export type RunState =
191
+ | { readonly phase: "bind"; readonly input: RunInput }
192
+ | {
193
+ readonly phase: "submit";
194
+ readonly input: RunInput;
195
+ readonly childId: number;
196
+ }
197
+ | {
198
+ readonly phase: "settle";
199
+ readonly input: RunInput;
200
+ readonly childId: number;
201
+ };
202
+
203
+ type RunHooks = Record<never, never>;
204
+
205
+ /** The text of the last assistant answer in a context. */
206
+ export const answerText = (messages: readonly Message[]): string => {
207
+ const last = [...messages]
208
+ .reverse()
209
+ .find((message): message is AssistantMessage => message.role === "assistant");
210
+ return (last?.content ?? []).map((part) => (part.type === "text" ? part.text : "")).join("");
211
+ };
212
+
213
+ /** Resolves toolkit names against the phase's registry snapshot and the runtime's catalogue. */
214
+ export const resolverFor = (deps: {
215
+ readonly registry: RegistrySnapshot;
216
+ readonly skills: SkillsCatalogue["Service"];
217
+ /** The runtime's MCP presence; absent in a read-only viewer, which connects to nothing. */
218
+ readonly presence?: McpPresence;
219
+ }): ToolkitResolver => {
220
+ const installed = deps.registry.installed();
221
+ const tools = deps.registry.tools();
222
+ const availableTools = tools.map((entry) => entry.tool.name);
223
+ const mcpServers: McpServerTools[] = installed.flatMap((extension) => {
224
+ const namespace = extension.namespace;
225
+ // A server extension always has one namespace; a snapshot entry without it is not a server.
226
+ if (!extension.name.startsWith("mcp:") || namespace === undefined) return [];
227
+ return [
228
+ {
229
+ extension: extension.name,
230
+ namespace: namespace.name,
231
+ tools: (extension.tools ?? []).map((tool) => tool.name),
232
+ },
233
+ ];
234
+ });
235
+ return {
236
+ availableExtensions: installed.map((extension) => extension.name),
237
+ availableTools,
238
+ availableSkills: deps.skills.all().map((skill) => skill.name),
239
+ extension: (name) => deps.registry.extension(name),
240
+ tool: (name) => tools.find((entry) => entry.tool.name === name)?.tool,
241
+ skill: deps.skills.find,
242
+ mcpServers,
243
+ // A codemode-exposed MCP tool is callable from scripts only, so `callers` names `tools`.
244
+ codemodeTools: tools
245
+ .filter((entry) => {
246
+ if (!entry.extension.name.startsWith("mcp:")) return false;
247
+ const callers = entry.tool.callers ?? ["model", "tools"];
248
+ return callers.includes("tools") && !callers.includes("model");
249
+ })
250
+ .map((entry) => entry.tool.name),
251
+ unconnected: deps.presence?.unconnected,
252
+ matchTools: (pattern) => {
253
+ const star = pattern.indexOf("*");
254
+ const prefix = pattern.slice(0, star);
255
+ const suffix = pattern.slice(star + 1);
256
+ return availableTools.filter((name) => name.startsWith(prefix) && name.endsWith(suffix));
257
+ },
258
+ };
259
+ };
260
+
261
+ const failed = (diagnostic: string): RunResult => ({ status: "failed", diagnostic });
262
+
263
+ /** A package-native failure: one terminal commit, one fact and one log line. */
264
+ const internalFailure = async (
265
+ task: { readonly input: RunInput },
266
+ runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
267
+ context: Context,
268
+ diagnostic: string,
269
+ log: LogSink,
270
+ settleSignal: SettleSignal,
271
+ ): Promise<void> => {
272
+ let recorded: Awaited<ReturnType<typeof recordSettlement>>;
273
+ await runtime.commit(async (tx) => {
274
+ const doc = await tx.doc(RunDoc, task.input.runId, {
275
+ definition: task.input.definition.name,
276
+ lane: task.input.lane,
277
+ });
278
+ recorded = await recordSettlement(doc, {
279
+ resolution: "failed",
280
+ reason: "internal",
281
+ rawDetail: diagnostic,
282
+ });
283
+ return {
284
+ status: "terminal",
285
+ outcome: {
286
+ status: "failed",
287
+ error: { message: diagnostic },
288
+ result: failed(diagnostic),
289
+ },
290
+ };
291
+ }, context);
292
+ if (recorded !== undefined) {
293
+ logRunFailed(log, task.input.runId, recorded.failure, recorded.retryable);
294
+ }
295
+ settleSignal.emit({ runId: task.input.runId });
296
+ };
297
+
298
+ const bind = async (
299
+ task: RunningTask<RunInput, Extract<RunState, { phase: "bind" }>, RunResult>,
300
+ runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
301
+ context: Context,
302
+ admission: AdmissionHost,
303
+ skills: SkillsCatalogue["Service"],
304
+ mcpPresence: () => McpPresence | undefined,
305
+ log: LogSink,
306
+ settleSignal: SettleSignal,
307
+ ): Promise<void> => {
308
+ const inspection = await admission.inspect();
309
+ const ownedTasks = await runtime.ownedTasks(context);
310
+ const counts = liveCounts(inspection, task.input.lane, {
311
+ excludeTaskId: runtime.taskId,
312
+ ownedTasks,
313
+ });
314
+ const caps = admission.caps();
315
+ if (available(caps.laneCap, counts.laneLive, caps.sessionCeiling, counts.sessionLive) <= 0) {
316
+ await runtime.commit(
317
+ () => ({
318
+ status: "sleeping",
319
+ until: runtime.now() + admission.pollMs,
320
+ checkpoint: task.state.checkpoint,
321
+ }),
322
+ context,
323
+ );
324
+ return;
325
+ }
326
+
327
+ // Launch-time binding reads the live registry, not a snapshot: the task needs
328
+ // the phase's own view. A view builds one `registry.snapshot()` instead.
329
+ const presence = mcpPresence();
330
+ const resolver = resolverFor({
331
+ registry: runtime.registry,
332
+ skills,
333
+ ...(presence === undefined ? {} : { presence }),
334
+ });
335
+ let bound;
336
+ try {
337
+ bound = await Effect.runPromise(bindToolkit(task.input.definition, resolver));
338
+ } catch (error) {
339
+ await internalFailure(task, runtime, context, reasonOf(error), log, settleSignal);
340
+ return;
341
+ }
342
+
343
+ await runtime.commit(async (tx) => {
344
+ const seed = { definition: task.input.definition.name, lane: task.input.lane };
345
+ const doc = await tx.doc(RunDoc, task.input.runId, seed);
346
+ if (doc.childConversationId !== null) {
347
+ return {
348
+ status: "running",
349
+ checkpoint: { phase: "submit", input: task.input, childId: doc.childConversationId },
350
+ };
351
+ }
352
+ const child = await createBoundChild(
353
+ tx,
354
+ task.input.gateRunId,
355
+ task.input.runId,
356
+ runtime.taskId,
357
+ bound,
358
+ task.input.definition,
359
+ task.input.maxTurns,
360
+ );
361
+ doc.childConversationId = conversationNumber(child.id);
362
+ return {
363
+ status: "running",
364
+ checkpoint: { phase: "submit", input: task.input, childId: conversationNumber(child.id) },
365
+ };
366
+ }, context);
367
+ };
368
+
369
+ const submit = async (
370
+ task: RunningTask<RunInput, Extract<RunState, { phase: "submit" }>, RunResult>,
371
+ runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
372
+ context: Context,
373
+ log: LogSink,
374
+ settleSignal: SettleSignal,
375
+ ): Promise<void> => {
376
+ const conversation = await runtime.conversation(
377
+ conversationId(task.state.checkpoint.childId),
378
+ context,
379
+ );
380
+ if (conversation === undefined) {
381
+ await internalFailure(
382
+ task,
383
+ runtime,
384
+ context,
385
+ "child conversation is missing",
386
+ log,
387
+ settleSignal,
388
+ );
389
+ return;
390
+ }
391
+ await conversation.submit(
392
+ {
393
+ type: "input",
394
+ content: task.input.task,
395
+ requestId: task.input.submissionKey,
396
+ notify: { taskId: runtime.taskId, key: task.input.submissionKey },
397
+ },
398
+ context,
399
+ );
400
+ await runtime.commit(
401
+ () => ({
402
+ status: "sleeping",
403
+ signals: [SubmissionSettled.key(task.input.submissionKey)],
404
+ checkpoint: { phase: "settle", input: task.input, childId: task.state.checkpoint.childId },
405
+ }),
406
+ context,
407
+ );
408
+ };
409
+
410
+ /**
411
+ * The newest request of one run, from the index. The `ask` tool wakes on a
412
+ * decline with an error; a child that then finishes would settle `answered`
413
+ * and hide the refusal, so a run whose newest request is declined settles
414
+ * `denied` with the request named, like a denied gate.
415
+ */
416
+ const newestRequest = async (
417
+ runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
418
+ runId: string,
419
+ context: Context,
420
+ ): Promise<RequestRecord | undefined> => {
421
+ const index = await runtime.snapshot(RequestIndexDoc, context);
422
+ let newest: RequestRecord | undefined;
423
+ for (const row of index?.rows ?? []) {
424
+ if (row.runId !== runId) continue;
425
+ const record = await runtime.snapshot(RequestDoc, row.key, context);
426
+ if (record === undefined) continue;
427
+ if (record.runId !== runId && record.childRunId !== runId) continue;
428
+ if (newest === undefined || record.requestedAt >= newest.requestedAt) newest = record;
429
+ }
430
+ return newest;
431
+ };
432
+
433
+ const declinedAtSettle = async (
434
+ runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
435
+ runId: string,
436
+ context: Context,
437
+ ): Promise<boolean> => {
438
+ const newest = await newestRequest(runtime, runId, context);
439
+ return newest?.status === "cancelled" && newest.reason === "declined";
440
+ };
441
+
442
+ const settle = async (
443
+ task: RunningTask<RunInput, Extract<RunState, { phase: "settle" }>, RunResult>,
444
+ runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
445
+ context: Context,
446
+ log: LogSink,
447
+ settleSignal: SettleSignal,
448
+ ): Promise<void> => {
449
+ const signal = await runtime.readSignal(SubmissionSettled, task.input.submissionKey, context);
450
+ let result: RunResult;
451
+ let failureReason: FailureReason | undefined;
452
+ let rawDetail: string | undefined;
453
+ if (signal === undefined || "expired" in signal) {
454
+ result = failed("missing_settlement");
455
+ } else {
456
+ const record = signal.value;
457
+ if (record.status === "done") {
458
+ if (await declinedAtSettle(runtime, task.input.runId, context)) {
459
+ const declined = await newestRequest(runtime, task.input.runId, context);
460
+ result = {
461
+ status: "denied",
462
+ ...(declined === undefined
463
+ ? {}
464
+ : { diagnostic: `request ${declined.requestId} was declined` }),
465
+ };
466
+ } else {
467
+ const view = await runtime.context(conversationId(task.state.checkpoint.childId), context);
468
+ result = { status: "answered", answer: answerText(view.messages) };
469
+ }
470
+ } else {
471
+ const gateIndex = await runtime.snapshot(GateIndexDoc, context);
472
+ const gates: GateRecord[] = [];
473
+ for (const key of gateIndex?.keys ?? []) {
474
+ const gate = await runtime.snapshot(GateDoc, key, context);
475
+ if (
476
+ gate !== undefined &&
477
+ gate.runId === task.input.gateRunId &&
478
+ (gate.childRunIds ?? []).includes(task.input.runId)
479
+ ) {
480
+ gates.push(gate);
481
+ }
482
+ }
483
+ const last = gates.reduce<GateRecord | undefined>(
484
+ (latest, gate) =>
485
+ latest === undefined || gate.requestedAt >= latest.requestedAt ? gate : latest,
486
+ undefined,
487
+ );
488
+ result =
489
+ last?.status === "denied" ? { status: "denied" } : failed(record.reason ?? "unanswered");
490
+ if (result.status === "failed") {
491
+ failureReason = reasonFor(record.reason);
492
+ rawDetail = typeof record.detail === "string" ? record.detail : undefined;
493
+ }
494
+ }
495
+ }
496
+ let recorded: Awaited<ReturnType<typeof recordSettlement>>;
497
+ await runtime.commit(async (tx) => {
498
+ const doc = await tx.doc(RunDoc, task.input.runId, {
499
+ definition: task.input.definition.name,
500
+ lane: task.input.lane,
501
+ });
502
+ recorded = await recordSettlement(doc, {
503
+ resolution: result.status,
504
+ ...(failureReason === undefined ? {} : { reason: failureReason }),
505
+ ...(rawDetail === undefined ? {} : { rawDetail }),
506
+ });
507
+ return result.status === "failed"
508
+ ? {
509
+ status: "terminal",
510
+ outcome: {
511
+ status: "failed",
512
+ error: { message: result.diagnostic },
513
+ result,
514
+ },
515
+ }
516
+ : { status: "terminal", outcome: { status: "completed", result } };
517
+ }, context);
518
+ // After the commit resolves: one line per failed run, then the settle event.
519
+ if (recorded !== undefined) {
520
+ logRunFailed(log, task.input.runId, recorded.failure, recorded.retryable);
521
+ }
522
+ settleSignal.emit({ runId: task.input.runId });
523
+ };
524
+
525
+ export const createRunTask = (
526
+ admission: AdmissionHost,
527
+ skills: SkillsCatalogue["Service"],
528
+ /** The runtime's MCP presence, read at each bind; absent in a read-only runtime. */
529
+ mcpPresence: () => McpPresence | undefined = () => undefined,
530
+ /** The session sink: one `run.failed` line per failed run. */
531
+ log: LogSink = nullLogSink,
532
+ /** The in-process settle signal: every terminal commit emits once. */
533
+ settleSignal: SettleSignal = nullSettleSignal,
534
+ ) =>
535
+ defineTask<RunInput, RunState, RunResult, RunHooks>({
536
+ name: "delegates.run",
537
+ version: 1,
538
+ initial: (input) => ({ phase: "bind", input }),
539
+ phases: {
540
+ bind: (task, runtime, context) =>
541
+ bind(task, runtime, context, admission, skills, mcpPresence, log, settleSignal),
542
+ submit: (task, runtime, context) => submit(task, runtime, context, log, settleSignal),
543
+ settle: (task, runtime, context) => settle(task, runtime, context, log, settleSignal),
544
+ },
545
+ abort: async (task, runtime, context) => {
546
+ await runtime.commit(async (tx) => {
547
+ const doc = await tx.doc(RunDoc, task.input.runId, {
548
+ definition: task.input.definition.name,
549
+ lane: task.input.lane,
550
+ });
551
+ await recordSettlement(doc, { resolution: "stopped" });
552
+ return {
553
+ status: "terminal",
554
+ outcome: { status: "aborted", reason: "stopped", result: { status: "stopped" } },
555
+ };
556
+ }, context);
557
+ settleSignal.emit({ runId: task.input.runId });
558
+ },
559
+ });
560
+
561
+ export interface LaunchIndexAttempt {
562
+ readonly runId: string;
563
+ readonly attempt: number;
564
+ }
565
+
566
+ /** Session family: `requestId` → its committed attempts. */
567
+ export const LaunchIndexDoc = defineDocFamily<
568
+ { attempts: LaunchIndexAttempt[] } & JsonObject,
569
+ { readonly requestId: string } & JsonObject
570
+ >({
571
+ kind: "delegates.launch-index",
572
+ version: 1,
573
+ scope: "session",
574
+ family: true,
575
+ initial: () => ({ attempts: [] }),
576
+ checkpointWhen: () => true,
577
+ });
578
+
579
+ export interface LaunchClaim {
580
+ readonly runId: string;
581
+ readonly attempt: number;
582
+ readonly reuseTaskId?: number;
583
+ }
584
+
585
+ /** The next attempt after every recorded one; pure, so it can be property-tested. */
586
+ export const nextAttempt = (attempts: readonly { readonly attempt: number }[]): number =>
587
+ attempts.reduce((highest, entry) => Math.max(highest, entry.attempt), 0) + 1;
588
+
589
+ const isReusable = (task: TaskRecord<unknown, unknown, unknown> | undefined): boolean =>
590
+ task !== undefined && task.state.status !== "terminal";
591
+
592
+ /**
593
+ * Reuses an unfinished run for the same identity; otherwise returns the next attempt. A terminal
594
+ * run, failed included, never shadows a retry.
595
+ */
596
+ export const claimLaunch = async (
597
+ tx: Tx,
598
+ identity: {
599
+ readonly requestId: string;
600
+ readonly definition: string;
601
+ readonly lane: string;
602
+ readonly seed: RunDocSeed & JsonObject;
603
+ },
604
+ ): Promise<LaunchClaim> => {
605
+ const index = await tx.doc(LaunchIndexDoc, identity.requestId, {
606
+ requestId: identity.requestId,
607
+ });
608
+ for (const entry of [...index.attempts].reverse()) {
609
+ const doc = await tx.doc(RunDoc, entry.runId, identity.seed);
610
+ if (doc.taskId === null) continue;
611
+ const task = await tx.task(taskId(doc.taskId));
612
+ if (isReusable(task)) {
613
+ return { runId: entry.runId, attempt: entry.attempt, reuseTaskId: doc.taskId };
614
+ }
615
+ if (task !== undefined && task.state.status === "terminal") break;
616
+ }
617
+ const attempt = nextAttempt(index.attempts);
618
+ const runId = `${identity.requestId}#${attempt}`;
619
+ index.attempts.push({ runId, attempt });
620
+ return { runId, attempt };
621
+ };
622
+
623
+ /** The configuration the run task needs; kept beside the definitions for one import. */
624
+ export type RunConfig = Pick<DelegatesConfig, "maxTurns"> & { readonly cwd?: string };
625
+
626
+ export type { TaskRecord };
627
+
628
+ export interface ListedRuns {
629
+ readonly runIds: readonly string[];
630
+ /** Indexed runs older than the window; zero when every indexed run is listed. */
631
+ readonly omitted: number;
632
+ /**
633
+ * The documents read while listing, keyed by the indexed run they belong to.
634
+ * A child reached through its parent's `childRunIds` has no entry: a caller
635
+ * that needs it reads it once.
636
+ */
637
+ readonly docs: ReadonlyMap<string, RunMetadata & JsonObject>;
638
+ }
639
+
640
+ /**
641
+ * The runs a session-scoped reader enumerates: the newest `limit` indexed run
642
+ * ids, each followed by its group's children. A fanout or review child is never
643
+ * indexed, so its parent document is the only way to reach it.
644
+ *
645
+ * Every windowed run is read, watched or not: a workflow commits its children to
646
+ * `childRunIds` only after it starts, so skipping a watched parent would hide
647
+ * every child that appears later. The read documents are returned, letting a
648
+ * caller that also needs them pay one snapshot instead of two.
649
+ */
650
+ export const listedRuns = async (
651
+ runtime: SessionRuntime,
652
+ options: { readonly limit?: number } = {},
653
+ ): Promise<ListedRuns> => {
654
+ const index = await runtime.snapshot(RunIndexDoc);
655
+ const indexed = index?.runIds ?? [];
656
+ // The index is in creation order, so the tail is the newest.
657
+ const window = options.limit === undefined ? indexed : indexed.slice(-options.limit);
658
+ const runIds: string[] = [];
659
+ const docs = new Map<string, RunMetadata & JsonObject>();
660
+ const add = (runId: string): void => {
661
+ if (!runIds.includes(runId)) runIds.push(runId);
662
+ };
663
+ for (const runId of window) {
664
+ add(runId);
665
+ const doc = await runtime.snapshot(RunDoc, runId);
666
+ if (doc === undefined) continue;
667
+ docs.set(runId, doc);
668
+ for (const childRunId of doc.childRunIds) add(childRunId);
669
+ }
670
+ return { runIds, omitted: indexed.length - window.length, docs };
671
+ };
672
+
673
+ /**
674
+ * The only committer of the announced marker: the recorder's announcement path.
675
+ * The snapshot guard keeps a vanished run from being re-created from a seed.
676
+ */
677
+ export const recordAnnouncement = async (
678
+ runtime: SessionRuntime,
679
+ runId: string,
680
+ taskId: number,
681
+ ): Promise<void> => {
682
+ if ((await runtime.snapshot(RunDoc, runId)) === undefined) return;
683
+ await runtime.run((context) =>
684
+ runtime.harness.commit(async (tx) => {
685
+ const doc = await tx.doc(RunDoc, runId, { definition: "", lane: "default" });
686
+ doc.settledTaskId = taskId;
687
+ }, context),
688
+ );
689
+ };