@ftrdotdev/pi-delegates 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/OPERATIONS.md +79 -6
  3. package/README.md +25 -17
  4. package/ROADMAP.md +21 -0
  5. package/TESTING.md +153 -318
  6. package/package.json +4 -3
  7. package/skills/pi-delegates/SKILL.md +29 -0
  8. package/skills/pi-delegates/references/launch.md +28 -0
  9. package/src/docs-contract.test.ts +106 -0
  10. package/src/domain/definitions.ts +3 -1
  11. package/src/domain/failure.ts +33 -0
  12. package/src/domain/model-source.ts +30 -0
  13. package/src/domain/orchestration/control.test.ts +69 -35
  14. package/src/domain/orchestration/control.ts +110 -89
  15. package/src/domain/orchestration/fanout.test.ts +125 -20
  16. package/src/domain/orchestration/fanout.ts +60 -22
  17. package/src/domain/orchestration/gates.test.ts +14 -15
  18. package/src/domain/orchestration/launch.test.ts +210 -11
  19. package/src/domain/orchestration/launch.ts +142 -32
  20. package/src/domain/orchestration/requests.test.ts +11 -16
  21. package/src/domain/orchestration/requests.ts +14 -1
  22. package/src/domain/orchestration/review.test.ts +89 -11
  23. package/src/domain/orchestration/run-wait.test.ts +4 -1
  24. package/src/domain/orchestration/run-wait.ts +1 -1
  25. package/src/domain/orchestration/workflow.test.ts +157 -16
  26. package/src/domain/orchestration/workflow.ts +269 -196
  27. package/src/domain/run-records.ts +214 -52
  28. package/src/domain/settlement.test.ts +186 -0
  29. package/src/domain/settlement.ts +137 -0
  30. package/src/domain/shapes.test.ts +20 -0
  31. package/src/domain/skills.test.ts +31 -20
  32. package/src/domain/skills.ts +36 -19
  33. package/src/domain/toolkit.test.ts +15 -1
  34. package/src/domain/toolkit.ts +8 -13
  35. package/src/domain/turn-budget.test.ts +37 -0
  36. package/src/domain/turn-budget.ts +23 -0
  37. package/src/domain/view.test.ts +78 -14
  38. package/src/domain/view.ts +67 -35
  39. package/src/extension/commands.test.ts +27 -23
  40. package/src/extension/commands.ts +10 -7
  41. package/src/extension/entry.test.ts +214 -56
  42. package/src/extension/entry.ts +78 -40
  43. package/src/extension/gate-alerts.test.ts +10 -8
  44. package/src/extension/inspector-command.test.ts +173 -21
  45. package/src/extension/inspector-command.ts +100 -53
  46. package/src/extension/prompt.test.ts +2 -4
  47. package/src/extension/retry-observer.test.ts +292 -0
  48. package/src/extension/retry-observer.ts +150 -0
  49. package/src/extension/settle-alerts.test.ts +579 -0
  50. package/src/extension/settle-alerts.ts +175 -0
  51. package/src/extension/shortcut.test.ts +6 -8
  52. package/src/extension/tools.test.ts +325 -24
  53. package/src/extension/tools.ts +61 -13
  54. package/src/extension/version.test.ts +21 -29
  55. package/src/goldens.test.ts +294 -0
  56. package/src/harness-policy.test.ts +13 -11
  57. package/src/layers.test.ts +309 -0
  58. package/src/layers.ts +405 -0
  59. package/src/package-manifest.test.ts +32 -19
  60. package/src/presentation/actions.test.ts +8 -8
  61. package/src/presentation/activity.test.ts +7 -8
  62. package/src/presentation/close.test.ts +14 -16
  63. package/src/presentation/inspector.test.ts +14 -11
  64. package/src/presentation/inspector.ts +27 -25
  65. package/src/presentation/overlay.test.ts +1 -3
  66. package/src/presentation/repaint.test.ts +226 -190
  67. package/src/presentation/snapshot.test.ts +5 -0
  68. package/src/presentation/status.test.ts +43 -0
  69. package/src/presentation/status.ts +30 -0
  70. package/src/presentation/strip.test.ts +13 -6
  71. package/src/presentation/strip.ts +7 -14
  72. package/src/presentation/wording.test.ts +153 -3
  73. package/src/presentation/wording.ts +78 -6
  74. package/src/runtime/bridge.ts +38 -44
  75. package/src/runtime/{timers.test.ts → clock.test.ts} +1 -1
  76. package/src/runtime/clock.ts +31 -0
  77. package/src/runtime/config.test.ts +26 -7
  78. package/src/runtime/config.ts +6 -1
  79. package/src/runtime/execution-env.test.ts +6 -8
  80. package/src/runtime/extensions.test.ts +4 -4
  81. package/src/runtime/extensions.ts +23 -11
  82. package/src/runtime/handle.ts +54 -0
  83. package/src/runtime/log.test.ts +19 -7
  84. package/src/runtime/log.ts +23 -0
  85. package/src/runtime/mcp.test.ts +29 -32
  86. package/src/runtime/mcp.ts +70 -3
  87. package/src/runtime/runtime-state.test.ts +25 -0
  88. package/src/runtime/runtime-state.ts +36 -0
  89. package/src/runtime/session-tag.ts +11 -0
  90. package/src/runtime/session.test.ts +24 -31
  91. package/src/runtime/session.ts +99 -261
  92. package/src/runtime/storage.ts +29 -0
  93. package/src/test-hygiene.test.ts +97 -0
  94. package/src/runtime/timers.ts +0 -10
