@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,691 @@
1
+ import type { Context } from "@earendil-works/chord/context";
2
+ import type { ModelThinkingLevel } from "@earendil-works/pi-ai";
3
+ import type { ConversationId, Task, TaskOptions, Tx } from "@earendil-works/pi-durable";
4
+ import { Effect, Match, Schema } from "effect";
5
+ import type { SessionRuntime } from "../../runtime/session.ts";
6
+ import { requestId } from "../../runtime/bridge.ts";
7
+ import {
8
+ AgentDefinition,
9
+ availableDefinitionNames,
10
+ decodeInlineDefinition,
11
+ DefinitionNotFound,
12
+ DefinitionWidened,
13
+ InlineDefinition,
14
+ type DefinitionCatalogue,
15
+ } from "../definitions.ts";
16
+ import {
17
+ claimLaunch,
18
+ resolverFor,
19
+ RunDoc,
20
+ RunIndexDoc,
21
+ type RunInput,
22
+ type RunMode,
23
+ type RunResult,
24
+ type RunState,
25
+ } from "../run-records.ts";
26
+ import { bindToolkit } from "../toolkit.ts";
27
+ import { resolveMaxTurns } from "../turn-budget.ts";
28
+ import { Execution } from "../failure.ts";
29
+ import { FanoutRequest, type FanoutChild, type FanoutInput, type FanoutPolicy } from "./fanout.ts";
30
+ import { REVIEW_INSTRUCTION } from "./review.ts";
31
+ import { CODING_EXTENSION } from "../names.ts";
32
+ import { waitForRun } from "./run-wait.ts";
33
+ import { viewRun, type RunView } from "../view.ts";
34
+ import { taskId as toTaskId } from "../ids.ts";
35
+
36
+ export const SingleRequest = Schema.Struct({
37
+ kind: Schema.Literal("single"),
38
+ agent: Schema.String,
39
+ task: Schema.String,
40
+ definition: Schema.optional(InlineDefinition),
41
+ /** The turn budget for this call; a child's own value wins over it. */
42
+ maxTurns: Schema.optional(Schema.Finite),
43
+ /** Absent: `wait`. Part of the request, so part of the run's identity. */
44
+ execution: Schema.optional(Execution),
45
+ });
46
+ export type SingleRequest = typeof SingleRequest.Type;
47
+
48
+ /** The one normalization: `wait` and absent hash identically, so they are one run. */
49
+ export const requestForIdentity = <T extends { readonly execution?: Execution | undefined }>(
50
+ request: T,
51
+ ): T => (request.execution !== "wait" ? request : { ...request, execution: undefined });
52
+
53
+ export const ReviewRequest = Schema.Struct({
54
+ kind: Schema.Literal("review"),
55
+ task: Schema.String,
56
+ reviewers: Schema.Array(
57
+ Schema.Struct({
58
+ agent: Schema.String,
59
+ /** This reviewer's own budget. */
60
+ maxTurns: Schema.optional(Schema.Finite),
61
+ }),
62
+ ),
63
+ /** The budget for every reviewer this request does not name one for. */
64
+ maxTurns: Schema.optional(Schema.Finite),
65
+ lane: Schema.optional(Schema.String),
66
+ /** Absent: `wait`. */
67
+ execution: Schema.optional(Execution),
68
+ });
69
+ export type ReviewRequest = typeof ReviewRequest.Type;
70
+
71
+ export const WorkflowRequest = Schema.Struct({
72
+ kind: Schema.Literal("workflow"),
73
+ agent: Schema.String,
74
+ script: Schema.String,
75
+ lane: Schema.optional(Schema.String),
76
+ });
77
+ export type WorkflowRequest = typeof WorkflowRequest.Type;
78
+
79
+ /** The largest script a workflow launch accepts, in UTF-8 bytes. */
80
+ export const MAX_SCRIPT_BYTES = 65_536;
81
+
82
+ export type LaunchRequest = SingleRequest | FanoutRequest | ReviewRequest | WorkflowRequest;
83
+
84
+ /** The model's arguments as one union: decode at the tool boundary, never cast. */
85
+ export const LaunchRequestSchema = Schema.Union([
86
+ SingleRequest,
87
+ FanoutRequest,
88
+ ReviewRequest,
89
+ WorkflowRequest,
90
+ ]);
91
+
92
+ export interface HostDefaults {
93
+ readonly model: { readonly provider: string; readonly modelId: string };
94
+ readonly thinkingLevel: ModelThinkingLevel;
95
+ }
96
+
97
+ export interface RunPlan {
98
+ readonly definition: AgentDefinition;
99
+ readonly inline: boolean;
100
+ }
101
+
102
+ export class HostModelMissing extends Schema.TaggedError<
103
+ HostModelMissing,
104
+ { readonly brand: unique symbol }
105
+ >()("HostModelMissing", {
106
+ message: Schema.String,
107
+ }) {}
108
+
109
+ export class WorkflowNotEnabled extends Schema.TaggedError<
110
+ WorkflowNotEnabled,
111
+ { readonly brand: unique symbol }
112
+ >()("WorkflowNotEnabled", { message: Schema.String }) {}
113
+
114
+ export class WorkflowOnly extends Schema.TaggedError<
115
+ WorkflowOnly,
116
+ { readonly brand: unique symbol }
117
+ >()("WorkflowOnly", {
118
+ message: Schema.String,
119
+ }) {}
120
+
121
+ export class WorkflowTooLarge extends Schema.TaggedError<
122
+ WorkflowTooLarge,
123
+ { readonly brand: unique symbol }
124
+ >()("WorkflowTooLarge", {
125
+ message: Schema.String,
126
+ }) {}
127
+
128
+ const EMPTY_APPROVAL = { gates: [] } as const;
129
+
130
+ const validateToolkit = (definition: AgentDefinition, deps: LaunchDeps): Promise<unknown> =>
131
+ Effect.runPromise(
132
+ bindToolkit(
133
+ definition,
134
+ resolverFor({
135
+ registry: deps.runtime.registry.snapshot(),
136
+ skills: deps.runtime.skills,
137
+ presence: deps.runtime.mcpPresence,
138
+ }),
139
+ ),
140
+ );
141
+
142
+ /** Plans one single request and records a missing host model before it can claim a run. */
143
+ const planFor = async (request: SingleRequest, deps: LaunchDeps): Promise<RunPlan> => {
144
+ try {
145
+ return await Effect.runPromise(planLaunch(request, deps.catalogue, deps.host));
146
+ } catch (error) {
147
+ if (error instanceof HostModelMissing) {
148
+ deps.runtime.log.write("error", "launch.host_model_missing", { agent: request.agent });
149
+ }
150
+ throw error;
151
+ }
152
+ };
153
+
154
+ const fillHost = (definition: AgentDefinition, host: HostDefaults): AgentDefinition => ({
155
+ ...definition,
156
+ model: definition.model ?? host.model,
157
+ thinkingLevel: definition.thinkingLevel ?? host.thinkingLevel,
158
+ });
159
+
160
+ /** A launch without a model cannot generate: refuse it before a task or a run exists. */
161
+ const planned = (
162
+ definition: AgentDefinition,
163
+ inline: boolean,
164
+ ): Effect.Effect<RunPlan, HostModelMissing> => {
165
+ const model = definition.model;
166
+ if (model === undefined || model.provider === "" || model.modelId === "") {
167
+ return Effect.fail(
168
+ HostModelMissing.make({
169
+ message:
170
+ `Definition "${definition.name}" has no host model: model.provider and ` +
171
+ `model.modelId are empty. Select a model in the session or set both on the definition.`,
172
+ }),
173
+ );
174
+ }
175
+ return Effect.succeed({ definition, inline });
176
+ };
177
+
178
+ /**
179
+ * Resolves a single request into one effective definition. A registered
180
+ * definition of the same name always contributes extensions and approval
181
+ * rules; an inline definition may only narrow the tools (and may fill a model
182
+ * or prompt the registered one leaves unset).
183
+ */
184
+ export const planLaunch = (
185
+ request: SingleRequest,
186
+ catalogue: DefinitionCatalogue,
187
+ host: HostDefaults,
188
+ ): Effect.Effect<RunPlan, DefinitionNotFound | DefinitionWidened | HostModelMissing> => {
189
+ const registered = catalogue.find(request.agent);
190
+ const inline = request.definition;
191
+ if (inline === undefined) {
192
+ if (registered === undefined) {
193
+ return Effect.fail(
194
+ DefinitionNotFound.make({
195
+ message: `Definition "${request.agent}" not found. Available: ${availableDefinitionNames(catalogue)}.`,
196
+ }),
197
+ );
198
+ }
199
+ return planned(fillHost(registered, host), false);
200
+ }
201
+
202
+ if (registered === undefined) {
203
+ return planned(
204
+ fillHost(
205
+ {
206
+ ...inline,
207
+ extensions: [CODING_EXTENSION],
208
+ approval: EMPTY_APPROVAL,
209
+ },
210
+ host,
211
+ ),
212
+ true,
213
+ );
214
+ }
215
+
216
+ const widened = inline.tools.filter((name) => !registered.tools.includes(name));
217
+ if (widened.length > 0) {
218
+ return Effect.fail(
219
+ DefinitionWidened.make({
220
+ message:
221
+ `Inline definition "${inline.name}" adds tools the registered definition ` +
222
+ `"${registered.name}" does not allow: ${widened.join(", ")}.`,
223
+ }),
224
+ );
225
+ }
226
+
227
+ return planned(
228
+ fillHost(
229
+ {
230
+ ...registered,
231
+ name: registered.name,
232
+ role: registered.role,
233
+ prompt: registered.prompt,
234
+ tools: inline.tools,
235
+ cwd: registered.cwd ?? inline.cwd,
236
+ model: registered.model ?? inline.model,
237
+ thinkingLevel: registered.thinkingLevel ?? inline.thinkingLevel,
238
+ extensions: registered.extensions,
239
+ approval: registered.approval,
240
+ },
241
+ host,
242
+ ),
243
+ true,
244
+ );
245
+ };
246
+
247
+ export interface LaunchDeps {
248
+ readonly runtime: SessionRuntime;
249
+ readonly catalogue: DefinitionCatalogue;
250
+ readonly host: HostDefaults;
251
+ readonly waitMs: number;
252
+ readonly signal?: AbortSignal;
253
+ readonly context?: Context;
254
+ }
255
+
256
+ export interface LaunchResult {
257
+ readonly view: RunView;
258
+ readonly text: string;
259
+ }
260
+
261
+ /** The run text one tool returns: the answer, the waiting reason or the status. */
262
+ export const textFor = (view: RunView): string => {
263
+ switch (view.status) {
264
+ case "answered":
265
+ return view.mode === "fanout" || view.mode === "review"
266
+ ? `Run ${view.runId}: ${view.answer ?? ""}`
267
+ : (view.answer ?? "");
268
+ case "waiting": {
269
+ const parts = [
270
+ ...(view.gates.length > 0 ? [`gate ${view.gates.join(", ")}`] : []),
271
+ ...(view.requests.length > 0 ? [`request ${view.requests.join(", ")}`] : []),
272
+ ];
273
+ // Waiting with nothing named is a group whose children run, not a decision.
274
+ return parts.length > 0
275
+ ? `Run ${view.runId} waits for ${parts.join(" and ")}.`
276
+ : `Run ${view.runId} is running.`;
277
+ }
278
+ case "running":
279
+ return `Run ${view.runId} is running.`;
280
+ case "queued":
281
+ return `Run ${view.runId} is queued.`;
282
+ case "stopped":
283
+ return `Run ${view.runId} is stopped. Resume it with delegate_control.`;
284
+ case "denied":
285
+ return view.diagnostic === null
286
+ ? `Run ${view.runId} was denied.`
287
+ : `Run ${view.runId} was denied: ${view.diagnostic}.`;
288
+ case "failed":
289
+ return `Run ${view.runId} failed: ${view.diagnostic ?? "unknown reason"}.`;
290
+ }
291
+ };
292
+
293
+ const finish = async (
294
+ runId: string,
295
+ runtime: SessionRuntime,
296
+ waitMs: number,
297
+ signal: AbortSignal | undefined,
298
+ ): Promise<LaunchResult> => {
299
+ const runDoc = await runtime.snapshot(RunDoc, runId);
300
+ if (runDoc?.taskId === undefined || runDoc.taskId === null) {
301
+ throw new Error(`Run ${runId} did not record its task.`);
302
+ }
303
+ const taskId = runDoc.taskId;
304
+ const outcome = await waitForRun(
305
+ { runtime, timers: runtime.timers },
306
+ { runId, taskId, waitMs, ...(signal === undefined ? {} : { signal }) },
307
+ );
308
+ if (outcome !== "settled") runtime.log.write("info", `wait.${outcome}`, { runId });
309
+ if (outcome === "aborted") {
310
+ await runtime.run((context) => runtime.harness.abortTask(toTaskId(taskId), context));
311
+ await runtime.run((context) => runtime.harness.waitForTask(toTaskId(taskId), context));
312
+ }
313
+ const view = await viewRun(runId, runtime);
314
+ return { view, text: textFor(view) };
315
+ };
316
+
317
+ /** One child's budget: child level, request level, definition, then the config default. */
318
+ const budgetOf = (input: {
319
+ readonly child?: number | undefined;
320
+ readonly request?: number | undefined;
321
+ readonly definition: AgentDefinition;
322
+ readonly deps: LaunchDeps;
323
+ }): number =>
324
+ resolveMaxTurns({
325
+ ...(input.child === undefined ? {} : { child: input.child }),
326
+ ...(input.request === undefined ? {} : { request: input.request }),
327
+ ...(input.definition.maxTurns === undefined ? {} : { definition: input.definition.maxTurns }),
328
+ configDefault: input.deps.runtime.config.maxTurns,
329
+ ceiling: input.deps.runtime.config.maxTurnsCeiling,
330
+ });
331
+
332
+ /** A detached group returns once its children exist; admission is short, never the run. */
333
+ export const DETACHED_ADMIT_MS = 5_000;
334
+
335
+ /** Waits, bounded, until the run's children are claimed: a detached group's whole wait. */
336
+ export const awaitChildren = async (
337
+ runtime: SessionRuntime,
338
+ runId: string,
339
+ count: number,
340
+ boundMs: number = DETACHED_ADMIT_MS,
341
+ ): Promise<void> => {
342
+ const deadline = runtime.now() + boundMs;
343
+ while (runtime.now() < deadline) {
344
+ const doc = await runtime.snapshot(RunDoc, runId);
345
+ if ((doc?.childRunIds.length ?? 0) >= count) return;
346
+ await new Promise<void>((resolve) => {
347
+ runtime.timers.setTimeout(resolve, 10);
348
+ });
349
+ }
350
+ };
351
+
352
+ /**
353
+ * Wait enters the frozen wait unchanged; detached returns the opening view at
354
+ * claim, or once a group's children exist so the view names one row per child.
355
+ */
356
+ const afterClaim = async (
357
+ execution: Execution | undefined,
358
+ runId: string,
359
+ deps: LaunchDeps,
360
+ children: number = 0,
361
+ ): Promise<LaunchResult> => {
362
+ if (execution !== "detached") return finish(runId, deps.runtime, deps.waitMs, deps.signal);
363
+ if (children > 0) {
364
+ await awaitChildren(
365
+ deps.runtime,
366
+ runId,
367
+ children,
368
+ Math.min(deps.waitMs > 0 ? deps.waitMs : DETACHED_ADMIT_MS, DETACHED_ADMIT_MS),
369
+ );
370
+ }
371
+ const view = await viewRun(runId, deps.runtime);
372
+ return { view, text: textFor(view) };
373
+ };
374
+
375
+ /** A codemode definition accepts workflow launches only. */
376
+ const assertWorkflowOnly = (agent: string, definition: AgentDefinition): void => {
377
+ if (definition.codemode === "runs") {
378
+ throw WorkflowOnly.make({
379
+ message: `Definition "${agent}" runs workflows only; launch it with kind: "workflow".`,
380
+ });
381
+ }
382
+ };
383
+
384
+ /** A workflow needs the definition's `codemode: "runs"`; without it, no run is claimed. */
385
+ const assertWorkflowEnabled = (agent: string, definition: AgentDefinition): void => {
386
+ if (definition.codemode !== "runs") {
387
+ throw WorkflowNotEnabled.make({
388
+ message:
389
+ `Definition "${agent}" does not enable code mode; a workflow launch needs ` +
390
+ `codemode: "runs" on the registered definition.`,
391
+ });
392
+ }
393
+ };
394
+
395
+ const assertScriptSize = (script: string): void => {
396
+ const bytes = Buffer.byteLength(script, "utf8");
397
+ if (bytes > MAX_SCRIPT_BYTES) {
398
+ throw WorkflowTooLarge.make({
399
+ message: `The script is ${bytes} bytes; a workflow script may be at most ${MAX_SCRIPT_BYTES} bytes.`,
400
+ });
401
+ }
402
+ };
403
+
404
+ /** Launches one agent, waits under the soft deadline and returns its view. */
405
+ export const launch = async (request: LaunchRequest, deps: LaunchDeps): Promise<LaunchResult> =>
406
+ Match.value(request).pipe(
407
+ Match.discriminators("kind")({
408
+ single: (r) => launchSingle(r, deps, { lane: "default", mode: "single" }),
409
+ fanout: (r) => launchFanout(r, deps),
410
+ review: (r) => launchReview(r, deps),
411
+ workflow: (r) =>
412
+ launchSingle({ kind: "single", agent: r.agent, task: r.script }, deps, {
413
+ lane: r.lane ?? "workflow",
414
+ mode: "workflow",
415
+ }),
416
+ }),
417
+ Match.exhaustive,
418
+ );
419
+
420
+ export interface SingleClaimRequest {
421
+ readonly runTask: Task<RunInput, RunState, RunResult, Record<never, never>>;
422
+ /** The run input without the fields the claim decides: run id, gate run, attempt, submission key. */
423
+ readonly input: Omit<RunInput, "runId" | "gateRunId" | "attempt" | "submissionKey">;
424
+ readonly requestedAgent: string;
425
+ /** The conversation that owns the created task: the root, or the workflow run's owner. */
426
+ readonly conversationId: ConversationId;
427
+ readonly ownership: TaskOptions["ownership"];
428
+ readonly mode: RunMode;
429
+ /** The launch kind the run document records; absent: `wait`. */
430
+ readonly execution?: Execution;
431
+ /** The workflow run whose child this is: recorded as `parentRunId` and appended to its list. */
432
+ readonly parent?: {
433
+ readonly runId: string;
434
+ readonly definition: string;
435
+ readonly lane: string;
436
+ readonly mode: RunMode;
437
+ };
438
+ /** Whether the run index records this run; a scripted child is listed for `status`. */
439
+ readonly index: boolean;
440
+ }
441
+
442
+ export interface SingleClaim {
443
+ readonly runId: string;
444
+ readonly attempt: number;
445
+ readonly taskId: number;
446
+ }
447
+
448
+ /** One commit claims the run, creates its task and writes the run document. */
449
+ export type ClaimCommit = <T>(change: (tx: Tx) => T | Promise<T>) => Promise<T>;
450
+
451
+ /**
452
+ * The one single-run write set: `launch()` and the script's `launch` tool both
453
+ * call it, so neither duplicates the claim, the task, the document or the index.
454
+ */
455
+ export const claimSingle = async (
456
+ commit: ClaimCommit,
457
+ request: SingleClaimRequest,
458
+ ): Promise<SingleClaim> =>
459
+ commit(async (tx) => {
460
+ const seed = {
461
+ definition: request.input.definition.name,
462
+ lane: request.input.lane,
463
+ mode: request.mode,
464
+ ...(request.execution === undefined ? {} : { execution: request.execution }),
465
+ ...(request.parent === undefined ? {} : { parentRunId: request.parent.runId }),
466
+ };
467
+ const claimed = await claimLaunch(tx, {
468
+ requestId: request.input.requestId,
469
+ definition: request.input.definition.name,
470
+ lane: request.input.lane,
471
+ seed,
472
+ });
473
+ if (claimed.reuseTaskId !== undefined) {
474
+ return { runId: claimed.runId, attempt: claimed.attempt, taskId: claimed.reuseTaskId };
475
+ }
476
+
477
+ const gateRunId = request.parent?.runId ?? claimed.runId;
478
+ const input: RunInput = {
479
+ ...request.input,
480
+ runId: claimed.runId,
481
+ gateRunId,
482
+ attempt: claimed.attempt,
483
+ submissionKey: `${claimed.runId}:task`,
484
+ };
485
+ const taskId = await tx.createTask(request.runTask, input, {
486
+ ownership: request.ownership,
487
+ conversationId: request.conversationId,
488
+ });
489
+ const doc = await tx.doc(RunDoc, claimed.runId, seed);
490
+ doc.requestedAgent = request.requestedAgent;
491
+ doc.task = input.task;
492
+ doc.requestId = input.requestId;
493
+ doc.attempt = claimed.attempt;
494
+ doc.taskId = taskId;
495
+ doc.gateRunId = gateRunId;
496
+ doc.maxTurns = input.maxTurns;
497
+ if (request.parent !== undefined) {
498
+ doc.parentRunId = request.parent.runId;
499
+ const parentDoc = await tx.doc(RunDoc, request.parent.runId, {
500
+ definition: request.parent.definition,
501
+ lane: request.parent.lane,
502
+ mode: request.parent.mode,
503
+ });
504
+ if (!parentDoc.childRunIds.includes(claimed.runId)) parentDoc.childRunIds.push(claimed.runId);
505
+ }
506
+ if (request.index) {
507
+ const index = await tx.doc(RunIndexDoc);
508
+ if (!index.runIds.includes(claimed.runId)) index.runIds.push(claimed.runId);
509
+ }
510
+ return { runId: claimed.runId, attempt: claimed.attempt, taskId };
511
+ });
512
+
513
+ const launchSingle = async (
514
+ request: SingleRequest,
515
+ deps: LaunchDeps,
516
+ options: { readonly lane: string; readonly mode: RunMode },
517
+ ): Promise<LaunchResult> => {
518
+ // Strip unknown fields and name the owner-only ones before planning or hashing the request.
519
+ const resolved: SingleRequest =
520
+ request.definition === undefined
521
+ ? request
522
+ : { ...request, definition: decodeInlineDefinition(request.definition) };
523
+ const plan = await planFor(resolved, deps);
524
+ if (options.mode === "workflow") {
525
+ assertWorkflowEnabled(request.agent, plan.definition);
526
+ assertScriptSize(request.task);
527
+ } else {
528
+ assertWorkflowOnly(request.agent, plan.definition);
529
+ }
530
+ await validateToolkit(plan.definition, deps);
531
+ const identity = requestId(deps.runtime.sessionId, requestForIdentity(resolved));
532
+ const lane = options.lane;
533
+ const maxTurns = resolveMaxTurns({
534
+ ...(resolved.maxTurns === undefined ? {} : { request: resolved.maxTurns }),
535
+ ...(plan.definition.maxTurns === undefined ? {} : { definition: plan.definition.maxTurns }),
536
+ configDefault: deps.runtime.config.maxTurns,
537
+ ceiling: deps.runtime.config.maxTurnsCeiling,
538
+ });
539
+
540
+ const claim = await deps.runtime.run((context) =>
541
+ claimSingle((change) => deps.runtime.harness.commit(change, deps.context ?? context), {
542
+ runTask: deps.runtime.tasks.run,
543
+ input: {
544
+ requestId: identity,
545
+ definition: plan.definition,
546
+ task: request.task,
547
+ host: deps.host,
548
+ lane,
549
+ maxTurns,
550
+ },
551
+ requestedAgent: request.agent,
552
+ conversationId: deps.runtime.root.id,
553
+ ownership: { kind: "conversation" },
554
+ mode: options.mode,
555
+ ...(request.execution === undefined ? {} : { execution: request.execution }),
556
+ index: true,
557
+ }),
558
+ );
559
+
560
+ return afterClaim(request.execution, claim.runId, deps);
561
+ };
562
+
563
+ const startGroup = async (
564
+ request: LaunchRequest,
565
+ deps: LaunchDeps,
566
+ group: {
567
+ readonly lane: string;
568
+ readonly definition: string;
569
+ readonly mode: RunMode;
570
+ readonly children: readonly FanoutChild[];
571
+ readonly policy: FanoutPolicy;
572
+ readonly review: boolean;
573
+ readonly label: string;
574
+ },
575
+ ): Promise<LaunchResult> => {
576
+ const identity = requestId(
577
+ deps.runtime.sessionId,
578
+ requestForIdentity(request as LaunchRequest & { readonly execution?: Execution }),
579
+ );
580
+ const execution = "execution" in request ? request.execution : undefined;
581
+ const seed = {
582
+ definition: group.definition,
583
+ lane: group.lane,
584
+ mode: group.mode,
585
+ ...(execution === undefined ? {} : { execution }),
586
+ };
587
+
588
+ const claim = await deps.runtime.run((context) =>
589
+ deps.runtime.harness.commit(async (tx) => {
590
+ const claimed = await claimLaunch(tx, {
591
+ requestId: identity,
592
+ definition: group.definition,
593
+ lane: group.lane,
594
+ seed,
595
+ });
596
+ if (claimed.reuseTaskId !== undefined) return claimed;
597
+
598
+ const input: FanoutInput = {
599
+ runId: claimed.runId,
600
+ lane: group.lane,
601
+ children: group.children,
602
+ host: deps.host,
603
+ maxTurns: deps.runtime.config.maxTurns,
604
+ ...(execution === undefined ? {} : { execution }),
605
+ policy: group.policy,
606
+ review: group.review,
607
+ };
608
+ const taskId = await tx.createTask(deps.runtime.tasks.fanout, input, {
609
+ ownership: { kind: "conversation" },
610
+ conversationId: deps.runtime.root.id,
611
+ });
612
+ const doc = await tx.doc(RunDoc, claimed.runId, seed);
613
+ doc.execution = execution ?? "wait";
614
+ doc.requestedAgent = group.lane;
615
+ doc.task = `${group.label}: ${group.children.length} children`;
616
+ doc.requestId = identity;
617
+ doc.attempt = claimed.attempt;
618
+ doc.taskId = taskId;
619
+ doc.gateRunId = claimed.runId;
620
+ const index = await tx.doc(RunIndexDoc);
621
+ if (!index.runIds.includes(claimed.runId)) index.runIds.push(claimed.runId);
622
+ return claimed;
623
+ }, deps.context ?? context),
624
+ );
625
+
626
+ return afterClaim(execution, claim.runId, deps, group.children.length);
627
+ };
628
+
629
+ const launchFanout = async (request: FanoutRequest, deps: LaunchDeps): Promise<LaunchResult> => {
630
+ const children: FanoutChild[] = [];
631
+ for (const entry of request.agents) {
632
+ const plan = await planFor({ kind: "single", agent: entry.agent, task: entry.task }, deps);
633
+ assertWorkflowOnly(entry.agent, plan.definition);
634
+ await validateToolkit(plan.definition, deps);
635
+ children.push({
636
+ agent: entry.agent,
637
+ task: entry.task,
638
+ definition: plan.definition,
639
+ maxTurns: budgetOf({
640
+ child: entry.maxTurns,
641
+ request: request.maxTurns,
642
+ definition: plan.definition,
643
+ deps,
644
+ }),
645
+ });
646
+ }
647
+ return startGroup(request, deps, {
648
+ lane: request.lane,
649
+ definition: "fanout",
650
+ mode: "fanout",
651
+ children,
652
+ policy: request.policy ?? "allSettled",
653
+ review: false,
654
+ label: "fanout",
655
+ });
656
+ };
657
+
658
+ const launchReview = async (request: ReviewRequest, deps: LaunchDeps): Promise<LaunchResult> => {
659
+ const children: FanoutChild[] = [];
660
+ for (const reviewer of request.reviewers) {
661
+ const plan = await planFor({ kind: "single", agent: reviewer.agent, task: request.task }, deps);
662
+ assertWorkflowOnly(reviewer.agent, plan.definition);
663
+ await validateToolkit(plan.definition, deps);
664
+ children.push({
665
+ agent: reviewer.agent,
666
+ task: request.task,
667
+ definition: {
668
+ ...plan.definition,
669
+ prompt: {
670
+ ...plan.definition.prompt,
671
+ role: `${plan.definition.prompt.role}\n\n${REVIEW_INSTRUCTION}`,
672
+ },
673
+ },
674
+ maxTurns: budgetOf({
675
+ child: reviewer.maxTurns,
676
+ request: request.maxTurns,
677
+ definition: plan.definition,
678
+ deps,
679
+ }),
680
+ });
681
+ }
682
+ return startGroup(request, deps, {
683
+ lane: request.lane ?? "review",
684
+ definition: "review",
685
+ mode: "review",
686
+ children,
687
+ policy: "allSettled",
688
+ review: true,
689
+ label: "review",
690
+ });
691
+ };