@noetic-tools/core 5.20.0 → 5.22.0-next.1

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 (84) hide show
  1. package/dist/builders/tool-builder.d.ts +20 -0
  2. package/dist/builders/tool-builder.js +23 -1
  3. package/dist/builders/workflow-hydrator.d.ts +19 -0
  4. package/dist/builders/workflow-hydrator.js +19 -0
  5. package/dist/builders/workflow-step.js +7 -1
  6. package/dist/connections/cron-schedule.js +12 -3
  7. package/dist/connections/durability.d.ts +1 -2
  8. package/dist/connections/durability.js +1 -4
  9. package/dist/connections/gates.js +6 -2
  10. package/dist/connections/harness-wiring.d.ts +5 -0
  11. package/dist/connections/harness-wiring.js +76 -10
  12. package/dist/connections/in-memory-connection.d.ts +4 -0
  13. package/dist/connections/in-memory-connection.js +10 -0
  14. package/dist/connections/model-tools.js +5 -1
  15. package/dist/connections/registry.d.ts +6 -2
  16. package/dist/connections/registry.js +10 -0
  17. package/dist/connections/sources.js +261 -20
  18. package/dist/connections/triggers.d.ts +62 -2
  19. package/dist/connections/triggers.js +375 -35
  20. package/dist/harness/agent-harness.d.ts +263 -4
  21. package/dist/harness/agent-harness.js +1156 -95
  22. package/dist/harness/connection-gate.d.ts +3 -0
  23. package/dist/harness/connection-gate.js +4 -0
  24. package/dist/harness/deps/runtime.d.ts +3 -0
  25. package/dist/harness/deps/runtime.js +2 -0
  26. package/dist/harness/flow-version.d.ts +13 -0
  27. package/dist/harness/flow-version.js +66 -0
  28. package/dist/harness/harness-options.d.ts +82 -0
  29. package/dist/harness/model-call.d.ts +0 -1
  30. package/dist/harness/model-call.js +8 -48
  31. package/dist/harness/model-rounds.d.ts +30 -0
  32. package/dist/harness/model-rounds.js +146 -1
  33. package/dist/harness/model-tool-round.d.ts +3 -0
  34. package/dist/harness/model-tool-round.js +201 -19
  35. package/dist/harness/park-watchers.d.ts +93 -0
  36. package/dist/harness/park-watchers.js +217 -0
  37. package/dist/harness/read-decision.d.ts +23 -0
  38. package/dist/harness/read-decision.js +100 -0
  39. package/dist/harness/spend.js +4 -0
  40. package/dist/harness/steer-inbox.js +3 -1
  41. package/dist/harness/thread-record.d.ts +77 -1
  42. package/dist/harness/thread-record.js +272 -13
  43. package/dist/index.d.ts +17 -7
  44. package/dist/index.js +10 -2
  45. package/dist/interpreter/acp-resume.d.ts +77 -0
  46. package/dist/interpreter/acp-resume.js +164 -0
  47. package/dist/interpreter/acp-tools.d.ts +11 -0
  48. package/dist/interpreter/acp-tools.js +94 -7
  49. package/dist/interpreter/connection-steps.d.ts +24 -1
  50. package/dist/interpreter/connection-steps.js +77 -2
  51. package/dist/interpreter/execute-acp-agent.js +111 -15
  52. package/dist/interpreter/execute-action.js +7 -0
  53. package/dist/interpreter/execute-call.js +30 -4
  54. package/dist/interpreter/execute-control.js +21 -0
  55. package/dist/interpreter/execute-invoke-tool.js +149 -5
  56. package/dist/interpreter/execute-wait.js +67 -9
  57. package/dist/interpreter/execute.js +4 -0
  58. package/dist/interpreter/turn-ending.d.ts +15 -0
  59. package/dist/interpreter/turn-ending.js +46 -0
  60. package/dist/portable/builders.d.ts +1 -1
  61. package/dist/portable/builders.js +1 -1
  62. package/dist/runtime/durable/parking.d.ts +61 -0
  63. package/dist/runtime/durable/parking.js +137 -0
  64. package/dist/runtime/durable/session-store.d.ts +38 -0
  65. package/dist/runtime/durable/session-store.js +79 -1
  66. package/dist/runtime/durable/step-ledger.d.ts +121 -2
  67. package/dist/runtime/durable/step-ledger.js +352 -15
  68. package/dist/runtime/durable/turn-lease.d.ts +128 -0
  69. package/dist/runtime/durable/turn-lease.js +307 -0
  70. package/dist/runtime/held-calls.d.ts +192 -0
  71. package/dist/runtime/held-calls.js +496 -0
  72. package/dist/runtime/in-memory-storage.d.ts +10 -1
  73. package/dist/runtime/in-memory-storage.js +20 -2
  74. package/dist/runtime/message-queue.d.ts +2 -0
  75. package/dist/runtime/message-queue.js +8 -0
  76. package/dist/runtime/session-runner.d.ts +18 -2
  77. package/dist/runtime/session-runner.js +88 -3
  78. package/dist/runtime/tool-approval.d.ts +46 -6
  79. package/dist/runtime/tool-approval.js +160 -38
  80. package/dist/runtime/tool-call.d.ts +34 -2
  81. package/dist/runtime/tool-call.js +182 -13
  82. package/dist/runtime/tool-context.d.ts +15 -1
  83. package/dist/runtime/tool-context.js +38 -2
  84. package/package.json +3 -3