@@ -9,7 +9,9 @@ import {
9
9
  type ToolPark,
10
10
  type ToolRegistration,
11
11
  } from "@earendil-works/pi-durable";
12
- import { Context as EffectContext, Effect, Layer, Schema } from "effect";
12
+ import { Context as EffectContext, Effect, Layer, Ref, Result, Schema } from "effect";
13
+ import type { SessionHandle } from "../../runtime/handle.ts";
14
+ import { SessionRuntimeTag } from "../../runtime/session-tag.ts";
13
15
  import type { SessionRuntime } from "../../runtime/session.ts";
14
16
  import { requestId } from "../../runtime/bridge.ts";
15
17
  import { DefinitionNotFound, type AgentDefinition } from "../definitions.ts";
@@ -22,7 +24,15 @@ import { declared, decode, type DeclaredSchema } from "../tool-schema.ts";
22
24
  import { control, RunNotFound, RunNotResumable, RunNotRunning } from "./control.ts";
23
25
  import type { FanoutInput } from "./fanout.ts";
24
26
  import { DAY_MS, decisionOf, GateDecision, GateDoc, gateKey, requestGate } from "./gates.ts";
25
- import { HostModelMissing, claimSingle, planLaunch, WorkflowOnly } from "./launch.ts";
27
+ import {
28
+ awaitChildren,
29
+ HostModelMissing,
30
+ claimSingle,
31
+ planLaunch,
32
+ WorkflowOnly,
33
+ } from "./launch.ts";
34
+ import { resolveMaxTurns } from "../turn-budget.ts";
35
+ import { Execution } from "../failure.ts";
26
36
  import { workflowSection } from "./workflow-section.ts";
27
37
 
28
38
  /** One child of a workflow, as a script reads it: a failed child is a value, not an exception. */
@@ -66,11 +76,21 @@ const LaunchArgs = Schema.Struct({
66
76
  agent: Schema.String,
67
77
  task: Schema.String,
68
78
  lane: Schema.optional(Schema.String),
79
+ execution: Schema.optional(Execution),
80
+ maxTurns: Schema.optional(Schema.Finite),
69
81
  });
70
82
 
71
83
  const ManyArgs = Schema.Struct({
72
- children: Schema.Array(Schema.Struct({ agent: Schema.String, task: Schema.String })),
84
+ children: Schema.Array(
85
+ Schema.Struct({
86
+ agent: Schema.String,
87
+ task: Schema.String,
88
+ maxTurns: Schema.optional(Schema.Finite),
89
+ }),
90
+ ),
73
91
  lane: Schema.optional(Schema.String),
92
+ execution: Schema.optional(Execution),
93
+ maxTurns: Schema.optional(Schema.Finite),
74
94
  });
