@ftrdotdev/pi-delegates 0.0.0-stage → 0.1.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 (116) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +57 -0
  4. package/README.md +448 -2
  5. package/ROADMAP.md +158 -0
  6. package/TESTING.md +1061 -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 +93 -4
  12. package/skills/pi-delegates/SKILL.md +147 -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 +156 -0
  17. package/src/domain/definitions.test.ts +41 -0
  18. package/src/domain/definitions.ts +161 -0
  19. package/src/domain/ids.ts +13 -0
  20. package/src/domain/names.ts +35 -0
  21. package/src/domain/orchestration/admission.ts +78 -0
  22. package/src/domain/orchestration/control.test.ts +1298 -0
  23. package/src/domain/orchestration/control.ts +436 -0
  24. package/src/domain/orchestration/fanout.test.ts +419 -0
  25. package/src/domain/orchestration/fanout.ts +334 -0
  26. package/src/domain/orchestration/gates.test.ts +686 -0
  27. package/src/domain/orchestration/gates.ts +360 -0
  28. package/src/domain/orchestration/launch.test.ts +173 -0
  29. package/src/domain/orchestration/launch.ts +581 -0
  30. package/src/domain/orchestration/requests.test.ts +700 -0
  31. package/src/domain/orchestration/requests.ts +769 -0
  32. package/src/domain/orchestration/review.test.ts +214 -0
  33. package/src/domain/orchestration/review.ts +168 -0
  34. package/src/domain/orchestration/run-wait.test.ts +262 -0
  35. package/src/domain/orchestration/run-wait.ts +256 -0
  36. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  37. package/src/domain/orchestration/workflow-section.ts +99 -0
  38. package/src/domain/orchestration/workflow.test.ts +1425 -0
  39. package/src/domain/orchestration/workflow.ts +705 -0
  40. package/src/domain/run-records.test.ts +27 -0
  41. package/src/domain/run-records.ts +527 -0
  42. package/src/domain/shapes.test.ts +165 -0
  43. package/src/domain/skills.test.ts +466 -0
  44. package/src/domain/skills.ts +97 -0
  45. package/src/domain/tool-schema.test.ts +46 -0
  46. package/src/domain/tool-schema.ts +20 -0
  47. package/src/domain/toolkit.test.ts +201 -0
  48. package/src/domain/toolkit.ts +379 -0
  49. package/src/domain/view.test.ts +739 -0
  50. package/src/domain/view.ts +459 -0
  51. package/src/example.test.ts +15 -0
  52. package/src/extension/commands.test.ts +481 -0
  53. package/src/extension/commands.ts +227 -0
  54. package/src/extension/entry.test.ts +1118 -0
  55. package/src/extension/entry.ts +342 -0
  56. package/src/extension/gate-alerts.test.ts +235 -0
  57. package/src/extension/gate-alerts.ts +143 -0
  58. package/src/extension/guard.test.ts +48 -0
  59. package/src/extension/guard.ts +31 -0
  60. package/src/extension/host-signals.test.ts +20 -0
  61. package/src/extension/host-signals.ts +13 -0
  62. package/src/extension/inspector-command.test.ts +1191 -0
  63. package/src/extension/inspector-command.ts +638 -0
  64. package/src/extension/prompt.test.ts +110 -0
  65. package/src/extension/prompt.ts +50 -0
  66. package/src/extension/request-alerts.test.ts +183 -0
  67. package/src/extension/request-alerts.ts +181 -0
  68. package/src/extension/revocation.test.ts +81 -0
  69. package/src/extension/revocation.ts +84 -0
  70. package/src/extension/shortcut.test.ts +64 -0
  71. package/src/extension/shortcut.ts +105 -0
  72. package/src/extension/tools.test.ts +993 -0
  73. package/src/extension/tools.ts +505 -0
  74. package/src/extension/version.test.ts +123 -0
  75. package/src/extension/version.ts +97 -0
  76. package/src/harness-policy.test.ts +74 -0
  77. package/src/package-manifest.test.ts +157 -0
  78. package/src/presentation/actions.test.ts +221 -0
  79. package/src/presentation/actions.ts +85 -0
  80. package/src/presentation/activity.test.ts +387 -0
  81. package/src/presentation/activity.ts +66 -0
  82. package/src/presentation/close.test.ts +361 -0
  83. package/src/presentation/inspector.test.ts +679 -0
  84. package/src/presentation/inspector.ts +440 -0
  85. package/src/presentation/overlay.test.ts +555 -0
  86. package/src/presentation/overlay.ts +229 -0
  87. package/src/presentation/repaint.test.ts +329 -0
  88. package/src/presentation/shortcut.ts +2 -0
  89. package/src/presentation/snapshot.test.ts +530 -0
  90. package/src/presentation/snapshot.ts +306 -0
  91. package/src/presentation/strip.test.ts +196 -0
  92. package/src/presentation/strip.ts +74 -0
  93. package/src/presentation/wording.test.ts +238 -0
  94. package/src/presentation/wording.ts +222 -0
  95. package/src/runtime/bridge.test.ts +131 -0
  96. package/src/runtime/bridge.ts +134 -0
  97. package/src/runtime/config.test.ts +44 -0
  98. package/src/runtime/config.ts +87 -0
  99. package/src/runtime/context.test.ts +19 -0
  100. package/src/runtime/context.ts +9 -0
  101. package/src/runtime/execution-env.test.ts +35 -0
  102. package/src/runtime/execution-env.ts +15 -0
  103. package/src/runtime/extensions.test.ts +86 -0
  104. package/src/runtime/extensions.ts +140 -0
  105. package/src/runtime/log.test.ts +128 -0
  106. package/src/runtime/log.ts +68 -0
  107. package/src/runtime/mcp.test.ts +1453 -0
  108. package/src/runtime/mcp.ts +938 -0
  109. package/src/runtime/models.test.ts +145 -0
  110. package/src/runtime/models.ts +259 -0
  111. package/src/runtime/observe.test.ts +50 -0
  112. package/src/runtime/observe.ts +150 -0
  113. package/src/runtime/session.test.ts +359 -0
  114. package/src/runtime/session.ts +425 -0
  115. package/src/runtime/timers.test.ts +31 -0
  116. package/src/runtime/timers.ts +10 -0
