@noetic-tools/core 5.22.0-next.2 → 5.22.0-next.4

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 (47) hide show
  1. package/dist/adapters/in-memory-subprocess-adapter.js +4 -2
  2. package/dist/builders/custom-item.d.ts +1 -1
  3. package/dist/builders/custom-item.js +14 -3
  4. package/dist/connections/pool.d.ts +18 -0
  5. package/dist/connections/pool.js +54 -9
  6. package/dist/connections/registry.js +11 -0
  7. package/dist/harness/agent-harness.d.ts +110 -4
  8. package/dist/harness/agent-harness.js +394 -40
  9. package/dist/harness/deps/types.d.ts +1 -1
  10. package/dist/harness/forget.d.ts +57 -0
  11. package/dist/harness/forget.js +496 -0
  12. package/dist/harness/harness-options.d.ts +40 -1
  13. package/dist/harness/model-rounds.d.ts +6 -0
  14. package/dist/harness/model-rounds.js +7 -3
  15. package/dist/harness/model-tool-round.js +19 -5
  16. package/dist/harness/park-watchers.d.ts +3 -2
  17. package/dist/harness/recorded-tool-calls.d.ts +16 -0
  18. package/dist/harness/recorded-tool-calls.js +106 -0
  19. package/dist/harness/spend.d.ts +13 -1
  20. package/dist/harness/spend.js +82 -1
  21. package/dist/harness/steer-inbox.js +9 -5
  22. package/dist/harness/thread-record.d.ts +23 -1
  23. package/dist/harness/thread-record.js +98 -21
  24. package/dist/harness/turn-cuts.d.ts +50 -0
  25. package/dist/harness/turn-cuts.js +108 -0
  26. package/dist/index.d.ts +6 -7
  27. package/dist/index.js +2 -3
  28. package/dist/interpreter/acp-tools.js +21 -4
  29. package/dist/interpreter/execute-action.js +7 -1
  30. package/dist/interpreter/execute.js +55 -3
  31. package/dist/interpreter/step-dispatcher.js +17 -1
  32. package/dist/interpreter/step-kind-dispatch.js +9 -1
  33. package/dist/runtime/durable/child-links.d.ts +61 -0
  34. package/dist/runtime/durable/child-links.js +127 -0
  35. package/dist/runtime/durable/session-store.d.ts +11 -0
  36. package/dist/runtime/durable/session-store.js +28 -2
  37. package/dist/runtime/durable/turn-lease.d.ts +10 -0
  38. package/dist/runtime/durable/turn-lease.js +10 -2
  39. package/dist/runtime/held-calls.d.ts +65 -6
  40. package/dist/runtime/held-calls.js +257 -5
  41. package/dist/runtime/output-store.d.ts +2 -0
  42. package/dist/runtime/output-store.js +3 -1
  43. package/dist/runtime/session-runner.d.ts +9 -1
  44. package/dist/runtime/session-runner.js +34 -0
  45. package/dist/runtime/tool-approval.d.ts +1 -3
  46. package/dist/runtime/tool-approval.js +1 -1
  47. package/package.json +2 -2
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Cut turns (spec 23 § Cut turns): a turn stopped by `lease_lost` or
3
+ * `ledger_write_failed` has everything before the stop on record, so it is run
4
+ * again by a later wake, with back-off, rather than failed. The harness keeps each
5
+ * thread's mark here as well as in the thread record, since the storage that just
6
+ * refused a write may refuse the mark too.
7
+ */
8
+ import type { TurnCutReason } from './deps/types.js';
9
+ import type { TurnCutConfig } from './harness-options.js';
10
+ /** How often a turn was cut, and when last. */
11
+ export interface CutMark {
12
+ readonly reason: string;
13
+ readonly count: number;
14
+ readonly at: number;
15
+ }
16
+ /**
17
+ * The parts of a stored turn a cut is read from. A turn is known by its messages,
18
+ * not its execution: one whose checkpoint could not be written resumes under a
19
+ * new execution id, and its cuts still count.
20
+ */
21
+ interface CutTurn {
22
+ readonly messageIds: ReadonlyArray<string>;
23
+ readonly cut?: CutMark;
24
+ }
25
+ /** @public How many times a turn may be cut and run again before it fails. */
26
+ export declare const DEFAULT_CUT_ATTEMPTS = 3;
27
+ /** @public How long after its first cut a turn is due again, in ms. */
28
+ export declare const DEFAULT_CUT_DELAY_MS = 1000;
29
+ /** @public The longest a cut turn waits before it is due again, in ms. */
30
+ export declare const DEFAULT_CUT_MAX_DELAY_MS = 60000;
31
+ /** @internal The harness's cut marks, by thread, and the policy that runs cut turns again. */
32
+ export declare class TurnCuts {
33
+ private readonly policy;
34
+ private readonly marks;
35
+ constructor(config: TurnCutConfig | undefined);
36
+ /** Why `error` cuts the turn rather than failing it, or undefined when it does not. */
37
+ reasonOf(error: unknown): TurnCutReason | undefined;
38
+ /** The turn's mark: the stored one or this harness's, whichever counts more cuts. */
39
+ markOf(threadId: string, turn: CutTurn): CutMark | undefined;
40
+ /**
41
+ * The mark for one more cut of the turn, kept here; undefined when the turn has
42
+ * been cut as often as the policy allows, and fails instead.
43
+ */
44
+ cut(threadId: string, turn: CutTurn, reason: TurnCutReason, at: number): CutMark | undefined;
45
+ /** When a turn with `mark` is due again. */
46
+ dueAt(mark: CutMark): number;
47
+ /** The thread's turn ended, parked or was dropped: its cuts no longer count. */
48
+ forget(threadId: string): void;
49
+ }
50
+ export {};
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Cut turns (spec 23 § Cut turns): a turn stopped by `lease_lost` or
3
+ * `ledger_write_failed` has everything before the stop on record, so it is run
4
+ * again by a later wake, with back-off, rather than failed. The harness keeps each
5
+ * thread's mark here as well as in the thread record, since the storage that just
6
+ * refused a write may refuse the mark too.
7
+ */
8
+ import { NoeticConfigError } from '@noetic-tools/types';
9
+ import { turnEndingIn } from '../interpreter/turn-ending.js';
10
+ //#endregion
11
+ //#region Constants
12
+ /** @public How many times a turn may be cut and run again before it fails. */
13
+ export const DEFAULT_CUT_ATTEMPTS = 3;
14
+ /** @public How long after its first cut a turn is due again, in ms. */
15
+ export const DEFAULT_CUT_DELAY_MS = 1e3;
16
+ /** @public The longest a cut turn waits before it is due again, in ms. */
17
+ export const DEFAULT_CUT_MAX_DELAY_MS = 6e4;
18
+ const CUT_REASONS = new Set([
19
+ 'lease_lost',
20
+ 'ledger_write_failed',
21
+ ]);
22
+ //#endregion
23
+ //#region Helpers
24
+ function isCutReason(kind) {
25
+ return kind !== undefined && CUT_REASONS.has(kind);
26
+ }
27
+ /** What names a turn's delivery: its message ids, in order. */
28
+ function deliveryOf(turn) {
29
+ return JSON.stringify(turn.messageIds);
30
+ }
31
+ function resolveCutPolicy(config) {
32
+ const attempts = config?.attempts ?? DEFAULT_CUT_ATTEMPTS;
33
+ const delayMs = config?.delayMs ?? DEFAULT_CUT_DELAY_MS;
34
+ const maxDelayMs = config?.maxDelayMs ?? DEFAULT_CUT_MAX_DELAY_MS;
35
+ const attemptsOk = Number.isInteger(attempts) && attempts >= 0;
36
+ const delayOk = Number.isFinite(delayMs) && delayMs >= 0;
37
+ const maxOk = Number.isFinite(maxDelayMs) && maxDelayMs >= delayMs;
38
+ if (!attemptsOk || !delayOk || !maxOk) {
39
+ throw new NoeticConfigError({
40
+ code: 'INVALID_LEASE_OPTIONS',
41
+ message: `environment.storage.lease.cut is not usable: attempts ${attempts}, delayMs ${delayMs}, maxDelayMs ${maxDelayMs}.`,
42
+ hint: 'Give attempts a whole number from 0 up, delayMs a finite number from 0 up, and maxDelayMs a finite number no less than delayMs, or leave them out for the defaults.',
43
+ });
44
+ }
45
+ return {
46
+ attempts,
47
+ delayMs,
48
+ maxDelayMs,
49
+ };
50
+ }
51
+ //#endregion
52
+ //#region TurnCuts
53
+ /** @internal The harness's cut marks, by thread, and the policy that runs cut turns again. */
54
+ export class TurnCuts {
55
+ policy;
56
+ marks = new Map();
57
+ constructor(config) {
58
+ this.policy = resolveCutPolicy(config);
59
+ }
60
+ /** Why `error` cuts the turn rather than failing it, or undefined when it does not. */
61
+ reasonOf(error) {
62
+ const kind = turnEndingIn(error)?.noeticError.kind;
63
+ return isCutReason(kind) ? kind : undefined;
64
+ }
65
+ /** The turn's mark: the stored one or this harness's, whichever counts more cuts. */
66
+ markOf(threadId, turn) {
67
+ const kept = this.marks.get(threadId);
68
+ const mine = kept?.delivery === deliveryOf(turn) ? kept : undefined;
69
+ if (!mine) {
70
+ return turn.cut;
71
+ }
72
+ if (!turn.cut || turn.cut.count < mine.count) {
73
+ return mine;
74
+ }
75
+ return turn.cut;
76
+ }
77
+ /**
78
+ * The mark for one more cut of the turn, kept here; undefined when the turn has
79
+ * been cut as often as the policy allows, and fails instead.
80
+ */
81
+ cut(threadId, turn, reason, at) {
82
+ const count = (this.markOf(threadId, turn)?.count ?? 0) + 1;
83
+ if (count > this.policy.attempts) {
84
+ this.marks.delete(threadId);
85
+ return undefined;
86
+ }
87
+ const mark = {
88
+ reason,
89
+ count,
90
+ at,
91
+ };
92
+ this.marks.set(threadId, {
93
+ ...mark,
94
+ delivery: deliveryOf(turn),
95
+ });
96
+ return mark;
97
+ }
98
+ /** When a turn with `mark` is due again. */
99
+ dueAt(mark) {
100
+ const delay = this.policy.delayMs * 2 ** Math.max(0, mark.count - 1);
101
+ return mark.at + Math.min(this.policy.maxDelayMs, delay);
102
+ }
103
+ /** The thread's turn ended, parked or was dropped: its cuts no longer count. */
104
+ forget(threadId) {
105
+ this.marks.delete(threadId);
106
+ }
107
+ }
108
+ //#endregion
package/dist/index.d.ts CHANGED
@@ -67,8 +67,7 @@ export { aiCondition, allCondition, anyCondition, embeddingMatch, otherwise, sem
67
67
  /** @public */
68
68
  export { cosineSimilarity } from './conditions/cosine-similarity.js';
69
69
  /** @public */
70
- /** @public */
71
- export { DECISION_ITEM_TYPE, isDecisionItem, isNoeticConfigError, isNoeticError, NoeticConfigError, NoeticErrorImpl, } from '@noetic-tools/types';
70
+ export { DECISION_ITEM_TYPE, failureCause, HeldCallSchema, HeldCallSettledSchema, isDecisionItem, isNoeticConfigError, isNoeticError, NoeticConfigError, NoeticErrorImpl, readHeldCallEvent, } from '@noetic-tools/types';
72
71
  /** @public */
73
72
  export type { AskUserAnnotation, AskUserInput, AskUserOption, AskUserOutput, AskUserQuestion, } from './types/ask-user-types.js';
74
73
  /** @public */
@@ -118,7 +117,7 @@ export { DEFAULT_EXPRESSION_LIMITS } from './expression/jsonata.js';
118
117
  /** @public */
119
118
  export { AgentHarness } from './harness/agent-harness.js';
120
119
  /** @public */
121
- export type { AgentEnvironmentConfig, ParkConfig, StorageEnvironmentConfig, TurnLeaseConfig, WakeTimeListener, } from './harness/harness-options.js';
120
+ export type { AgentEnvironmentConfig, ParkConfig, StorageEnvironmentConfig, TurnCutConfig, TurnLeaseConfig, WakeTimeListener, } from './harness/harness-options.js';
122
121
  /** @public */
123
122
  export { DEFAULT_TASK_POLL_MS, DEFAULT_WAKE_DEBOUNCE_MS } from './harness/park-watchers.js';
124
123
  /** @public */
@@ -180,13 +179,13 @@ export type { ContextScope, ExecutionContext, ExecutionOutcome, ExecutionSpan, L
180
179
  /** @public */
181
180
  export type { LayerTraceSpan, Span, TraceExporter } from '@noetic-tools/types';
182
181
  /** @public */
183
- export type { FrameworkStreamEvent, HarnessResponse, SdkStreamEvent, StreamEvent, StreamingItem, } from '@noetic-tools/types';
182
+ export type { FrameworkStreamEvent, HarnessResponse, SdkStreamEvent, StreamEvent, StreamingItem, TurnCut, TurnCutReason, } from '@noetic-tools/types';
184
183
  /** @public */
185
- export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, DrainCall, DrainReport, ExecuteOptions, ExecutionScope, ExecutionStatus, HarnessJudgmentContract, HarnessStatus, HeldCall, HeldResolution, ItemSchemaConfig, ReanchorReason, RecallLayerOutput, SessionScope, SessionUsage, StuckTurn, ToolHold, TrailMark, } from '@noetic-tools/types';
184
+ export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, DrainCall, DrainReport, ExecuteOptions, ExecutionScope, ExecutionStatus, HarnessJudgmentContract, HarnessStatus, HeldCall, HeldCallContext, HeldCallEvent, HeldCallHandler, HeldCallSettled, HeldResolution, HeldSteerPolicy, ItemSchemaConfig, ReanchorReason, RecallLayerOutput, RecordedToolCall, SessionScope, SessionUsage, StoredTurn, StuckTurn, ToolHold, TrailMark, } from '@noetic-tools/types';
186
185
  /** @public */