75
95
 
76
96
  const LaneArgs = Schema.Struct({ name: Schema.String });
@@ -113,55 +133,53 @@ const step = <A>(operation: () => Promise<A>): Effect.Effect<A, WorkflowError> =
113
133
  },
114
134
  });
115
135
 
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
136
  /**
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.
137
+ * The script surface as a service. The session graph builds it once per handle:
138
+ * it reads the runtime from context, so the methods hold no state of their own.
159
139
  */
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)));
140
+ export class WorkflowService extends EffectContext.Service<
141
+ WorkflowService,
142
+ {
143
+ launch(
144
+ args: typeof LaunchArgs.Type,
145
+ api: ToolExecutionApi,
146
+ context: Context,
147
+ ): Effect.Effect<ChildOutcome, WorkflowError>;
148
+ launchMany(
149
+ args: typeof ManyArgs.Type,
150
+ api: ToolExecutionApi,
151
+ context: Context,
152
+ ): Effect.Effect<typeof ChildOutcomes.Type, WorkflowError>;
153
+ lane(args: typeof LaneArgs.Type): Effect.Effect<LaneView, WorkflowError>;
154
+ status(
155
+ args: typeof StatusArgs.Type,
156
+ ): Effect.Effect<typeof StatusProjection.Type, WorkflowError>;
157
+ ref(args: typeof RefArgs.Type): Effect.Effect<typeof RunRef.Type, WorkflowError>;
158
+ steer(
159
+ args: typeof SteerArgs.Type,
160
+ api: ToolExecutionApi,
161
+ context: Context,
162
+ ): Effect.Effect<void, WorkflowError>;
163
+ stop(
164
+ args: typeof StopArgs.Type,
165
+ api: ToolExecutionApi,
166
+ context: Context,
167
+ ): Effect.Effect<void, WorkflowError>;
168
+ /**
169
+ * Commits a pending gate and hands it back: the tool parks on it and answers the
170
+ * decision, so the service never waits. A gate of another workflow is refused.
171
+ */
172
+ gate(
173
+ args: typeof GateArgs.Type,
174
+ api: ToolExecutionApi,
175
+ context: Context,
176
+ ): Effect.Effect<GateOutcome, WorkflowError>;
177
+ }
178
+ >()("@ftrdotdev/pi-delegates/domain/orchestration/workflow/WorkflowService") {
179
+ static layer = Layer.effect(
180
+ WorkflowService,
181
+ Effect.map(SessionRuntimeTag, (runtime) => WorkflowService.of(workflowMethods(runtime))),
182
+ );
165
183
  }
166
184
 