@@ -0,0 +1,705 @@
1
+ import type { Context } from "@earendil-works/chord/context";
2
+ import type { JsonValue } from "@earendil-works/chord/json";
3
+ import {
4
+ defineExtension,
5
+ defineTool,
6
+ type Extension,
7
+ type ToolExecutionApi,
8
+ type ToolExecutionResult,
9
+ type ToolPark,
10
+ type ToolRegistration,
11
+ } from "@earendil-works/pi-durable";
12
+ import { Context as EffectContext, Effect, Layer, Schema } from "effect";
13
+ import type { SessionRuntime } from "../../runtime/session.ts";
14
+ import { requestId } from "../../runtime/bridge.ts";
15
+ import { DefinitionNotFound, type AgentDefinition } from "../definitions.ts";
16
+ import { RUN_TOOL_NAMES, RUNS_EXTENSION } from "../names.ts";
17
+ import { claimLaunch, resolverFor, RunDoc, RunIndexDoc, type LaunchClaim } from "../run-records.ts";
18
+ import { bindToolkit, ToolkitDoc } from "../toolkit.ts";
19
+ import { statusOf, viewRun, viewSession, LaneView, RunStatus } from "../view.ts";
20
+ import { taskId as toTaskId } from "../ids.ts";
21
+ import { declared, decode, type DeclaredSchema } from "../tool-schema.ts";
22
+ import { control, RunNotFound, RunNotResumable, RunNotRunning } from "./control.ts";
23
+ import type { FanoutInput } from "./fanout.ts";
24
+ import { DAY_MS, decisionOf, GateDecision, GateDoc, gateKey, requestGate } from "./gates.ts";
25
+ import { HostModelMissing, claimSingle, planLaunch, WorkflowOnly } from "./launch.ts";
26
+ import { workflowSection } from "./workflow-section.ts";
27
+
28
+ /** One child of a workflow, as a script reads it: a failed child is a value, not an exception. */
29
+ export const ChildOutcome = Schema.Struct({
30
+ run: Schema.String,
31
+ answer: Schema.String,
32
+ status: RunStatus,
33
+ });
34
+ export type ChildOutcome = typeof ChildOutcome.Type;
35
+
36
+ export const ChildOutcomes = Schema.Struct({ runs: Schema.Array(ChildOutcome) });
37
+
38
+ export const StatusEntry = Schema.Struct({
39
+ run: Schema.String,
40
+ definition: Schema.String,
41
+ lane: Schema.String,
42
+ status: RunStatus,
43
+ });
44
+
45
+ export const StatusProjection = Schema.Struct({ runs: Schema.Array(StatusEntry) });
46
+
47
+ export const RunRef = Schema.Struct({
48
+ run: Schema.String,
49
+ conversationId: Schema.NullOr(Schema.Finite),
50
+ gateRunId: Schema.String,
51
+ });
52
+
53
+ export const GateDecisionOut = Schema.Struct({
54
+ decision: Schema.Literals(["approved", "denied", "expired"]),
55
+ });
56
+
57
+ /** What the gate tool learns: a pending gate to park on, or the decision that closed one. */
58
+ export type GateOutcome =
59
+ | { readonly kind: "pending"; readonly key: string; readonly until: number }
60
+ | {
61
+ readonly kind: "decided";
62
+ readonly decision: (typeof GateDecisionOut.Type)["decision"];
63
+ };
64
+
65
+ const LaunchArgs = Schema.Struct({
66
+ agent: Schema.String,
67
+ task: Schema.String,
68
+ lane: Schema.optional(Schema.String),
69
+ });
70
+
71
+ const ManyArgs = Schema.Struct({
72
+ children: Schema.Array(Schema.Struct({ agent: Schema.String, task: Schema.String })),
73
+ lane: Schema.optional(Schema.String),
74
+ });
75
+
76
+ const LaneArgs = Schema.Struct({ name: Schema.String });
77
+ const StatusArgs = Schema.Struct({ run: Schema.optional(Schema.String) });
78
+ const RefArgs = Schema.Struct({ run: Schema.String });
79
+ const SteerArgs = Schema.Struct({ run: Schema.String, message: Schema.String });
80
+ const StopArgs = Schema.Struct({ run: Schema.String });
81
+ const GateArgs = Schema.Struct({ name: Schema.String, note: Schema.optional(Schema.String) });
82
+
83
+ export class WorkflowRefused extends Schema.TaggedError<
84
+ WorkflowRefused,
85
+ { readonly brand: unique symbol }
86
+ >()("WorkflowRefused", {
87
+ reason: Schema.Literals(["own-run", "not-running", "unknown-gate", "duplicate-gate"]),
88
+ message: Schema.String,
89
+ }) {}
90
+
91
+ export type WorkflowError =
92
+ | DefinitionNotFound
93
+ | HostModelMissing
94
+ | RunNotFound
95
+ | RunNotResumable
96
+ | RunNotRunning
97
+ | WorkflowRefused;
98
+
99
+ /** The refusals a script sees as a value: an `isError` result that names why. */
100
+ const isRefusal = (error: unknown): error is WorkflowError =>
101
+ error instanceof WorkflowRefused ||
102
+ error instanceof RunNotFound ||
103
+ error instanceof RunNotResumable ||
104
+ error instanceof RunNotRunning;
105
+
106
+ const step = <A>(operation: () => Promise<A>): Effect.Effect<A, WorkflowError> =>
107
+ Effect.tryPromise({
108
+ try: operation,
109
+ catch: (error) => {
110
+ if (isRefusal(error)) return error;
111
+ // A definition, a host model or a sandbox that cannot resolve is a mistake, not a refusal.
112
+ throw error;
113
+ },
114
+ });
115
+
116
+ export interface WorkflowDeps {
117
+ /** The session runtime, resolved per tool execute: the registry predates the harness. */
118
+ readonly runtime: () => SessionRuntime;
119
+ }
120
+
121
+ export interface WorkflowServiceShape {
122
+ launch(
123
+ args: typeof LaunchArgs.Type,
124
+ api: ToolExecutionApi,
125
+ context: Context,
126
+ ): Effect.Effect<ChildOutcome, WorkflowError>;
127
+ launchMany(
128
+ args: typeof ManyArgs.Type,
129
+ api: ToolExecutionApi,
130
+ context: Context,
131
+ ): Effect.Effect<typeof ChildOutcomes.Type, WorkflowError>;
132
+ lane(args: typeof LaneArgs.Type): Effect.Effect<LaneView, WorkflowError>;
133
+ status(args: typeof StatusArgs.Type): Effect.Effect<typeof StatusProjection.Type, WorkflowError>;
134
+ ref(args: typeof RefArgs.Type): Effect.Effect<typeof RunRef.Type, WorkflowError>;
135
+ steer(
136
+ args: typeof SteerArgs.Type,
137
+ api: ToolExecutionApi,
138
+ context: Context,
139
+ ): Effect.Effect<void, WorkflowError>;
140
+ stop(
141
+ args: typeof StopArgs.Type,
142
+ api: ToolExecutionApi,
143
+ context: Context,
144
+ ): Effect.Effect<void, WorkflowError>;
145
+ /**
146
+ * Commits a pending gate and hands it back: the tool parks on it and answers the
147
+ * decision, so the service never waits. A gate of another workflow is refused.
148
+ */
149
+ gate(
150
+ args: typeof GateArgs.Type,
151
+ api: ToolExecutionApi,
152
+ context: Context,
153
+ ): Effect.Effect<GateOutcome, WorkflowError>;
154
+ }
155
+
156
+ /**
157
+ * The script surface as a service. Each tool execute builds its own layer: the
158
+ * layer captures only the lazy runtime getter, so it holds no state.
159
+ */
160
+ export class WorkflowService extends EffectContext.Service<WorkflowService, WorkflowServiceShape>()(
161
+ "@ftrdotdev/pi-delegates/domain/orchestration/workflow/WorkflowService",
162
+ ) {
163
+ static layer = (deps: WorkflowDeps) =>
164
+ Layer.sync(WorkflowService, () => WorkflowService.of(workflowMethods(deps)));
165
+ }
166
+
167
+ type WorkflowToolkit = {
168
+ readonly runId: string;
169
+ readonly runTaskId: number;
170
+ };
171
+
172
+ const toolkitOf = async (
173
+ api: ToolExecutionApi,
174
+ context: Context,
175
+ reason: "not-running" | "unknown-gate" = "not-running",
176
+ ): Promise<WorkflowToolkit> => {
177
+ const toolkit = await api.snapshot(ToolkitDoc, api.conversationId, context);
178
+ if (toolkit === undefined || toolkit.runId === "" || toolkit.runTaskId === 0) {
179
+ throw WorkflowRefused.make({
180
+ reason,
181
+ message:
182
+ "This conversation is not a workflow run; the run tools need a workflow's child conversation.",
183
+ });
184
+ }
185
+ return { runId: toolkit.runId, runTaskId: toolkit.runTaskId };
186
+ };
187
+
188
+ const workflowDocOf = async (runtime: SessionRuntime, runId: string) => {
189
+ const doc = await runtime.snapshot(RunDoc, runId);
190
+ if (doc === undefined) {
191
+ throw RunNotFound.make({ message: `Run ${runId} not found.` });
192
+ }
193
+ return doc;
194
+ };
195
+
196
+ /** Resolves and binds one scripted child; a mistake here fails the call, not a value. */
197
+ const planChild = async (
198
+ runtime: SessionRuntime,
199
+ api: ToolExecutionApi,
200
+ agent: string,
201
+ task: string,
202
+ ) => {
203
+ const plan = await Effect.runPromise(
204
+ planLaunch({ kind: "single", agent, task }, runtime.catalogue, runtime.host()),
205
+ );
206
+ if (plan.definition.codemode === "runs") {
207
+ throw WorkflowOnly.make({
208
+ message: `Definition "${agent}" runs workflows only; a script cannot start another workflow.`,
209
+ });
210
+ }
211
+ await Effect.runPromise(
212
+ bindToolkit(
213
+ plan.definition,
214
+ resolverFor({
215
+ registry: api.registry,
216
+ skills: runtime.skills,
217
+ presence: runtime.mcpPresence,
218
+ }),
219
+ ),
220
+ );
221
+ return plan;
222
+ };
223
+
224
+ const childOutcome = async (runtime: SessionRuntime, runId: string): Promise<ChildOutcome> => {
225
+ const view = await viewRun(runId, runtime);
226
+ return { run: runId, answer: view.answer ?? "", status: view.status };
227
+ };
228
+
229
+ /** The conversation that owns the workflow run task: a task-owned child must live in it. */
230
+ const ownerConversation = async (api: ToolExecutionApi, runTaskId: number, context: Context) => {
231
+ const owner = await api.getTask(toTaskId(runTaskId), context);
232
+ if (owner === undefined) {
233
+ throw WorkflowRefused.make({
234
+ reason: "not-running",
235
+ message: "The workflow run task is not open; this script cannot start a child.",
236
+ });
237
+ }
238
+ return owner.conversationId;
239
+ };
240
+
241
+ const launchChild = async (
242
+ deps: WorkflowDeps,
243
+ args: typeof LaunchArgs.Type,
244
+ api: ToolExecutionApi,
245
+ context: Context,
246
+ ): Promise<ChildOutcome> => {
247
+ const runtime = deps.runtime();
248
+ const toolkit = await toolkitOf(api, context);
249
+ const parent = await workflowDocOf(runtime, toolkit.runId);
250
+ const plan = await planChild(runtime, api, args.agent, args.task);
251
+ const lane = args.lane ?? parent.lane;
252
+ const owner = await ownerConversation(api, toolkit.runTaskId, context);
253
+ const identity = requestId(runtime.sessionId, {
254
+ kind: "single",
255
+ agent: args.agent,
256
+ task: args.task,
257
+ workflow: toolkit.runId,
258
+ call: api.callId,
259
+ });
260
+
261
+ const claimed = await claimSingle((change) => api.commit(change, context), {
262
+ runTask: runtime.tasks.run,
263
+ input: {
264
+ requestId: identity,
265
+ definition: plan.definition,
266
+ task: args.task,
267
+ host: runtime.host(),
268
+ lane,
269
+ maxTurns: runtime.config.maxTurns,
270
+ },
271
+ requestedAgent: args.agent,
272
+ conversationId: owner,
273
+ ownership: { kind: "task", taskId: toTaskId(toolkit.runTaskId) },
274
+ mode: "single",
275
+ parent: {
276
+ runId: toolkit.runId,
277
+ definition: parent.definition,
278
+ lane: parent.lane,
279
+ mode: parent.mode,
280
+ },
281
+ index: true,
282
+ });
283
+
284
+ await api.waitForTask(toTaskId(claimed.taskId), context);
285
+ return childOutcome(runtime, claimed.runId);
286
+ };
287
+
288
+ type ClaimedChild = LaunchClaim & { readonly createdTaskId?: number };
289
+
290
+ const launchGroup = async (
291
+ deps: WorkflowDeps,
292
+ args: typeof ManyArgs.Type,
293
+ api: ToolExecutionApi,
294
+ context: Context,
295
+ ): Promise<{ readonly childRunIds: readonly string[] }> => {
296
+ const runtime = deps.runtime();
297
+ const toolkit = await toolkitOf(api, context);
298
+ const parent = await workflowDocOf(runtime, toolkit.runId);
299
+ const lane = args.lane ?? parent.lane;
300
+ const owner = await ownerConversation(api, toolkit.runTaskId, context);
301
+ const children: { agent: string; task: string; definition: AgentDefinition }[] = [];
302
+ for (const child of args.children) {
303
+ const plan = await planChild(runtime, api, child.agent, child.task);
304
+ children.push({ agent: child.agent, task: child.task, definition: plan.definition });
305
+ }
306
+ const identity = requestId(runtime.sessionId, {
307
+ kind: "fanout",
308
+ workflow: toolkit.runId,
309
+ call: api.callId,
310
+ agents: args.children,
311
+ });
312
+
313
+ const claimed: ClaimedChild = await api.commit(async (tx) => {
314
+ const seed = {
315
+ definition: "fanout",
316
+ lane,
317
+ mode: "fanout" as const,
318
+ parentRunId: toolkit.runId,
319
+ };
320
+ const claim = await claimLaunch(tx, {
321
+ requestId: identity,
322
+ definition: "fanout",
323
+ lane,
324
+ seed,
325
+ });
326
+ if (claim.reuseTaskId !== undefined) return claim;
327
+
328
+ const input: FanoutInput = {
329
+ runId: claim.runId,
330
+ lane,
331
+ children,
332
+ host: runtime.host(),
333
+ maxTurns: runtime.config.maxTurns,
334
+ policy: "allSettled",
335
+ review: false,
336
+ parentRunId: toolkit.runId,
337
+ parentDefinition: parent.definition,
338
+ };
339
+ const taskId = await tx.createTask(runtime.tasks.fanout, input, {
340
+ ownership: { kind: "task", taskId: toTaskId(toolkit.runTaskId) },
341
+ conversationId: owner,
342
+ });
343
+ const doc = await tx.doc(RunDoc, claim.runId, seed);
344
+ doc.requestedAgent = "fanout";
345
+ doc.task = `fanout: ${children.length} children`;
346
+ doc.requestId = identity;
347
+ doc.attempt = claim.attempt;
348
+ doc.taskId = taskId;
349
+ doc.gateRunId = toolkit.runId;
350
+ doc.parentRunId = toolkit.runId;
351
+ const index = await tx.doc(RunIndexDoc);
352
+ if (!index.runIds.includes(claim.runId)) index.runIds.push(claim.runId);
353
+ return { ...claim, createdTaskId: taskId };
354
+ }, context);
355
+
356
+ const taskId = claimed.reuseTaskId ?? claimed.createdTaskId;
357
+ if (taskId === undefined) throw new Error("The workflow group task was not created.");
358
+ await api.waitForTask(toTaskId(taskId), context);
359
+ const group = await workflowDocOf(runtime, claimed.runId);
360
+ const childRunIds = [...group.childRunIds];
361
+ // The workflow nests the group's children: one list the stop path and the view read.
362
+ await api.commit(async (tx) => {
363
+ const doc = await tx.doc(RunDoc, toolkit.runId, {
364
+ definition: parent.definition,
365
+ lane: parent.lane,
366
+ mode: parent.mode,
367
+ });
368
+ for (const runId of childRunIds) {
369
+ if (!doc.childRunIds.includes(runId)) doc.childRunIds.push(runId);
370
+ }
371
+ }, context);
372
+ return { childRunIds };
373
+ };
374
+
375
+ const laneView = async (runtime: SessionRuntime, name: string) => {
376
+ const view = await viewSession(runtime);
377
+ return (
378
+ view.lanes.find((lane) => lane.name === name) ?? {
379
+ name,
380
+ running: 0,
381
+ queued: 0,
382
+ answered: 0,
383
+ }
384
+ );
385
+ };
386
+
387
+ const statusProjection = async (
388
+ runtime: SessionRuntime,
389
+ run: string | undefined,
390
+ ): Promise<typeof StatusProjection.Type> => {
391
+ const index = await runtime.snapshot(RunIndexDoc);
392
+ const runIds = run === undefined ? (index?.runIds ?? []) : [run];
393
+ const runs: { run: string; definition: string; lane: string; status: RunStatus }[] = [];
394
+ for (const runId of runIds) {
395
+ // A named run must exist: an unknown id is a refusal, not an empty list.
396
+ const doc =
397
+ run === undefined
398
+ ? await runtime.snapshot(RunDoc, runId)
399
+ : await workflowDocOf(runtime, runId);
400
+ if (doc === undefined) continue;
401
+ const taskNumber = doc.taskId;
402
+ const task =
403
+ taskNumber === null
404
+ ? undefined
405
+ : await runtime.run((context) => runtime.harness.getTask(toTaskId(taskNumber), context));
406
+ runs.push({ run: runId, definition: doc.definition, lane: doc.lane, status: statusOf(task) });
407
+ }
408
+ return { runs };
409
+ };
410
+
411
+ const runRef = async (runtime: SessionRuntime, run: string): Promise<typeof RunRef.Type> => {
412
+ const doc = await workflowDocOf(runtime, run);
413
+ return {
414
+ run,
415
+ conversationId: doc.childConversationId,
416
+ gateRunId: doc.gateRunId === "" ? run : doc.gateRunId,
417
+ };
418
+ };
419
+
420
+ const refuseOwnRun = (toolkit: WorkflowToolkit, run: string, verb: string): void => {
421
+ if (toolkit.runId === run) {
422
+ throw WorkflowRefused.make({
423
+ reason: "own-run",
424
+ message: `Run ${run} is this script's own run; a script cannot ${verb} it.`,
425
+ });
426
+ }
427
+ };
428
+
429
+ const scriptGateName = (name: string): string => `script:${name}`;
430
+
431
+ /**
432
+ * Commits a pending gate for the workflow run and reports whether to park. A
433
+ * repeated name from another call of the same run is refused.
434
+ */
435
+ const gateOfWorkflow = async (
436
+ args: typeof GateArgs.Type,
437
+ api: ToolExecutionApi,
438
+ context: Context,
439
+ ): Promise<GateOutcome> => {
440
+ const toolkit = await toolkitOf(api, context, "unknown-gate");
441
+ const name = scriptGateName(args.name);
442
+ const key = gateKey(toolkit.runId, name);
443
+ const ownTaskId = api.taskId;
444
+ const existing = await api.snapshot(GateDoc, key, context);
445
+ if (existing !== undefined && existing.status !== "expired") {
446
+ if (!existing.taskIds.includes(ownTaskId)) {
447
+ throw WorkflowRefused.make({
448
+ reason: "duplicate-gate",
449
+ message: `Gate ${name} already exists for run ${toolkit.runId}.`,
450
+ });
451
+ }
452
+ return existing.status === "pending"
453
+ ? { kind: "pending", key, until: existing.deadline }
454
+ : { kind: "decided", decision: decisionOf(existing) };
455
+ }
456
+
457
+ const until = await api.memo(`gate.deadline.${key}`, api.now() + DAY_MS, context);
458
+ await requestGate(api, { key, runId: toolkit.runId, gate: name, tool: "gate", until }, context);
459
+ const record = await api.snapshot(GateDoc, key, context);
460
+ if (record?.status === "pending") return { kind: "pending", key, until };
461
+ return { kind: "decided", decision: decisionOf(record) };
462
+ };
463
+
464
+ const workflowMethods = (deps: WorkflowDeps): WorkflowServiceShape => ({
465
+ launch: (args, api, context) => step(() => launchChild(deps, args, api, context)),
466
+ launchMany: Effect.fnUntraced(function* (args, api, context) {
467
+ const started = yield* step(() => launchGroup(deps, args, api, context));
468
+ const runtime = deps.runtime();
469
+ const runs = yield* Effect.forEach(
470
+ started.childRunIds,
471
+ (runId) => step(() => childOutcome(runtime, runId)),
472
+ { concurrency: "unbounded" },
473
+ );
474
+ return { runs };
475
+ }),
476
+ lane: (args) => step(() => laneView(deps.runtime(), args.name)),
477
+ status: (args) => step(() => statusProjection(deps.runtime(), args.run)),
478
+ ref: (args) => step(() => runRef(deps.runtime(), args.run)),
479
+ steer: (args, api, context) =>
480
+ step(async () => {
481
+ const runtime = deps.runtime();
482
+ const toolkit = await toolkitOf(api, context);
483
+ refuseOwnRun(toolkit, args.run, "steer");
484
+ await control(
485
+ { action: "steer", run: args.run, message: args.message },
486
+ { runtime, wait: { policy: "settle", waitMs: 0 } },
487
+ );
488
+ }),
489
+ stop: (args, api, context) =>
490
+ step(async () => {
491
+ const runtime = deps.runtime();
492
+ const toolkit = await toolkitOf(api, context);
493
+ refuseOwnRun(toolkit, args.run, "stop");
494
+ await control(
495
+ { action: "stop", run: args.run },
496
+ { runtime, wait: { policy: "settle", waitMs: 0 } },
497
+ );
498
+ }),
499
+ gate: (args, api, context) => step(() => gateOfWorkflow(args, api, context)),
500
+ });
501
+
502
+ /**
503
+ * The service as one program, its layer built per call. This is the tool entry
504
+ * point: each execute builds a layer that captures only the lazy runtime getter,
505
+ * and nothing above this function can provide it.
506
+ */
507
+ const call = <A>(
508
+ deps: WorkflowDeps,
509
+ use: (service: WorkflowServiceShape) => Effect.Effect<A, WorkflowError>,
510
+ ): Effect.Effect<A, WorkflowError> =>
511
+ Effect.gen(function* () {
512
+ const service = yield* WorkflowService;
513
+ return yield* use(service);
514
+ // oxlint-disable-next-line effecttsgo/strict-effect-provide -- entry point
515
+ }).pipe(Effect.provide(WorkflowService.layer(deps)));
516
+
517
+ /** A refusal is a value the script can branch on; a mistake throws, so code mode raises. */
518
+ const refusalResult = (error: unknown): ToolExecutionResult => {
519
+ if (isRefusal(error)) {
520
+ return { output: [{ type: "text", text: error.message }], isError: true };
521
+ }
522
+ throw error;
523
+ };
524
+
525
+ /** Runs one command; a refusal comes back as a tool result, anything else throws. */
526
+ const settleOutcome = async <A>(
527
+ effect: Effect.Effect<A, WorkflowError>,
528
+ ): Promise<
529
+ | { readonly ok: true; readonly value: A }
530
+ | { readonly ok: false; readonly failure: ToolExecutionResult }
531
+ > => {
532
+ try {
533
+ return { ok: true, value: await Effect.runPromise(effect) };
534
+ } catch (error) {
535
+ return { ok: false, failure: refusalResult(error) };
536
+ }
537
+ };
538
+
539
+ /** Bounded outputs are local values, but the tool seam requires JSON: encode, never cast. */
540
+ const jsonOf = (value: unknown): JsonValue => Schema.encodeUnknownSync(Schema.MutableJson)(value);
541
+
542
+ const settle = async <A>(
543
+ effect: Effect.Effect<A, WorkflowError>,
544
+ present: (value: A) => unknown,
545
+ ): Promise<ToolExecutionResult> => {
546
+ const settled = await settleOutcome(effect);
547
+ if (!settled.ok) return settled.failure;
548
+ return { structuredOutput: jsonOf(present(settled.value)) };
549
+ };
550
+
551
+ /** A command with no structured value: answer with text, and a refusal as an error result. */
552
+ const settleText = async (
553
+ effect: Effect.Effect<void, WorkflowError>,
554
+ text: string,
555
+ ): Promise<ToolExecutionResult> => {
556
+ const settled = await settleOutcome(effect);
557
+ return settled.ok ? { output: [{ type: "text", text }] } : settled.failure;
558
+ };
559
+
560
+ const runTool = <T, J = unknown>(options: {
561
+ readonly name: (typeof RUN_TOOL_NAMES)[number];
562
+ readonly description: string;
563
+ readonly parameters: DeclaredSchema<T>;
564
+ readonly output?: DeclaredSchema<J>;
565
+ readonly execute: (
566
+ args: T,
567
+ api: ToolExecutionApi,
568
+ context: Context,
569
+ ) => Promise<ToolExecutionResult | ToolPark>;
570
+ }): ToolRegistration =>
571
+ defineTool({
572
+ name: options.name,
573
+ description: options.description,
574
+ parameters: options.parameters.json,
575
+ callers: ["tools"],
576
+ replay: "safe",
577
+ ...(options.output === undefined ? {} : { structuredOutputSchema: options.output.json }),
578
+ execute: async (raw, api, context) =>
579
+ options.execute(decode(options.parameters.schema, raw), api, context),
580
+ });
581
+
582
+ /** The eight script tools over the service. */
583
+ export const runTools = (runtime: () => SessionRuntime): readonly ToolRegistration[] => {
584
+ const deps: WorkflowDeps = { runtime };
585
+ return [
586
+ runTool({
587
+ name: "launch",
588
+ description:
589
+ "Start one child run in the workflow's lane, wait for it, and return its run id, " +
590
+ "answer and status.",
591
+ parameters: declared(LaunchArgs),
592
+ output: declared(ChildOutcome),
593
+ execute: (args, api, context) =>
594
+ settle(
595
+ call(deps, (service) => service.launch(args, api, context)),
596
+ (value) => value,
597
+ ),
598
+ }),
599
+ runTool({
600
+ name: "launch_many",
601
+ description:
602
+ "Start a group of child runs in one lane, wait for all of them, and return one " +
603
+ "run id, answer and status per child.",
604
+ parameters: declared(ManyArgs),
605
+ output: declared(ChildOutcomes),
606
+ execute: (args, api, context) =>
607
+ settle(
608
+ call(deps, (service) => service.launchMany(args, api, context)),
609
+ (value) => value,
610
+ ),
611
+ }),
612
+ runTool({
613
+ name: "lane",
614
+ description: "Read one lane's running, queued and answered counts.",
615
+ parameters: declared(LaneArgs),
616
+ output: declared(LaneView),
617
+ execute: (args) =>
618
+ settle(
619
+ call(deps, (service) => service.lane(args)),
620
+ (value) => value,
621
+ ),
622
+ }),
623
+ runTool({
624
+ name: "status",
625
+ description:
626
+ "Read every run of this session, or one run, as run id, definition, lane and status.",
627
+ parameters: declared(StatusArgs),
628
+ output: declared(StatusProjection),
629
+ execute: (args) =>
630
+ settle(
631
+ call(deps, (service) => service.status(args)),
632
+ (value) => value,
633
+ ),
634
+ }),
635
+ runTool({
636
+ name: "ref",
637
+ description: "Read one run's id, child conversation and gate run.",
638
+ parameters: declared(RefArgs),
639
+ output: declared(RunRef),
640
+ execute: (args) =>
641
+ settle(
642
+ call(deps, (service) => service.ref(args)),
643
+ (value) => value,
644
+ ),
645
+ }),
646
+ runTool({
647
+ name: "steer",
648
+ description: "Send a message to a running child of this workflow.",
649
+ parameters: declared(SteerArgs),
650
+ execute: (args, api, context) =>
651
+ settleText(
652
+ call(deps, (service) => service.steer(args, api, context)),
653
+ `steered ${args.run}`,
654
+ ),
655
+ }),
656
+ runTool({
657
+ name: "stop",
658
+ description: "Stop a child of this workflow.",
659
+ parameters: declared(StopArgs),
660
+ execute: (args, api, context) =>
661
+ settleText(
662
+ call(deps, (service) => service.stop(args, api, context)),
663
+ `stopped ${args.run}`,
664
+ ),
665
+ }),
666
+ runTool({
667
+ name: "gate",
668
+ description: "Ask a person to approve or deny a named gate, then return the decision.",
669
+ parameters: declared(GateArgs),
670
+ output: declared(GateDecisionOut),
671
+ execute: async (args, api, context) => {
672
+ const settled = await settleOutcome(
673
+ call(deps, (service) => service.gate(args, api, context)),
674
+ );
675
+ if (!settled.ok) return settled.failure;
676
+ const outcome = settled.value;
677
+ if (outcome.kind === "pending") {
678
+ return {
679
+ sleep: { signals: [GateDecision.key(outcome.key)], until: outcome.until },
680
+ };
681
+ }
682
+ return { structuredOutput: { decision: outcome.decision } };
683
+ },
684
+ }),
685
+ ];
686
+ };
687
+
688
+ /** The `runs` extension: the namespace, the script section and, in a session runtime, the tools. */
689
+ export const createRunsExtension = (runtime?: () => SessionRuntime): Extension =>
690
+ defineExtension({
691
+ name: RUNS_EXTENSION,
692
+ namespace: {
693
+ name: RUNS_EXTENSION,
694
+ description: "Start and control delegation runs from a workflow script.",
695
+ instructions:
696
+ "Every call starts or reads a run. `launch` starts one child and waits for it; " +
697
+ "`launch_many` starts a group. Prefer `launch_many` for parallel children: " +
698
+ "the lane cap admits a group, not a single launch.",
699
+ },
700
+ ...(runtime === undefined ? {} : { tools: runTools(runtime) }),
701
+ sections: [workflowSection()],
702
+ });
703
+
704
+ export { refusingSandbox, RefusingSandbox, WORKFLOW_SECTION_KEY } from "./workflow-section.ts";
705
+ export { diagnosticSandbox } from "./workflow-section.ts";