187
- export type { PendingSpend, ReconcileSpendOptions, SpendSettlement, WriteOffSpendOptions, } from '@noetic-tools/types';
186
+ export type { ForgetOptions, ForgetReport, ListStoredOptions, PendingSpend, ReconcileSpendOptions, SpendSettlement, StoredExecution, WriteOffSpendOptions, } from '@noetic-tools/types';
188
187
  /** @public */
189
- export { SpendKind } from '@noetic-tools/types';
188
+ export { ExecutionPart, SpendKind } from '@noetic-tools/types';
190
189
  /** @public */
191
190
  export type { AfterModelCallParams, AfterModelCallResult, ApproveRequest, ApproveToolCallParams, BeforeToolCallParams, BeforeToolCallResult, LedgerEntry, OnSteerParams, OnSteerResult, Steer, SteeringConfig, SteeringDecision, SteeringRule, SteeringState, SteerVerdict, ToolApprover, } from '@noetic-tools/types';
192
191
  /** @public */
package/dist/index.js CHANGED
@@ -50,8 +50,7 @@ export { cosineSimilarity } from './conditions/cosine-similarity.js';
50
50
  //#endregion
51
51
  //#region Errors
52
52
  /** @public */
53
- /** @public */
54
- export { DECISION_ITEM_TYPE, isDecisionItem, isNoeticConfigError, isNoeticError, NoeticConfigError, NoeticErrorImpl, } from '@noetic-tools/types';
53
+ export { DECISION_ITEM_TYPE, failureCause, HeldCallSchema, HeldCallSettledSchema, isDecisionItem, isNoeticConfigError, isNoeticError, NoeticConfigError, NoeticErrorImpl, readHeldCallEvent, } from '@noetic-tools/types';
55
54
  /** @public */