167
185
  type WorkflowToolkit = {
@@ -221,6 +239,23 @@ const planChild = async (
221
239
  return plan;
222
240
  };
223
241
 
242
+ /** One child's budget: child level, request level, definition, then the config default. */
243
+ const budgetFor = (
244
+ runtime: SessionRuntime,
245
+ input: {
246
+ readonly child?: number | undefined;
247
+ readonly request?: number | undefined;
248
+ readonly definition: AgentDefinition;
249
+ },
250
+ ): number =>
251
+ resolveMaxTurns({
252
+ ...(input.child === undefined ? {} : { child: input.child }),
253
+ ...(input.request === undefined ? {} : { request: input.request }),
254
+ ...(input.definition.maxTurns === undefined ? {} : { definition: input.definition.maxTurns }),
255
+ configDefault: runtime.config.maxTurns,
256
+ ceiling: runtime.config.maxTurnsCeiling,
257
+ });
258
+
224
259
  const childOutcome = async (runtime: SessionRuntime, runId: string): Promise<ChildOutcome> => {
225
260
  const view = await viewRun(runId, runtime);
226
261
  return { run: runId, answer: view.answer ?? "", status: view.status };
@@ -239,12 +274,11 @@ const ownerConversation = async (api: ToolExecutionApi, runTaskId: number, conte
239
274
  };
240
275
 
241
276
  const launchChild = async (
242
- deps: WorkflowDeps,
277
+ runtime: SessionRuntime,
243
278
  args: typeof LaunchArgs.Type,
244
279
  api: ToolExecutionApi,
245
280
  context: Context,
246
281
  ): Promise<ChildOutcome> => {
247
- const runtime = deps.runtime();
248
282
  const toolkit = await toolkitOf(api, context);
249
283
  const parent = await workflowDocOf(runtime, toolkit.runId);
250
284
  const plan = await planChild(runtime, api, args.agent, args.task);
@@ -256,6 +290,11 @@ const launchChild = async (
256
290
  task: args.task,
257
291
  workflow: toolkit.runId,
258
292
  call: api.callId,
293
+ ...(args.execution === "detached" ? { execution: "detached" as const } : {}),
294
+ });
295
+ const maxTurns = budgetFor(runtime, {
296
+ request: args.maxTurns,
297
+ definition: plan.definition,
259
298
  });
260
299
 
261
300
  const claimed = await claimSingle((change) => api.commit(change, context), {
@@ -266,12 +305,13 @@ const launchChild = async (
266
305
  task: args.task,
267
306
  host: runtime.host(),
268
307
  lane,
269
- maxTurns: runtime.config.maxTurns,
308
+ maxTurns,
270
309
  },
271
310
  requestedAgent: args.agent,
272
311
  conversationId: owner,
273
312
  ownership: { kind: "task", taskId: toTaskId(toolkit.runTaskId) },
274
313
  mode: "single",
314
+ ...(args.execution === undefined ? {} : { execution: args.execution }),
275
315
  parent: {
276
316
  runId: toolkit.runId,
277
317
  definition: parent.definition,
@@ -281,6 +321,11 @@ const launchChild = async (
281
321
  index: true,
282
322
  });
283
323
 
324
+ // A detached launch answers the run id, the opening status and an empty answer; the
325
+ // notice reports the end. Reading the task here would race the child's own start.
326
+ if (args.execution === "detached") {
327
+ return { run: claimed.runId, answer: "", status: "queued" };
328
+ }
284
329
  await api.waitForTask(toTaskId(claimed.taskId), context);
285
330
  return childOutcome(runtime, claimed.runId);
286
331
  };
@@ -288,26 +333,40 @@ const launchChild = async (
288
333
  type ClaimedChild = LaunchClaim & { readonly createdTaskId?: number };
289
334
 
290
335
  const launchGroup = async (
291
- deps: WorkflowDeps,
336
+ runtime: SessionRuntime,
292
337
  args: typeof ManyArgs.Type,
293
338
  api: ToolExecutionApi,
294
339
  context: Context,
295
340
  ): Promise<{ readonly childRunIds: readonly string[] }> => {
296
- const runtime = deps.runtime();
297
341
  const toolkit = await toolkitOf(api, context);
298
342
  const parent = await workflowDocOf(runtime, toolkit.runId);
299
343
  const lane = args.lane ?? parent.lane;
300
344
  const owner = await ownerConversation(api, toolkit.runTaskId, context);
301
- const children: { agent: string; task: string; definition: AgentDefinition }[] = [];
345
+ const children: {
346
+ agent: string;
347
+ task: string;
348
+ definition: AgentDefinition;
349
+ maxTurns: number;
350
+ }[] = [];
302
351
  for (const child of args.children) {
303
352
  const plan = await planChild(runtime, api, child.agent, child.task);
304
- children.push({ agent: child.agent, task: child.task, definition: plan.definition });
353
+ children.push({
354
+ agent: child.agent,
355
+ task: child.task,
356
+ definition: plan.definition,
357
+ maxTurns: budgetFor(runtime, {
358
+ ...(child.maxTurns === undefined ? {} : { child: child.maxTurns }),
359
+ request: args.maxTurns,
360
+ definition: plan.definition,
361
+ }),
362
+ });
305
363
  }
306
364
  const identity = requestId(runtime.sessionId, {
307
365
  kind: "fanout",
308
366
  workflow: toolkit.runId,
309
367
  call: api.callId,
310
368
  agents: args.children,
369
+ ...(args.execution === "detached" ? { execution: "detached" as const } : {}),
311
370
  });
312
371
 
313
372
  const claimed: ClaimedChild = await api.commit(async (tx) => {
@@ -315,6 +374,7 @@ const launchGroup = async (
315
374
  definition: "fanout",
316
375
  lane,
317
376
  mode: "fanout" as const,
377
+ ...(args.execution === undefined ? {} : { execution: args.execution }),
318
378
  parentRunId: toolkit.runId,
319
379
  };
320
380
  const claim = await claimLaunch(tx, {
@@ -331,6 +391,7 @@ const launchGroup = async (
331
391
  children,
332
392
  host: runtime.host(),
333
393
  maxTurns: runtime.config.maxTurns,
394
+ ...(args.execution === undefined ? {} : { execution: args.execution }),
334
395
  policy: "allSettled",
335
396
  review: false,
336
397
  parentRunId: toolkit.runId,
@@ -355,7 +416,12 @@ const launchGroup = async (
355
416
 
356
417
  const taskId = claimed.reuseTaskId ?? claimed.createdTaskId;
357
418
  if (taskId === undefined) throw new Error("The workflow group task was not created.");
358
- await api.waitForTask(toTaskId(taskId), context);
419
+ // A detached group answers its children's run ids: the notice reports their ends.
420
+ if (args.execution === "detached") {
421
+ await awaitChildren(runtime, claimed.runId, children.length);
422
+ } else {
423
+ await api.waitForTask(toTaskId(taskId), context);
424
+ }
359
425
  const group = await workflowDocOf(runtime, claimed.runId);
360
426
  const childRunIds = [...group.childRunIds];
361
427
  // The workflow nests the group's children: one list the stop path and the view read.
@@ -461,11 +527,20 @@ const gateOfWorkflow = async (
461
527
  return { kind: "decided", decision: decisionOf(record) };
462
528
  };
463
529
 
464
- const workflowMethods = (deps: WorkflowDeps): WorkflowServiceShape => ({
465
- launch: (args, api, context) => step(() => launchChild(deps, args, api, context)),
530
+ const workflowMethods = (runtime: SessionRuntime): WorkflowService["Service"] => ({
531
+ launch: (args, api, context) => step(() => launchChild(runtime, args, api, context)),
466
532
  launchMany: Effect.fnUntraced(function* (args, api, context) {
467
- const started = yield* step(() => launchGroup(deps, args, api, context));
468
- const runtime = deps.runtime();
533
+ const started = yield* step(() => launchGroup(runtime, args, api, context));
534
+ // A detached group answers one opening entry per child without reading a task.
535
+ if (args.execution === "detached") {
536
+ return {
537
+ runs: started.childRunIds.map((runId) => ({
538
+ run: runId,
539
+ answer: "",
540
+ status: "queued" as const,
541
+ })),
542
+ };
543
+ }
469
544
  const runs = yield* Effect.forEach(
470
545
  started.childRunIds,
471
546
  (runId) => step(() => childOutcome(runtime, runId)),
@@ -473,12 +548,11 @@ const workflowMethods = (deps: WorkflowDeps): WorkflowServiceShape => ({
473
548
  );
474
549
  return { runs };
475
550
  }),
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)),
551
+ lane: (args) => step(() => laneView(runtime, args.name)),
552
+ status: (args) => step(() => statusProjection(runtime, args.run)),
553
+ ref: (args) => step(() => runRef(runtime, args.run)),
479
554
  steer: (args, api, context) =>
480
555
  step(async () => {
481
- const runtime = deps.runtime();
482
556
  const toolkit = await toolkitOf(api, context);
483
557
  refuseOwnRun(toolkit, args.run, "steer");
484
558
  await control(
@@ -488,7 +562,6 @@ const workflowMethods = (deps: WorkflowDeps): WorkflowServiceShape => ({
488
562
  }),
489
563
  stop: (args, api, context) =>
490
564
  step(async () => {
491
- const runtime = deps.runtime();
492
565
  const toolkit = await toolkitOf(api, context);
493
566
  refuseOwnRun(toolkit, args.run, "stop");
494
567
  await control(
@@ -500,19 +573,21 @@ const workflowMethods = (deps: WorkflowDeps): WorkflowServiceShape => ({
500
573
  });
501
574
 
502
575
  /**
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.
576
+ * The service as one program inside the live handle's graph. This is the tool
577
+ * entry point: the graph already built the layer, so a call only yields it.
506
578
  */
507
579
  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)));
580
+ current: Ref.Ref<SessionHandle | undefined>,
581
+ use: (service: WorkflowService["Service"]) => Effect.Effect<A, WorkflowError>,
582
+ ): Effect.Effect<A, WorkflowError> => {
583
+ // The same failure as before: a synchronous throw with the identical message,
584
+ // so the tool payload stays byte-identical.
585
+ const handle = Ref.getUnsafe(current);
586
+ if (handle === undefined) {
587
+ throw new Error("The delegation runtime is not ready; start a session first.");
588
+ }
589
+ return handle.run(Effect.flatMap(WorkflowService, use));
590
+ };
516
591
 
517
592
  /** A refusal is a value the script can branch on; a mistake throws, so code mode raises. */
518
593
  const refusalResult = (error: unknown): ToolExecutionResult => {
@@ -522,17 +597,14 @@ const refusalResult = (error: unknown): ToolExecutionResult => {
522
597
  throw error;
523
598
  };
524
599
 
525
- /** Runs one command; a refusal comes back as a tool result, anything else throws. */
526
- const settleOutcome = async <A>(
600
+ /** Runs one command; a refusal comes back as a failure result, anything else throws. */
601
+ export const settleOutcome = async <A>(
527
602
  effect: Effect.Effect<A, WorkflowError>,
528
- ): Promise<
529
- | { readonly ok: true; readonly value: A }
530
- | { readonly ok: false; readonly failure: ToolExecutionResult }
531
- > => {
603
+ ): Promise<Result.Result<A, ToolExecutionResult>> => {
532
604
  try {
533
- return { ok: true, value: await Effect.runPromise(effect) };
605
+ return Result.succeed(await Effect.runPromise(effect));
534
606
  } catch (error) {
535
- return { ok: false, failure: refusalResult(error) };
607
+ return Result.fail(refusalResult(error));
536
608
  }
537
609
  };
538
610
 
@@ -544,8 +616,8 @@ const settle = async <A>(
544
616
  present: (value: A) => unknown,
545
617
  ): Promise<ToolExecutionResult> => {
546
618
  const settled = await settleOutcome(effect);
547
- if (!settled.ok) return settled.failure;
548
- return { structuredOutput: jsonOf(present(settled.value)) };
619
+ if (Result.isFailure(settled)) return settled.failure;
620
+ return { structuredOutput: jsonOf(present(settled.success)) };
549
621
  };
550
622
 
551
623
  /** A command with no structured value: answer with text, and a refusal as an error result. */
@@ -554,7 +626,7 @@ const settleText = async (
554
626
  text: string,
555
627
  ): Promise<ToolExecutionResult> => {
556
628
  const settled = await settleOutcome(effect);
557
- return settled.ok ? { output: [{ type: "text", text }] } : settled.failure;
629
+ return Result.isSuccess(settled) ? { output: [{ type: "text", text }] } : settled.failure;
558
630
  };
559
631
 
560
632
  const runTool = <T, J = unknown>(options: {
@@ -579,114 +651,115 @@ const runTool = <T, J = unknown>(options: {
579
651
  options.execute(decode(options.parameters.schema, raw), api, context),
580
652
  });
581
653
 
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
- };
654
+ /** The eight script tools over the service, each call entering the live handle. */
655
+ export const runTools = (
656
+ current: Ref.Ref<SessionHandle | undefined>,
657
+ ): readonly ToolRegistration[] => [
658
+ runTool({
659
+ name: "launch",
660
+ description:
661
+ "Start one child run in the workflow's lane, wait for it, and return its run id, " +
662
+ 'answer and status. With execution: "detached" it answers the run id, the empty ' +
663
+ "string and the opening status without waiting.",
664
+ parameters: declared(LaunchArgs),
665
+ output: declared(ChildOutcome),
666
+ execute: (args, api, context) =>
667
+ settle(
668
+ call(current, (service) => service.launch(args, api, context)),
669
+ (value) => value,
670
+ ),
671
+ }),
672
+ runTool({
673
+ name: "launch_many",
674
+ description:
675
+ "Start a group of child runs in one lane, wait for all of them, and return one " +
676
+ 'run id, answer and status per child. With execution: "detached" each child answers ' +
677
+ "the empty string and the opening status.",
678
+ parameters: declared(ManyArgs),
679
+ output: declared(ChildOutcomes),
680
+ execute: (args, api, context) =>
681
+ settle(
682
+ call(current, (service) => service.launchMany(args, api, context)),
683
+ (value) => value,
684
+ ),
685
+ }),
686
+ runTool({
687
+ name: "lane",
688
+ description: "Read one lane's running, queued and answered counts.",
689
+ parameters: declared(LaneArgs),
690
+ output: declared(LaneView),
691
+ execute: (args) =>
692
+ settle(
693
+ call(current, (service) => service.lane(args)),
694
+ (value) => value,
695
+ ),
696
+ }),
697
+ runTool({
698
+ name: "status",
699
+ description:
700
+ "Read every run of this session, or one run, as run id, definition, lane and status.",
701
+ parameters: declared(StatusArgs),
702
+ output: declared(StatusProjection),
703
+ execute: (args) =>
704
+ settle(
705
+ call(current, (service) => service.status(args)),
706
+ (value) => value,
707
+ ),
708
+ }),
709
+ runTool({
710
+ name: "ref",
711
+ description: "Read one run's id, child conversation and gate run.",
712
+ parameters: declared(RefArgs),
713
+ output: declared(RunRef),
714
+ execute: (args) =>
715
+ settle(
716
+ call(current, (service) => service.ref(args)),
717
+ (value) => value,
718
+ ),
719
+ }),
720
+ runTool({
721
+ name: "steer",
722
+ description: "Send a message to a running child of this workflow.",
723
+ parameters: declared(SteerArgs),
724
+ execute: (args, api, context) =>
725
+ settleText(
726
+ call(current, (service) => service.steer(args, api, context)),
727
+ `steered ${args.run}`,
728
+ ),
729
+ }),
730
+ runTool({
731
+ name: "stop",
732
+ description: "Stop a child of this workflow.",
733
+ parameters: declared(StopArgs),
734
+ execute: (args, api, context) =>
735
+ settleText(
736
+ call(current, (service) => service.stop(args, api, context)),
737
+ `stopped ${args.run}`,
738
+ ),
739
+ }),
740
+ runTool({
741
+ name: "gate",
742
+ description: "Ask a person to approve or deny a named gate, then return the decision.",
743
+ parameters: declared(GateArgs),
744
+ output: declared(GateDecisionOut),
745
+ execute: async (args, api, context) => {
746
+ const settled = await settleOutcome(
747
+ call(current, (service) => service.gate(args, api, context)),
748
+ );
749
+ if (Result.isFailure(settled)) return settled.failure;
750
+ const outcome = settled.success;
751
+ if (outcome.kind === "pending") {
752
+ return {
753
+ sleep: { signals: [GateDecision.key(outcome.key)], until: outcome.until },
754
+ };
755
+ }
756
+ return { structuredOutput: { decision: outcome.decision } };
757
+ },
758
+ }),
759
+ ];
687
760
 
688
761
  /** The `runs` extension: the namespace, the script section and, in a session runtime, the tools. */
689
- export const createRunsExtension = (runtime?: () => SessionRuntime): Extension =>
762
+ export const createRunsExtension = (session?: Ref.Ref<SessionHandle | undefined>): Extension =>
690
763
  defineExtension({
691
764
  name: RUNS_EXTENSION,
692
765
  namespace: {
@@ -697,7 +770,7 @@ export const createRunsExtension = (runtime?: () => SessionRuntime): Extension =
697
770
  "`launch_many` starts a group. Prefer `launch_many` for parallel children: " +
698
771
  "the lane cap admits a group, not a single launch.",
699
772
  },
700
- ...(runtime === undefined ? {} : { tools: runTools(runtime) }),
773
+ ...(session === undefined ? {} : { tools: runTools(session) }),
701
774
  sections: [workflowSection()],
702
775
  });
703
776