@@ -33,6 +33,14 @@ const PendingEntrySchema = z.object({
33
33
  leaseId: z.string().optional(),
34
34
  cursor: z.string().nullish(),
35
35
  deadline: z.number().optional(),
36
+ /** On a `wait`: the event it listens for, so a parked turn can be watched over. */
37
+ event: z.string().optional(),
38
+ /**
39
+ * Set on a `wait` whose event replays from a cursor (`replay: 'durable'`). Such
40
+ * a wait does not depend on the connection instance it began on: any instance of
41
+ * the same surface can listen again from the cursor (spec 35 § Durability).
42
+ */
43
+ durable: z.boolean().optional(),
36
44
  });
37
45
  function harnessOf(ctx) {
38
46
  return {
@@ -377,9 +385,13 @@ export function refuseWitnessAct(ctx, resolved, op) {
377
385
  export class PendingEntries {
378
386
  storage;
379
387
  key;
380
- constructor(storage, key) {
388
+ mayWrite;
389
+ constructor(storage, key,
390
+ /** False once the run writes under a lease it no longer holds. */
391
+ mayWrite = () => true) {
381
392
  this.storage = storage;
382
393
  this.key = key;
394
+ this.mayWrite = mayWrite;
383
395
  }
384
396
  /** The entry a previous attempt left, or undefined when there is none (or it does not parse). */
385
397
  async load() {
@@ -391,6 +403,9 @@ export class PendingEntries {
391
403
  return parsed.success ? parsed.data : undefined;
392
404
  }
393
405
  async write(entry) {
406
+ if (!this.mayWrite()) {
407
+ return;
408
+ }
394
409
  try {
395
410
  await this.storage.set(this.key, entry);
396
411
  }
@@ -399,6 +414,9 @@ export class PendingEntries {
399
414
  }
400
415
  }
401
416
  async clear() {
417
+ if (!this.mayWrite()) {
418
+ return;
419
+ }
402
420
  try {
403
421
  await this.storage.delete(this.key);
404
422
  }
@@ -407,6 +425,44 @@ export class PendingEntries {
407
425
  }
408
426
  }
409
427
  }
428
+ /**
429
+ * The events an execution's waits listen for and can pick up again from a cursor:
430
+ * what a watcher needs to wake a parked turn (spec 23 § Parked turns).
431
+ */
432
+ export async function resumableWaitsOf(storage, executionId) {
433
+ const waits = [];
434
+ for (const key of await storage.list(`execution:${executionId}:pending:`)) {
435
+ const parsed = PendingEntrySchema.safeParse(await storage.get(key));
436
+ const resumable = parsed.success && parsed.data.kind === 'wait' && resumesFromCursor(parsed.data);
437
+ if (!parsed.success || !resumable || parsed.data.event === undefined) {
438
+ continue;
439
+ }
440
+ waits.push({
441
+ connection: parsed.data.connection,
442
+ event: parsed.data.event,
443
+ cursor: parsed.data.cursor ?? null,
444
+ });
445
+ }
446
+ return waits;
447
+ }
448
+ /**
449
+ * The long operations an execution's calls wait on: what a watcher polls to know
450
+ * when a parked turn can go on (spec 23 § Parked turns).
451
+ */
452
+ export async function pendingTasksOf(storage, executionId) {
453
+ const tasks = [];
454
+ for (const key of await storage.list(`execution:${executionId}:pending:`)) {
455
+ const parsed = PendingEntrySchema.safeParse(await storage.get(key));
456
+ if (!parsed.success || parsed.data.kind !== 'call' || parsed.data.taskId === undefined) {
457
+ continue;
458
+ }
459
+ tasks.push({
460
+ connection: parsed.data.connection,
461
+ taskId: parsed.data.taskId,
462
+ });
463
+ }
464
+ return tasks;
465
+ }
410
466
  /** The storage key of a step's pending entry. */
411
467
  export function pendingEntryKey(executionId, ledgerKey) {
412
468
  return `execution:${executionId}:pending:${ledgerKey}`;
@@ -426,7 +482,8 @@ function pendingEntriesFor(ctx, ledgerKey) {
426
482
  if (!storage || !durable || ledgerKey === undefined) {
427
483
  return undefined;
428
484
  }
429
- return new PendingEntries(storage, pendingEntryKey(runRootOf(ctx).id, ledgerKey));
485
+ const ledger = ctx.ledger;
486
+ return new PendingEntries(storage, pendingEntryKey(runRootOf(ctx).id, ledgerKey), () => ledger?.isHeld ?? true);
430
487
  }
431
488
  /**
432
489
  * Decides what a resumed step does with the pending entry a previous attempt
@@ -445,6 +502,9 @@ export async function reconcilePending(connection, signal, ctx) {
445
502
  return undefined;
446
503
  }
447
504
  const current = connection.resolved.identity();
505
+ if (resumesFromCursor(entry) && entry.identity.surface === current.surface) {
506
+ return entry;
507
+ }
448
508
  const executionId = connection.scope.executionId;
449
509
  const registry = ctx ? harnessOf(ctx).connectionRegistry : undefined;
450
510
  const decision = resumeDecision({
@@ -472,6 +532,17 @@ export async function reconcilePending(connection, signal, ctx) {
472
532
  await connection.pending?.clear();
473
533
  return undefined;
474
534
  }
535
+ /**
536
+ * True for a pending entry that any instance of its surface can pick up: a `wait`
537
+ * that replays from a cursor, or a `call` whose long operation has an id the server
538
+ * keeps. Neither depends on the connection instance it began on.
539
+ */
540
+ function resumesFromCursor(entry) {
541
+ if (entry.kind === 'call') {
542
+ return entry.taskId !== undefined;
543
+ }
544
+ return entry.durable === true;
545
+ }
475
546
  /** Records on the run's ledger that the step at `ledgerKey` used `resolved` (spec 35 § Durability). */
476
547
  function noteConnectionUse(ctx, ledgerKey, resolved) {
477
548
  if (!(ctx instanceof ContextImpl) || !ctx.ledger || ledgerKey === undefined) {
@@ -539,6 +610,10 @@ async function dropReplacedPending(executionId, storage, decide) {
539
610
  if (!parsed.success) {
540
611
  continue;
541
612
  }
613
+ // A wait that replays from a cursor is settled when its step runs again.
614
+ if (resumesFromCursor(parsed.data)) {
615
+ continue;
616
+ }
542
617
  const decision = await decide(parsed.data.connection, parsed.data.identity);
543
618
  if (decision !== 'keep') {
544
619
  await storage.delete(key);
@@ -12,6 +12,7 @@ import { runtimeOf } from '../connections/model-tools.js';
12
12
  import { AcpEventBridge } from './acp-events.js';
13
13
  import { withHistoryPrompt } from './acp-history.js';
14
14
  import { renderLayerContext } from './acp-layers.js';
15
+ import { ACP_RESUME_NOTICE, acpSessionRecords } from './acp-resume.js';
15
16
  import { AcpToolRunner, mergeBridgedItems, resolveAcpTools } from './acp-tools.js';
16
17
  import { appendUserInput, MAX_STEERING_RETRIES, resolveLazy } from './execute-action.js';
17
18
  import { trackUsage } from './message-helpers.js';
@@ -146,6 +147,36 @@ function buildSteerer(ctx, layers) {
146
147
  };
147
148
  };
148
149
  }
150
+ /**
151
+ * The last tier of a permission request: the harness's approval seam (spec 08
152
+ * § Held tool calls). The agent's process is waiting on the answer and its session
153
+ * would not survive the turn stopping, so the turn stays live while the request is
154
+ * held.
155
+ */
156
+ function buildApprover(ctx) {
157
+ const approve = ctx.harness.approve?.bind(ctx.harness);
158
+ if (!approve) {
159
+ return undefined;
160
+ }
161
+ return async (request) => {
162
+ const decision = await approve({
163
+ toolName: request.toolCall.title ?? request.toolCall.toolCallId,
164
+ toolArgs: request.toolCall.rawInput,
165
+ callId: request.toolCall.toolCallId,
166
+ ctx,
167
+ park: false,
168
+ });
169
+ if (decision.action === SteeringAction.Allow) {
170
+ return {
171
+ decision: 'allow',
172
+ };
173
+ }
174
+ return {
175
+ decision: 'deny',
176
+ reason: decision.guidance ?? `approval ${decision.action}`,
177
+ };
178
+ };
179
+ }
149
180
  /**
150
181
  * Point an existing host at the step that is about to take a turn.
151
182
  *
@@ -158,6 +189,7 @@ function buildSteerer(ctx, layers) {
158
189
  function bindHostToStep(host, opts) {
159
190
  host.permissions = opts.step.permissions;
160
191
  host.steerPermission = buildSteerer(opts.ctx, opts.layers);
192
+ host.approvePermission = buildApprover(opts.ctx);
161
193
  // Bind the executing context into the handler so the protocol client never
162
194
  // has to know about `Context` — it just asks a question and gets an answer.
163
195
  const handler = opts.step.onPermissionRequest;
@@ -293,7 +325,45 @@ function assertReuseIsKeptAlive(step) {
293
325
  hint: "Add `keepAlive: 'run'` to share the connection for the rest of the run, or `keepAlive: 'harness'` to keep it past the run and close it yourself with `harness.closeAcpSessions()`.",
294
326
  });
295
327
  }
328
+ /**
329
+ * Open the step's session on a new connection. An earlier attempt's session is
330
+ * reloaded when the agent can; an agent that cannot, or that no longer has the
331
+ * session, gets a new one, and the step starts it over.
332
+ */
333
+ async function sessionOn(connection, opts) {
334
+ const { cwd, loadId, resumeId } = opts;
335
+ if (loadId) {
336
+ return {
337
+ session: await connection.loadSession({
338
+ sessionId: loadId,
339
+ cwd,
340
+ }),
341
+ resumed: false,
342
+ };
343
+ }
344
+ if (resumeId !== undefined && connection.agentCapabilities.loadSession === true) {
345
+ const session = await connection
346
+ .loadSession({
347
+ sessionId: resumeId,
348
+ cwd,
349
+ })
350
+ .catch(() => undefined);
351
+ if (session) {
352
+ return {
353
+ session,
354
+ resumed: true,
355
+ };
356
+ }
357
+ }
358
+ return {
359
+ session: await connection.newSession({
360
+ cwd,
361
+ }),
362
+ resumed: false,
363
+ };
364
+ }
296
365
  async function openSession(opts) {
366
+ let resumed = false;
297
367
  const store = sessionStore(opts.baseCtx);
298
368
  const keepAlive = keepAliveOf(opts.step.session);
299
369
  const reuseKey = opts.step.session?.reuse;
@@ -315,15 +385,13 @@ async function openSession(opts) {
315
385
  // must close it first — otherwise the agent outlives the step and, because
316
386
  // its stdio keeps the event loop alive, the host never exits.
317
387
  try {
318
- const loadId = opts.step.session?.load;
319
- const session = loadId
320
- ? await connection.loadSession({
321
- sessionId: loadId,
322
- cwd: opts.cwd,
323
- })
324
- : await connection.newSession({
325
- cwd: opts.cwd,
326
- });
388
+ const opened = await sessionOn(connection, {
389
+ cwd: opts.cwd,
390
+ loadId: opts.step.session?.load,
391
+ resumeId: opts.resumeId,
392
+ });
393
+ resumed = opened.resumed;
394
+ const { session } = opened;
327
395
  return {
328
396
  connection,
329
397
  session,
@@ -357,6 +425,7 @@ async function openSession(opts) {
357
425
  key,
358
426
  keepAlive,
359
427
  fresh,
428
+ resumed,
360
429
  };
361
430
  }
362
431
  /**
@@ -575,6 +644,13 @@ export async function executeAcpAgent(step, input, ctx, layers) {
575
644
  layers,
576
645
  input: promptText,
577
646
  });
647
+ // An earlier attempt of this step may have left its session behind.
648
+ const sessions = step.session?.load ? undefined : acpSessionRecords(baseCtx);
649
+ const recorded = await sessions?.load();
650
+ const resumeId = recorded?.agentId === agent.agentId ? recorded.sessionId : undefined;
651
+ // `session/load` replays the session's conversation as updates. They are the
652
+ // agent's history, not this turn's work, so they are not forwarded.
653
+ let reloading = false;
578
654
  let bridge = new AcpEventBridge(step, agent.agentId, baseCtx);
579
655
  // A tool pipeline error fails the step, as it does in `callModel`: it is
580
656
  // kept, the agent's turn is cancelled, and the error is thrown once the
@@ -586,6 +662,9 @@ export async function executeAcpAgent(step, input, ctx, layers) {
586
662
  agentId: agent.agentId,
587
663
  layers,
588
664
  onUpdate: (notification) => {
665
+ if (reloading) {
666
+ return;
667
+ }
589
668
  tools?.observe(notification.update);
590
669
  events.forward(notification);
591
670
  },
@@ -606,6 +685,7 @@ export async function executeAcpAgent(step, input, ctx, layers) {
606
685
  ...bindingFor(bridge),
607
686
  cwd,
608
687
  });
688
+ reloading = resumeId !== undefined;
609
689
  const resolution = await openSession({
610
690
  step,
611
691
  agent,
@@ -614,17 +694,32 @@ export async function executeAcpAgent(step, input, ctx, layers) {
614
694
  host,
615
695
  binding: bindingFor(bridge),
616
696
  tools,
697
+ resumeId,
698
+ }).finally(() => {
699
+ reloading = false;
617
700
  });
701
+ if (resolution.resumed) {
702
+ tools?.sessionReloaded();
703
+ }
704
+ if (resolution.fresh && !resolution.resumed) {
705
+ await sessions?.write({
706
+ sessionId: resolution.live.session.sessionId,
707
+ agentId: agent.agentId,
708
+ });
709
+ }
618
710
  await applySessionSelection(step, ctx, resolution, baseCtx);
619
711
  turnError.cancel = () => resolution.live.session.cancel();
620
712
  // History seeds only a freshly opened session; a reused one already owns
621
713
  // its conversation on the agent side.
622
- let turnPrompt = resolution.fresh
623
- ? withHistoryPrompt({
624
- prompt: promptText,
625
- history: priorHistory,
626
- })
627
- : promptText;
714
+ // A reloaded session has its conversation too, and the work it had done.
715
+ let turnPrompt = resolution.resumed
716
+ ? `${ACP_RESUME_NOTICE}\n\n${promptText}`
717
+ : resolution.fresh
718
+ ? withHistoryPrompt({
719
+ prompt: promptText,
720
+ history: priorHistory,
721
+ })
722
+ : promptText;
628
723
  let turnBlocks = blocks;
629
724
  let retries = 0;
630
725
  for (;;) {
@@ -690,6 +785,7 @@ export async function executeAcpAgent(step, input, ctx, layers) {
690
785
  await baseCtx.harness.storeLayers(layers, response, baseCtx);
691
786
  }
692
787
  await finalizeSession(resolution, baseCtx);
788
+ await sessions?.clear();
693
789
  return await stepOutput(step, result);
694
790
  }
695
791
  }
@@ -14,6 +14,7 @@ import { emitStepEvent, runToReturn } from './emit-items.js';
14
14
  import { trackUsage } from './message-helpers.js';
15
15
  import { wrapModelError } from './model-error.js';
16
16
  import { parseStructuredOutput } from './structured-output.js';
17
+ import { turnEndingIn } from './turn-ending.js';
17
18
  import { getContextChannelStore, isContextImpl, isFunctionCall, isMutableContext, } from './typeguards.js';
18
19
  //#region run
19
20
  export async function executeRunCode(step, input, ctx) {
@@ -39,6 +40,12 @@ export async function executeRunCode(step, input, ctx) {
39
40
  if (isNoeticError(e) && e.noeticError.kind === 'cancelled') {
40
41
  throw e;
41
42
  }
43
+ // These end the turn, not the step: a retry could not help, and wrapping
44
+ // them would hide from the harness why the turn stopped.
45
+ const ending = turnEndingIn(e);
46
+ if (ending) {
47
+ throw ending;
48
+ }
42
49
  lastError = e instanceof Error ? e : new Error(String(e));
43
50
  if (attempt < maxAttempts - 1 && retry) {
44
51
  const delay = computeDelay(retry, attempt);
@@ -5,6 +5,7 @@
5
5
  * the same idempotency key instead of acting twice (spec 23a § Connection Steps).
6
6
  */
7
7
  import { frameworkCast } from '@noetic-tools/types';
8
+ import { ContextImpl } from '../runtime/context-impl.js';
8
9
  import { evaluateTarget, reconcilePending, refuseWitnessAct, resolveStepConnection, signalOf, } from './connection-steps.js';
9
10
  //#endregion
10
11
  //#region Helpers
@@ -56,6 +57,12 @@ export async function executeCall(step, input, ctx, options = {}) {
56
57
  ledgerKey: options.ledgerKey,
57
58
  });
58
59
  refuseWitnessAct(baseCtx, connection.resolved, step.op);
60
+ // An operation with a lasting effect marks its step: a turn resumed under another
61
+ // flow version will not throw that record away unasked (spec 23 § Versions).
62
+ const info = connection.resolved.manifest.operations[step.op];
63
+ if ((info?.once || info?.effects) && baseCtx instanceof ContextImpl) {
64
+ baseCtx.ledger?.noteEffect(baseCtx.currentDispatch()?.path);
65
+ }
59
66
  const signal = signalOf(baseCtx);
60
67
  const prior = await reconcilePending(connection, signal, baseCtx);
61
68
  const key = prior?.key ?? connection.idempotencyKey;
@@ -85,14 +92,33 @@ export async function executeCall(step, input, ctx, options = {}) {
85
92
  onTask: (status) => {
86
93
  if (entry.taskId !== status.taskId) {
87
94
  entry.taskId = status.taskId;
88
- void connection.pending?.write(entry);
95
+ void connection.pending?.write(entry).then(markWaiting);
89
96
  }
90
97
  },
91
98
  };
99
+ // Once the long operation has an id on record the step only waits for it, and a
100
+ // parked turn can come back for it (spec 23 § Parked turns).
101
+ let stopWaiting;
102
+ const markWaiting = () => {
103
+ if (stopWaiting || !(baseCtx instanceof ContextImpl) || !connection.pending) {
104
+ return;
105
+ }
106
+ stopWaiting = baseCtx.ledger?.parking.wait(baseCtx.currentDispatch()?.path, Number.POSITIVE_INFINITY);
107
+ };
108
+ if (prior?.taskId) {
109
+ markWaiting();
110
+ }
92
111
  // A previous attempt's long operation is waited on, not started again (spec 35 § Durability).
93
- const output = prior?.taskId && connection.resolved.awaitTask
94
- ? await connection.resolved.awaitTask(prior.taskId, step.op, callOptions)
95
- : await connection.resolved.call(step.op, args, callOptions);
112
+ let output;
113
+ try {
114
+ output =
115
+ prior?.taskId && connection.resolved.awaitTask
116
+ ? await connection.resolved.awaitTask(prior.taskId, step.op, callOptions)
117
+ : await connection.resolved.call(step.op, args, callOptions);
118
+ }
119
+ finally {
120
+ stopWaiting?.();
121
+ }
96
122
  await connection.pending?.clear();
97
123
  return frameworkCast(output);
98
124
  }
@@ -11,6 +11,7 @@ import { closeUnstartedSpan, openChildSpan, traceChild } from './child-span.js';
11
11
  import { cloneWithGuard } from './clone-guard.js';
12
12
  import { releasePathLeases } from './connection-steps.js';
13
13
  import { forgetAnswers } from './execute-decide.js';
14
+ import { turnEndingIn } from './turn-ending.js';
14
15
  import { getContextChannelStore, isContextImpl, isMutableContext } from './typeguards.js';
15
16
  //#region conditional
16
17
  export async function executeConditional(step, input, ctx, executeStep) {
@@ -262,6 +263,20 @@ function toNoeticError(err, stepId) {
262
263
  retriesExhausted: false,
263
264
  };
264
265
  }
266
+ /**
267
+ * A path whose error ends the turn ends it for every path: it is not folded into
268
+ * `fork_partial`, handed to a `settle` merge, or lost to a race.
269
+ *
270
+ * @throws The turn-ending error of the first path that has one.
271
+ */
272
+ function throwTurnEnding(settled) {
273
+ for (const result of settled) {
274
+ const ending = result.status === 'rejected' ? turnEndingIn(result.reason) : undefined;
275
+ if (ending) {
276
+ throw ending;
277
+ }
278
+ }
279
+ }
265
280
  function classifyResults(settled, paths) {
266
281
  const succeeded = [];
267
282
  const failed = [];
@@ -316,6 +331,7 @@ async function executeAll(step, paths, _input, ctx, childContexts, executeStep,
316
331
  }
317
332
  });
318
333
  const settled = await runWithConcurrency(tasks, concurrency);
334
+ throwTurnEnding(settled);
319
335
  const { succeeded, failed } = classifyResults(settled, paths);
320
336
  // If the PARENT context was aborted mid-inParallel, the whole inParallel is cancelled —
321
337
  // surface 'cancelled', not a partial-failure shape (spec 09, item 3).
@@ -560,6 +576,11 @@ export async function executeLoop(step, input, ctx, executeStep) {
560
576
  if (e.noeticError.kind === 'cancelled') {
561
577
  throw e;
562
578
  }
579
+ // Nor is an error that ends the turn something a loop retries or skips.
580
+ const ending = turnEndingIn(e);
581
+ if (ending) {
582
+ throw ending;
583
+ }
563
584
  const action = step.onError(e.noeticError, ctx);
564
585
  if (action === 'retry') {
565
586
  continue;
@@ -3,12 +3,17 @@
3
3
  * approval gates, run the tool (streaming generator progress), and trace it.
4
4
  */
5
5
  import { frameworkCast, NoeticErrorImpl, validateSchema } from '@noetic-tools/types';
6
+ import { orderedCallId } from '../connections/durability.js';
6
7
  import { ToolAttr } from '../observability/genai-attributes.js';
7
- import { askApproval } from '../runtime/tool-approval.js';
8
+ import { ContextImpl } from '../runtime/context-impl.js';
9
+ import { heldArgsHash, heldCallsOf, heldScopeOf, holdAndWait, mayWriteHolds, } from '../runtime/held-calls.js';
10
+ import { awaitApproval } from '../runtime/tool-approval.js';
11
+ import { isToolHold } from '../runtime/tool-call.js';
8
12
  import { emitToolUi } from '../runtime/tool-ui.js';
9
13
  import { buildToolExecutionContext, emitFrameworkEvent, getBroadcaster } from './action-deps.js';
10
14
  import { SteeringAction } from './action-types.js';
11
15
  import { openChildSpan, traceChild } from './child-span.js';
16
+ import { runRootOf } from './connection-steps.js';
12
17
  //#region tool
13
18
  function isAsyncGenerator(value) {
14
19
  if (typeof value !== 'object' || value === null) {
@@ -116,12 +121,53 @@ async function runInvokeTool(step, input, baseCtx, harness, layers, span) {
116
121
  refuse(decision);
117
122
  }
118
123
  }
119
- if (step.tool.needsApproval) {
120
- const approval = await askApproval({
124
+ // Held calls of this step, and its idempotency key, go under its dispatch path:
125
+ // a step id repeats across loop iterations and parallel branches, a path does
126
+ // not. A run with no ledger has no path, so the call is told apart by its order
127
+ // among this step's calls in the run.
128
+ const holdId = (baseCtx instanceof ContextImpl ? baseCtx.currentDispatch()?.path : undefined) ??
129
+ orderedCallId(runRootOf(baseCtx), baseCtx, step.id);
130
+ const held = {
131
+ callId: holdId,
132
+ name: step.tool.name,
133
+ args: parsedArgs,
134
+ argsHash: heldArgsHash(step.tool.name, parsedArgs),
135
+ };
136
+ const holds = heldCallsOf(harness);
137
+ const holdScope = heldScopeOf(baseCtx);
138
+ // The body already ran, and left its result for a person to give: the turn
139
+ // parked on it, or was cut off, and this is the step coming back. Running the
140
+ // body again would ask the question a second time.
141
+ const left = await holds.load(holdScope, holdId);
142
+ if (left?.reason === 'result' && left.argsHash === held.argsHash) {
143
+ const result = await heldResult({
144
+ harness,
145
+ ctx: baseCtx,
146
+ stepId: step.id,
147
+ }, left);
148
+ emitToolUi({
149
+ ctx: baseCtx,
150
+ tool: step.tool,
151
+ callId: step.id,
152
+ phase: 'result',
153
+ args: parsedArgs,
154
+ output: result,
155
+ });
156
+ emitCompleted(false, typeof result === 'string' ? result : JSON.stringify(result));
157
+ return frameworkCast(result);
158
+ }
159
+ // A durable call a host died inside had its approval before it started. What a
160
+ // person is asked now is how it ended, not whether it may run.
161
+ const wasCutOff = step.tool.durable === true &&
162
+ (await heldCallsOf(harness).wasStarted(heldScopeOf(baseCtx), holdId, heldArgsHash(step.tool.name, parsedArgs)));
163
+ if (step.tool.needsApproval && !wasCutOff) {
164
+ const approval = await awaitApproval({
121
165
  harness,
122
166
  toolName: step.tool.name,
123
167
  toolArgs: parsedArgs,
168
+ // The approver sees the step's id; the hold goes under an id unique to this call.
124
169
  callId: step.id,
170
+ recordId: holdId,
125
171
  ctx: baseCtx,
126
172
  });
127
173
  span.setAttribute(ToolAttr.APPROVAL, approval.outcome);
@@ -129,6 +175,46 @@ async function runInvokeTool(step, input, baseCtx, harness, layers, span) {
129
175
  refuse(approval.decision);
130
176
  }
131
177
  }
178
+ // A durable tool is not repeated unasked (spec 23a § Tool calls in a round). An
179
+ // intent with no result means a host died while it ran: a person says what happened.
180
+ const durable = step.tool.durable === true;
181
+ if (durable && baseCtx instanceof ContextImpl) {
182
+ baseCtx.ledger?.noteEffect(baseCtx.currentDispatch()?.path);
183
+ }
184
+ if (durable && (await holds.wasStarted(holdScope, holdId, held.argsHash))) {
185
+ const answer = await holdAndWait({
186
+ harness,
187
+ ctx: baseCtx,
188
+ record: {
189
+ ...held,
190
+ reason: 'outcome',
191
+ },
192
+ });
193
+ if (answer.resolution?.hasOutput) {
194
+ emitCompleted(false, JSON.stringify(answer.resolution.output));
195
+ return frameworkCast(answer.resolution.output);
196
+ }
197
+ const action = answer.resolution?.action ?? SteeringAction.Deny;
198
+ if (action !== SteeringAction.Allow) {
199
+ refuse({
200
+ action,
201
+ guidance: answer.resolution?.guidance,
202
+ });
203
+ }
204
+ }
205
+ if (durable && mayWriteHolds(baseCtx)) {
206
+ await holds.arm(holdScope, holdId, held.argsHash);
207
+ }
208
+ // The tool reported back with an error: its outcome is known, and it may be tried
209
+ // again. A result is another matter. It is on record only once the step's own
210
+ // ledger entry is written, after this returns, so the intent stays until the
211
+ // run's records are cleared: a host that dies in between resumes to a held
212
+ // call, not to the tool running a second time unasked.
213
+ const disarm = async () => {
214
+ if (durable && mayWriteHolds(baseCtx)) {
215
+ await holds.disarm(holdScope, holdId);
216
+ }
217
+ };
132
218
  emitToolUi({
133
219
  ctx: baseCtx,
134
220
  tool: step.tool,
@@ -137,9 +223,12 @@ async function runInvokeTool(step, input, baseCtx, harness, layers, span) {
137
223
  args: parsedArgs,
138
224
  });
139
225
  try {
140
- const toolCtx = buildToolExecutionContext(baseCtx, harness);
226
+ // The step's place in the run is its key: a resumed step sends the same one.
227
+ const toolCtx = buildToolExecutionContext(baseCtx, harness, {
228
+ recordId: holdId,
229
+ });
141
230
  const execResult = step.tool.execute(parsedArgs, toolCtx);
142
- const result = isAsyncGenerator(execResult)
231
+ const ran = isAsyncGenerator(execResult)
143
232
  ? await consumeToolGenerator({
144
233
  generator: execResult,
145
234
  stepId: step.id,
@@ -148,6 +237,32 @@ async function runInvokeTool(step, input, baseCtx, harness, layers, span) {
148
237
  args: parsedArgs,
149
238
  })
150
239
  : await execResult;
240
+ // The tool did its part and left the result for a person to give.
241
+ const result = isToolHold(ran)
242
+ ? await heldResult({
243
+ harness,
244
+ ctx: baseCtx,
245
+ stepId: step.id,
246
+ }, {
247
+ ...held,
248
+ reason: 'result',
249
+ ...(ran.dueAt === undefined
250
+ ? {}
251
+ : {
252
+ dueAt: ran.dueAt,
253
+ }),
254
+ ...(ran.onDue === undefined
255
+ ? {}
256
+ : {
257
+ onDue: ran.onDue,
258
+ }),
259
+ ...(ran.request === undefined
260
+ ? {}
261
+ : {
262
+ request: ran.request,
263
+ }),
264
+ })
265
+ : ran;
151
266
  emitToolUi({
152
267
  ctx: baseCtx,
153
268
  tool: step.tool,
@@ -170,8 +285,13 @@ async function runInvokeTool(step, input, baseCtx, harness, layers, span) {
170
285
  });
171
286
  emitCompleted(true, e instanceof Error ? e.message : String(e));
172
287
  if (e instanceof NoeticErrorImpl) {
288
+ // A run cut short was not the tool reporting back: its outcome stays unknown.
289
+ if (e.noeticError.kind !== 'cancelled') {
290
+ await disarm();
291
+ }
173
292
  throw e;
174
293
  }
294
+ await disarm();
175
295
  throw new NoeticErrorImpl({
176
296
  kind: 'step_failed',
177
297
  stepId: step.id,
@@ -181,3 +301,27 @@ async function runInvokeTool(step, input, baseCtx, harness, layers, span) {
181
301
  }
182
302
  }
183
303
  //#endregion
304
+ //#region Held results
305
+ /**
306
+ * Wait for the answer to a result a tool left open with `hold()`.
307
+ *
308
+ * @throws NoeticError `step_failed` when the hold's deadline passes with no answer,
309
+ * `cancelled` when the context is aborted while it waits.
310
+ */
311
+ async function heldResult(at, record) {
312
+ const answer = await holdAndWait({
313
+ harness: at.harness,
314
+ ctx: at.ctx,
315
+ record,
316
+ });
317
+ if (answer.resolution?.hasOutput) {
318
+ return answer.resolution.output;
319
+ }
320
+ throw new NoeticErrorImpl({
321
+ kind: 'step_failed',
322
+ stepId: at.stepId,
323
+ cause: new Error(`nobody answered '${record.name}' before the hold ran out`),
324
+ retriesExhausted: true,
325
+ });
326
+ }
327
+ //#endregion