56
55
  export { AskUserAnnotationSchema, AskUserInputSchema, AskUserOptionSchema, AskUserOutputSchema, AskUserQuestionSchema, } from './types/ask-user-types.js';
57
56
  //#endregion
@@ -121,7 +120,7 @@ export { ChannelSnapshotSchema, CheckpointSchemaVersion, CheckpointSnapshotSchem
121
120
  /** @public */
122
121
  export { Slot } from '@noetic-tools/context';
123
122
  /** @public */
124
- export { SpendKind } from '@noetic-tools/types';
123
+ export { ExecutionPart, SpendKind } from '@noetic-tools/types';
125
124
  /** @public */
126
125
  export { LedgerEntryKind, SteerAction, SteeringAction, SteerPoint } from '@noetic-tools/types';
127
126
  /** @public */
@@ -13,7 +13,7 @@ import { orderedCallId } from '../connections/durability.js';
13
13
  import { offeredTools, stepConnectionsOf } from '../connections/step-tools.js';
14
14
  import { ToolAttr } from '../observability/genai-attributes.js';
15
15
  import { drainsOf } from '../runtime/drain.js';
16
- import { heldCallsOf, heldScopeOf, mayWriteHolds, waitOnHeldCalls } from '../runtime/held-calls.js';
16
+ import { heldCallsOf, heldScopeOf, mayWriteHolds, noticeHeld, waitOnHeldCalls, } from '../runtime/held-calls.js';
17
17
  import { createToolResultItem, executeToolCall, resolveWireJsonSchema } from '../runtime/tool-call.js';
18
18
  import { sanitizeToolNameForWire } from '../util/tool-name.js';
19
19
  import { BridgedCallRecords } from './acp-resume.js';
@@ -373,8 +373,20 @@ export class AcpToolRunner {
373
373
  callId: params.callId ?? held.callId,
374
374
  heldAs: held.callId,
375
375
  });
376
+ noticeHeld({
377
+ harness: ctx.harness,
378
+ ctx,
379
+ held,
380
+ emit: (settled) => binding.events.toolEvent('tool_call_settled', {
381
+ ...settled,
382
+ callId: params.callId ?? settled.callId,
383
+ heldAs: settled.callId,
384
+ }),
385
+ });
376
386
  }
377
- await waitOnHeldCalls({
387
+ // The wait throws `cancelled` when the agent's signal ends it, as it does for
388
+ // the turn's own abort: only the latter is the turn's to handle.
389
+ const gaveUp = await waitOnHeldCalls({
378
390
  harness: ctx.harness,
379
391
  ctx,
380
392
  callIds: [
@@ -382,11 +394,16 @@ export class AcpToolRunner {
382
394
  ],
383
395
  signal,
384
396
  park: false,
397
+ }).then(() => signal.aborted, (error) => {
398
+ if (signal.aborted) {
399
+ return true;
400
+ }
401
+ throw error;
385
402
  });
386
403
  // The agent stopped waiting for this call: nobody is left to give an answer to.
387
- if (signal.aborted) {
404
+ if (gaveUp) {
388
405
  if (mayWriteHolds(ctx)) {
389
- await heldCallsOf(ctx.harness).close(heldScopeOf(ctx), held.callId);
406
+ await heldCallsOf(ctx.harness).close(heldScopeOf(ctx), held.callId, 'cancelled');
390
407
  }
391
408
  return {
392
409
  output: CANCELLED_OUTPUT,
@@ -46,7 +46,13 @@ export async function executeRunCode(step, input, ctx) {
46
46
  if (ending) {
47
47
  throw ending;
48
48
  }
49
- lastError = e instanceof Error ? e : new Error(String(e));
49
+ // A thrown non-Error keeps the value itself as the wrapper's cause.
50
+ lastError =
51
+ e instanceof Error
52
+ ? e
53
+ : new Error(String(e), {
54
+ cause: e,
55
+ });
50
56
  if (attempt < maxAttempts - 1 && retry) {
51
57
  const delay = computeDelay(retry, attempt);
52
58
  await new Promise((r) => setTimeout(r, delay));
@@ -1,4 +1,4 @@
1
- import { frameworkCast, NoeticErrorImpl } from '@noetic-tools/types';
1
+ import { frameworkCast, isNoeticConfigError, isNoeticError, NoeticErrorImpl, } from '@noetic-tools/types';
2
2
  import { recordedScopeOf, recordStepOutput } from '../expression/step-outputs.js';
3
3
  import { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.js';
4
4
  import { ContextImpl } from '../runtime/context-impl.js';
@@ -144,13 +144,13 @@ function parseRecordedItems(ctx, raw) {
144
144
  * runs again on resume.
145
145
  */
146
146
  async function recordToLedger(opts) {
147
- const { ledger, ledgerKey, inputHash, lane, step, output } = opts;
147
+ const { ledger, ledgerKey, inputHash, lane, positionalPath, step, output } = opts;
148
148
  if (!ledger || ledgerKey === undefined) {
149
149
  return;
150
150
  }
151
151
  const items = lane?.appendedItems() ?? [];
152
152
  const streamed = lane?.emittedIndices() ?? [];
153
- await ledger.record({
153
+ const stored = await ledger.record({
154
154
  path: ledgerKey,
155
155
  stepId: step.id,
156
156
  kind: step.kind,
@@ -168,6 +168,42 @@ async function recordToLedger(opts) {
168
168
  : {}),
169
169
  completedAt: new Date().toISOString(),
170
170
  });
171
+ /* A positional record prunes what recorded beneath it. A `key:` record sits at no
172
+ * position, so the rounds and child steps that recorded under this dispatch's path
173
+ * are dropped here: the step now replays from its key, and nothing reads them. */
174
+ if (stored && ledgerKey.startsWith(REPLAY_KEY_PREFIX) && positionalPath) {
175
+ await ledger.dropWithin(positionalPath);
176
+ }
177
+ }
178
+ /**
179
+ * Run one of the harness's step hooks (spec 08 § Step hooks). A hook that throws fails
180
+ * the step it ran for: a Noetic error passes through as is, anything else becomes
181
+ * `step_failed` with the hook's error as its cause.
182
+ */
183
+ async function runStepHook(stepId, hook) {
184
+ try {
185
+ await hook();
186
+ }
187
+ catch (error) {
188
+ if (isNoeticError(error) || isNoeticConfigError(error)) {
189
+ throw error;
190
+ }
191
+ throw new NoeticErrorImpl({
192
+ kind: 'step_failed',
193
+ stepId,
194
+ cause: error instanceof Error
195
+ ? error
196
+ : new Error(String(error), {
197
+ cause: error,
198
+ }),
199
+ retriesExhausted: false,
200
+ });
201
+ }
202
+ }
203
+ /** The step hooks a context's harness was configured with, when it has any. */
204
+ function stepHooksOf(ctx) {
205
+ const hooks = ctx.harness.config.hooks;
206
+ return hooks?.beforeStep || hooks?.afterStep ? hooks : undefined;
171
207
  }
172
208
  //#endregion
173
209
  /**
@@ -267,6 +303,7 @@ async function executeStep(step, input, ctx) {
267
303
  lane?.skipLedger();
268
304
  }
269
305
  const inputHash = ledgerKey === undefined ? undefined : lane?.currentDispatch()?.inputHash;
306
+ const positionalPath = lane?.currentDispatch()?.path;
270
307
  const ledger = impl?.ledger;
271
308
  const replay = replayFromLedger({
272
309
  ledger,
@@ -290,8 +327,15 @@ async function executeStep(step, input, ctx) {
290
327
  }
291
328
  // Parking needs to know which steps are in flight (spec 23 § Parked turns).
292
329
  const leaveParking = ledger?.parking.enter(lane?.currentDispatch()?.path);
330
+ const hooks = stepHooksOf(baseCtx);
331
+ const hookStep = frameworkCast(step);
332
+ const hookCtx = frameworkCast(stepCtx);
293
333
  let result;
294
334
  try {
335
+ const before = hooks?.beforeStep;
336
+ if (before) {
337
+ await runStepHook(step.id, () => before(hookStep, hookCtx));
338
+ }
295
339
  await beginEmitItems(step, input, stepCtx);
296
340
  result = await dispatchStepKind(step, input, {
297
341
  stepCtx,
@@ -302,6 +346,13 @@ async function executeStep(step, input, ctx) {
302
346
  // Inside the try, so an item the schemas refuse fails the dispatch like any other
303
347
  // error; before the ledger record, so the entry holds the items and replays them.
304
348
  await emitStepItems(step, result, stepCtx);
349
+ // The step completes only once afterStep returns: one that throws fails it, and
350
+ // the step is not recorded, so a resume runs it again.
351
+ const after = hooks?.afterStep;
352
+ if (after) {
353
+ const output = result;
354
+ await runStepHook(step.id, () => after(hookStep, output, hookCtx));
355
+ }
305
356
  // A JSON workflow node's output is readable as `$steps.<id>` from here on (spec 33).
306
357
  const outputScope = recordedScopeOf(step);
307
358
  if (outputScope) {
@@ -341,6 +392,7 @@ async function executeStep(step, input, ctx) {
341
392
  ledgerKey,
342
393
  inputHash,
343
394
  lane,
395
+ positionalPath,
344
396
  step,
345
397
  output: result,
346
398
  });
@@ -1,3 +1,4 @@
1
+ import { ChildAdapterSource, spawnLinked } from '../runtime/durable/child-links.js';
1
2
  import { DetachedHandleImpl } from '../util/detached-handle.js';
2
3
  import { executeNoAdapter } from './execute.js';
3
4
  //#region Adapter resolution
@@ -20,6 +21,16 @@ export function resolveStepAdapter(step, callOverride, fallback) {
20
21
  }
21
22
  return fallback;
22
23
  }
24
+ /** Where `resolveStepAdapter` took the adapter from, for the child's link. */
25
+ function adapterSourceOf(step, callOverride) {
26
+ if (callOverride) {
27
+ return ChildAdapterSource.Call;
28
+ }
29
+ if ((step.kind === 'runCode' || step.kind === 'spawn') && step.subprocess) {
30
+ return ChildAdapterSource.Step;
31
+ }
32
+ return ChildAdapterSource.Harness;
33
+ }
23
34
  //#endregion
24
35
  //#region Dispatcher
25
36
  /**
@@ -60,7 +71,12 @@ export function dispatchStepThroughAdapter(h, s, input, parentCtx, overrides) {
60
71
  return new DetachedHandleImpl({
61
72
  id: childCtx.id,
62
73
  stepId: s.id,
63
- spawned: adapter.spawn(request),
74
+ spawned: spawnLinked(parentCtx, adapter, {
75
+ childId: childCtx.id,
76
+ stepId: s.id,
77
+ from: adapterSourceOf(s, overrides?.subprocess),
78
+ spawn: () => adapter.spawn(request),
79
+ }),
64
80
  });
65
81
  }
66
82
  //#endregion
@@ -4,6 +4,7 @@
4
4
  * the step lifecycle around this (depth/abort guards, events, ledger, checkpoint).
5
5
  */
6
6
  import { frameworkCast, NoeticErrorImpl } from '@noetic-tools/types';
7
+ import { ChildAdapterSource, spawnLinked } from '../runtime/durable/child-links.js';
7
8
  import { DetachedHandleImpl } from '../util/detached-handle.js';
8
9
  import { executeAcpAgent } from './execute-acp-agent.js';
9
10
  import { executeCallModel, executeRunCode, executeSpawn, executeWithContext, } from './execute-action.js';
@@ -65,7 +66,14 @@ async function dispatchViaAdapter(step, input, ctx, executionId, executor) {
65
66
  const handle = new DetachedHandleImpl({
66
67
  id: executionId,
67
68
  stepId: step.id,
68
- spawned: adapter.spawn(request),
69
+ spawned: executionId === ctx.id
70
+ ? adapter.spawn(request)
71
+ : spawnLinked(ctx, adapter, {
72
+ childId: executionId,
73
+ stepId: step.id,
74
+ from: step.subprocess === undefined ? ChildAdapterSource.Harness : ChildAdapterSource.Step,
75
+ spawn: () => adapter.spawn(request),
76
+ }),
69
77
  });
70
78
  return handle.await();
71
79
  }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Child links: how a run remembers the executions it had a subprocess adapter run
3
+ * out of process, so a forget of the run finds them and stops one still running
4
+ * (spec 23 § Forgetting).
5
+ *
6
+ * A spawn run in process records its steps under its run's root, so it needs no
7
+ * link. One an adapter runs elsewhere becomes an execution of its own, under its
8
+ * own id: the parent run writes `execution:<rootId>:child:<childId>` before
9
+ * dispatching it, naming the step and where its adapter came from, and marks the
10
+ * link `settled` once the child has finished.
11
+ */
12
+ import type { Context, SpawnedSubprocess, SubprocessAdapter } from '@noetic-tools/types';
13
+ import { z } from 'zod';
14
+ /** @internal Mark `adapter` as one that runs steps in the calling process. */
15
+ export declare function markInProcess<T extends SubprocessAdapter>(adapter: T): T;
16
+ /** @internal True when `adapter` runs steps in the calling process: its children need no link. */
17
+ export declare function runsInProcess(adapter: SubprocessAdapter): boolean;
18
+ /** @internal The out-of-process adapters `harness` has dispatched a child through. */
19
+ export declare function adaptersUsedBy(harness: object): ReadonlyArray<SubprocessAdapter>;
20
+ /** @internal The adapter `harness` dispatched the child `childId` through, when it did. */
21
+ export declare function adapterOfChild(harness: object, childId: string): SubprocessAdapter | undefined;
22
+ /** @internal Where the adapter that ran a child came from. */
23
+ export declare const ChildAdapterSource: {
24
+ /** The harness's `environment.subprocess`. */
25
+ readonly Harness: "harness";
26
+ /** The step's own `subprocess`. */
27
+ readonly Step: "step";
28
+ /** The `subprocess` a `detachedSpawn` call passed. */
29
+ readonly Call: "call";
30
+ };
31
+ /** @internal */
32
+ export type ChildAdapterSource = (typeof ChildAdapterSource)[keyof typeof ChildAdapterSource];
33
+ /** @internal A child link as stored. */
34
+ export declare const ChildLinkSchema: z.ZodObject<{
35
+ stepId: z.ZodString;
36
+ at: z.ZodString;
37
+ from: z.ZodEnum<{
38
+ step: "step";
39
+ call: "call";
40
+ harness: "harness";
41
+ }>;
42
+ settled: z.ZodOptional<z.ZodBoolean>;
43
+ }, z.core.$strip>;
44
+ /** @internal */
45
+ export type ChildLink = z.infer<typeof ChildLinkSchema>;
46
+ /** @internal The key of the link from the run rooted at `rootId` to `childId`. */
47
+ export declare function childLinkKey(rootId: string, childId: string): string;
48
+ /**
49
+ * Dispatch a step to `adapter` for `parent`. A step the adapter runs out of process
50
+ * is an execution of its own: on a durable run it is linked to the run's root before
51
+ * it is dispatched, and the link is marked settled once the child finished (spec 23
52
+ * § Forgetting).
53
+ *
54
+ * @internal
55
+ */
56
+ export declare function spawnLinked<TContext>(parent: Context<TContext>, adapter: SubprocessAdapter, child: {
57
+ childId: string;
58
+ stepId: string;
59
+ from: ChildAdapterSource;
60
+ spawn: () => Promise<SpawnedSubprocess>;
61
+ }): Promise<SpawnedSubprocess>;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Child links: how a run remembers the executions it had a subprocess adapter run
3
+ * out of process, so a forget of the run finds them and stops one still running
4
+ * (spec 23 § Forgetting).
5
+ *
6
+ * A spawn run in process records its steps under its run's root, so it needs no
7
+ * link. One an adapter runs elsewhere becomes an execution of its own, under its
8
+ * own id: the parent run writes `execution:<rootId>:child:<childId>` before
9
+ * dispatching it, naming the step and where its adapter came from, and marks the
10
+ * link `settled` once the child has finished.
11
+ */
12
+ import { frameworkCast } from '@noetic-tools/types';
13
+ import { z } from 'zod';
14
+ import { ContextImpl, rootIdOf } from '../context-impl.js';
15
+ //#region In-process adapters
16
+ /** Adapters that run a step in the calling process, through its local executor. */
17
+ const inProcess = new WeakSet();
18
+ /** @internal Mark `adapter` as one that runs steps in the calling process. */
19
+ export function markInProcess(adapter) {
20
+ inProcess.add(adapter);
21
+ return adapter;
22
+ }
23
+ /** @internal True when `adapter` runs steps in the calling process: its children need no link. */
24
+ export function runsInProcess(adapter) {
25
+ return inProcess.has(adapter);
26
+ }
27
+ //#endregion
28
+ //#region Adapters used
29
+ /** The adapter each child a harness dispatched out of process ran on, by child id. */
30
+ const ranBy = new WeakMap();
31
+ function noteAdapter(harness, childId, adapter) {
32
+ const children = ranBy.get(harness) ?? new Map();
33
+ children.set(childId, adapter);
34
+ ranBy.set(harness, children);
35
+ }
36
+ /** @internal The out-of-process adapters `harness` has dispatched a child through. */
37
+ export function adaptersUsedBy(harness) {
38
+ return [
39
+ ...new Set(ranBy.get(harness)?.values()),
40
+ ];
41
+ }
42
+ /** @internal The adapter `harness` dispatched the child `childId` through, when it did. */
43
+ export function adapterOfChild(harness, childId) {
44
+ return ranBy.get(harness)?.get(childId);
45
+ }
46
+ //#endregion
47
+ //#region Links
48
+ /** @internal Where the adapter that ran a child came from. */
49
+ export const ChildAdapterSource = {
50
+ /** The harness's `environment.subprocess`. */
51
+ Harness: 'harness',
52
+ /** The step's own `subprocess`. */
53
+ Step: 'step',
54
+ /** The `subprocess` a `detachedSpawn` call passed. */
55
+ Call: 'call',
56
+ };
57
+ /** @internal A child link as stored. */
58
+ export const ChildLinkSchema = z.object({
59
+ stepId: z.string(),
60
+ at: z.string(),
61
+ from: z.enum([
62
+ ChildAdapterSource.Harness,
63
+ ChildAdapterSource.Step,
64
+ ChildAdapterSource.Call,
65
+ ]),
66
+ /** Set once the child finished, however it ended. */
67
+ settled: z.boolean().optional(),
68
+ });
69
+ /** @internal The key of the link from the run rooted at `rootId` to `childId`. */
70
+ export function childLinkKey(rootId, childId) {
71
+ return `execution:${rootId}:child:${childId}`;
72
+ }
73
+ /** Mark a link settled, unless a forget deleted it meanwhile: nothing brings it back. */
74
+ async function markSettled(storage, key) {
75
+ const raw = await storage.get(key);
76
+ const link = ChildLinkSchema.safeParse(raw);
77
+ if (!link.success || link.data.settled) {
78
+ return;
79
+ }
80
+ const next = {
81
+ ...link.data,
82
+ settled: true,
83
+ };
84
+ if (storage.swap) {
85
+ await storage.swap(key, raw, next);
86
+ return;
87
+ }
88
+ await storage.set(key, next);
89
+ }
90
+ //#endregion
91
+ //#region Dispatch
92
+ /** The durable storage of `parent`'s run, when it has a ledger: only then is a child linked. */
93
+ function durableStorageOf(parent) {
94
+ if (!(parent instanceof ContextImpl) || parent.ledger === undefined) {
95
+ return undefined;
96
+ }
97
+ return frameworkCast(parent.harness).config?.storage;
98
+ }
99
+ /**
100
+ * Dispatch a step to `adapter` for `parent`. A step the adapter runs out of process
101
+ * is an execution of its own: on a durable run it is linked to the run's root before
102
+ * it is dispatched, and the link is marked settled once the child finished (spec 23
103
+ * § Forgetting).
104
+ *
105
+ * @internal
106
+ */
107
+ export async function spawnLinked(parent, adapter, child) {
108
+ const storage = runsInProcess(adapter) ? undefined : durableStorageOf(parent);
109
+ if (!storage) {
110
+ return child.spawn();
111
+ }
112
+ noteAdapter(parent.harness, child.childId, adapter);
113
+ const key = childLinkKey(rootIdOf(frameworkCast(parent)), child.childId);
114
+ const link = {
115
+ stepId: child.stepId,
116
+ at: new Date().toISOString(),
117
+ from: child.from,
118
+ };
119
+ await storage.set(key, link);
120
+ const spawned = await child.spawn();
121
+ void spawned.settled
122
+ .catch(() => undefined)
123
+ .then(() => markSettled(storage, key))
124
+ .catch(() => undefined);
125
+ return spawned;
126
+ }
127
+ //#endregion
@@ -37,6 +37,11 @@ declare const SessionRecordSchema: z.ZodObject<{
37
37
  to: z.ZodString;
38
38
  }, z.core.$strip>>;
39
39
  accept: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>;
40
+ cut: z.ZodOptional<z.ZodObject<{
41
+ reason: z.ZodString;
42
+ count: z.ZodNumber;
43
+ at: z.ZodNumber;
44
+ }, z.core.$strip>>;
40
45
  parked: z.ZodOptional<z.ZodObject<{
41
46
  until: z.ZodOptional<z.ZodNumber>;
42
47
  }, z.core.$strip>>;
@@ -46,6 +51,8 @@ declare const SessionRecordSchema: z.ZodObject<{
46
51
  text: z.ZodString;
47
52
  executionId: z.ZodOptional<z.ZodString>;
48
53
  }, z.core.$strip>>>;
54
+ executions: z.ZodOptional<z.ZodArray<z.ZodString>>;
55
+ layers: z.ZodOptional<z.ZodArray<z.ZodString>>;
49
56
  steers: z.ZodOptional<z.ZodArray<z.ZodObject<{
50
57
  id: z.ZodString;
51
58
  input: z.ZodUnknown;
@@ -84,4 +91,8 @@ export interface SessionStore {
84
91
  }
85
92
  /** @internal */
86
93
  export declare function createSessionStore(storage: StorageAdapter): SessionStore;
94
+ /** @internal The prefix every thread's record key starts with. */
95
+ export declare const SESSION_PREFIX = "session:";
96
+ /** @internal The key a thread's record is stored under. */
97
+ export declare function sessionKey(threadId: string): string;
87
98
  export {};