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

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 (60) hide show
  1. package/dist/adapters/in-memory-subprocess-adapter.js +4 -2
  2. package/dist/adapters/openrouter.d.ts +6 -1
  3. package/dist/adapters/openrouter.js +10 -0
  4. package/dist/builders/custom-item.d.ts +1 -1
  5. package/dist/builders/custom-item.js +14 -3
  6. package/dist/builders/decide-builders.d.ts +7 -0
  7. package/dist/builders/tool-builder.d.ts +5 -1
  8. package/dist/builders/tool-builder.js +2 -0
  9. package/dist/builders/workflow-control-nodes.js +1 -0
  10. package/dist/connections/pool.d.ts +18 -0
  11. package/dist/connections/pool.js +54 -9
  12. package/dist/connections/registry.js +11 -0
  13. package/dist/harness/agent-harness.d.ts +130 -3
  14. package/dist/harness/agent-harness.js +337 -22
  15. package/dist/harness/decide-call.d.ts +15 -0
  16. package/dist/harness/decide-call.js +57 -7
  17. package/dist/harness/deps/types.d.ts +1 -1
  18. package/dist/harness/forget.d.ts +57 -0
  19. package/dist/harness/forget.js +496 -0
  20. package/dist/harness/harness-options.d.ts +24 -1
  21. package/dist/harness/llm-client.d.ts +2 -0
  22. package/dist/harness/llm-client.js +9 -5
  23. package/dist/harness/model-rounds.d.ts +6 -0
  24. package/dist/harness/model-rounds.js +7 -3
  25. package/dist/harness/model-tool-round.js +67 -8
  26. package/dist/harness/recorded-tool-calls.d.ts +16 -0
  27. package/dist/harness/recorded-tool-calls.js +106 -0
  28. package/dist/harness/spend.d.ts +13 -1
  29. package/dist/harness/spend.js +82 -1
  30. package/dist/harness/steer-inbox.js +9 -5
  31. package/dist/harness/thread-record.d.ts +12 -1
  32. package/dist/harness/thread-record.js +63 -19
  33. package/dist/index.d.ts +9 -6
  34. package/dist/index.js +4 -3
  35. package/dist/interpreter/acp-tools.js +21 -4
  36. package/dist/interpreter/execute-action.js +7 -1
  37. package/dist/interpreter/execute-decide.js +5 -0
  38. package/dist/interpreter/execute.js +55 -3
  39. package/dist/interpreter/step-dispatcher.js +17 -1
  40. package/dist/interpreter/step-kind-dispatch.js +9 -1
  41. package/dist/portable/runtime.d.ts +4 -0
  42. package/dist/portable/runtime.js +2 -0
  43. package/dist/runtime/durable/child-links.d.ts +61 -0
  44. package/dist/runtime/durable/child-links.js +127 -0
  45. package/dist/runtime/durable/session-store.d.ts +6 -0
  46. package/dist/runtime/durable/session-store.js +16 -2
  47. package/dist/runtime/durable/turn-lease.d.ts +10 -0
  48. package/dist/runtime/durable/turn-lease.js +10 -2
  49. package/dist/runtime/event-broadcaster.d.ts +9 -1
  50. package/dist/runtime/event-broadcaster.js +16 -1
  51. package/dist/runtime/held-calls.d.ts +65 -6
  52. package/dist/runtime/held-calls.js +257 -5
  53. package/dist/runtime/output-store.d.ts +90 -0
  54. package/dist/runtime/output-store.js +243 -0
  55. package/dist/runtime/session-streams.d.ts +28 -7
  56. package/dist/runtime/session-streams.js +112 -67
  57. package/dist/runtime/tool-approval.d.ts +1 -3
  58. package/dist/runtime/tool-approval.js +1 -1
  59. package/package.json +2 -2
  60. package/schema/noetic-workflow.schema.json +27 -0
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 */
@@ -130,6 +129,10 @@ export { DEFAULT_PARK_GRACE_MS } from './runtime/durable/parking.js';
130
129
  /** @public */
131
130
  export { DEFAULT_LEASE_TTL_MS } from './runtime/durable/turn-lease.js';
132
131
  /** @public */
132
+ export type { OutputSnapshot } from './runtime/output-store.js';
133
+ /** @public */
134
+ export { OutputStore, OutputStoreError } from './runtime/output-store.js';
135
+ /** @public */
133
136
  export { getRegistry, lookupStep, registerStep } from './runtime/step-registry.js';
134
137
  /** @public */
135
138
  export type { Expression } from '@noetic-tools/types';
@@ -144,7 +147,7 @@ export { MergeStrategySchema, UntilPredicateSchema, validateWorkflow, WorkflowDo
144
147
  export type { Channel, ChannelHandle, ExternalChannel } from '@noetic-tools/types';
145
148
  /** @public */
146
149
  /** @public */
147
- export type { InferSchemaInput, InferSchemaOutput, InputSchemaConfig, LLMResponse, LlmProviderConfig, ModelParams, RetryPolicy, RoundUsage, SchemaValidationFailure, SchemaValidationResult, SchemaValidationSuccess, ServerToolSpec, StandardJSONSchemaV1, StandardSchemaV1, StepMeta, TokenUsage, Tool, ToolChoice, ToolContextDeclaration, UsageCharge, } from '@noetic-tools/types';
150
+ export type { InferSchemaInput, InferSchemaOutput, InputSchemaConfig, LLMResponse, LlmProviderConfig, ModelParams, RetryPolicy, RoundUsage, SchemaValidationFailure, SchemaValidationResult, SchemaValidationSuccess, ServerToolSpec, StandardJSONSchemaV1, StandardSchemaV1, StepMeta, TokenUsage, Tool, ToolChoice, ToolContextDeclaration, ToolModelOutput, UsageCharge, } from '@noetic-tools/types';
148
151
  /** @public */
149
152
  export { isServerToolSpec, isStandardJsonSchema, isZodSchema, ServiceTier, standardIssuesToZodError, ToolChoiceMode, validateSchema, } from '@noetic-tools/types';
150
153
  /** @public */
@@ -178,11 +181,11 @@ export type { LayerTraceSpan, Span, TraceExporter } from '@noetic-tools/types';
178
181
  /** @public */
179
182
  export type { FrameworkStreamEvent, HarnessResponse, SdkStreamEvent, StreamEvent, StreamingItem, } from '@noetic-tools/types';
180
183
  /** @public */
181
- 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, StuckTurn, ToolHold, TrailMark, } from '@noetic-tools/types';
182
185
  /** @public */
183
- 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';
184
187
  /** @public */
185
- export { SpendKind } from '@noetic-tools/types';
188
+ export { ExecutionPart, SpendKind } from '@noetic-tools/types';
186
189
  /** @public */
187
190
  export type { AfterModelCallParams, AfterModelCallResult, ApproveRequest, ApproveToolCallParams, BeforeToolCallParams, BeforeToolCallResult, LedgerEntry, OnSteerParams, OnSteerResult, Steer, SteeringConfig, SteeringDecision, SteeringRule, SteeringState, SteerVerdict, ToolApprover, } from '@noetic-tools/types';
188
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
@@ -102,6 +101,8 @@ export { DEFAULT_PARK_GRACE_MS } from './runtime/durable/parking.js';
102
101
  /** @public */
103
102
  export { DEFAULT_LEASE_TTL_MS } from './runtime/durable/turn-lease.js';
104
103
  /** @public */
104
+ export { OutputStore, OutputStoreError } from './runtime/output-store.js';
105
+ /** @public */
105
106
  export { getRegistry, lookupStep, registerStep } from './runtime/step-registry.js';
106
107
  /** @public */
107
108
  /** @public */
@@ -119,7 +120,7 @@ export { ChannelSnapshotSchema, CheckpointSchemaVersion, CheckpointSnapshotSchem
119
120
  /** @public */
120
121
  export { Slot } from '@noetic-tools/context';
121
122
  /** @public */
122
- export { SpendKind } from '@noetic-tools/types';
123
+ export { ExecutionPart, SpendKind } from '@noetic-tools/types';
123
124
  /** @public */
124
125
  export { LedgerEntryKind, SteerAction, SteeringAction, SteerPoint } from '@noetic-tools/types';
125
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));
@@ -42,6 +42,11 @@ export async function executeDecide(step, input, ctx, layers) {
42
42
  state,
43
43
  questions: step.questions,
44
44
  samples: step.samples,
45
+ ...(step.headers
46
+ ? {
47
+ headers: step.headers,
48
+ }
49
+ : {}),
45
50
  signal: isContextImpl(baseCtx) ? baseCtx.abortSignal : undefined,
46
51
  parentSpan: span,
47
52
  _billTo: baseCtx,
@@ -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
  }
@@ -2,3 +2,7 @@
2
2
  export { AgentHarness } from '../harness/agent-harness.js';
3
3
  /** @public */
4
4
  export { createInMemoryStorage } from '../runtime/in-memory-storage.js';
5
+ /** @public */
6
+ export type { OutputSnapshot } from '../runtime/output-store.js';
7
+ /** @public */
8
+ export { OutputStore, OutputStoreError } from '../runtime/output-store.js';
@@ -2,3 +2,5 @@
2
2
  export { AgentHarness } from '../harness/agent-harness.js';
3
3
  /** @public */
4
4
  export { createInMemoryStorage } from '../runtime/in-memory-storage.js';
5
+ /** @public */
6
+ export { OutputStore, OutputStoreError } from '../runtime/output-store.js';
@@ -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
@@ -46,6 +46,8 @@ declare const SessionRecordSchema: z.ZodObject<{
46
46
  text: z.ZodString;
47
47
  executionId: z.ZodOptional<z.ZodString>;
48
48
  }, z.core.$strip>>>;
49
+ executions: z.ZodOptional<z.ZodArray<z.ZodString>>;
50
+ layers: z.ZodOptional<z.ZodArray<z.ZodString>>;
49
51
  steers: z.ZodOptional<z.ZodArray<z.ZodObject<{
50
52
  id: z.ZodString;
51
53
  input: z.ZodUnknown;
@@ -84,4 +86,8 @@ export interface SessionStore {
84
86
  }
85
87
  /** @internal */
86
88
  export declare function createSessionStore(storage: StorageAdapter): SessionStore;
89
+ /** @internal The prefix every thread's record key starts with. */
90
+ export declare const SESSION_PREFIX = "session:";
91
+ /** @internal The key a thread's record is stored under. */
92
+ export declare function sessionKey(threadId: string): string;
87
93
  export {};
@@ -92,6 +92,18 @@ const SessionRecordSchema = z.object({
92
92
  executionId: z.string().optional(),
93
93
  }))
94
94
  .optional(),
95
+ /**
96
+ * Every execution the thread began a turn on, oldest first. `done` keeps only the
97
+ * last few turns; this is how a forget (spec 23 § Forgetting) and the thread's trail
98
+ * find the older ones. Absent in records written before it was kept.
99
+ */
100
+ executions: z.array(z.string()).optional(),
101
+ /**
102
+ * Ids of the context layers whose state may be kept at the thread's scope key, so a
103
+ * forget on a harness that never ran the thread still finds it. Absent in records
104
+ * written before it was kept.
105
+ */
106
+ layers: z.array(z.string()).optional(),
95
107
  /** Steers sent into the turn in flight, in arrival order. */
96
108
  steers: z
97
109
  .array(z.object({
@@ -145,8 +157,10 @@ export function createSessionStore(storage) {
145
157
  threads: async () => (await storage.list(SESSION_PREFIX)).map((key) => key.slice(SESSION_PREFIX.length)),
146
158
  };
147
159
  }
148
- const SESSION_PREFIX = 'session:';
149
- function sessionKey(threadId) {
160
+ /** @internal The prefix every thread's record key starts with. */
161
+ export const SESSION_PREFIX = 'session:';
162
+ /** @internal The key a thread's record is stored under. */
163
+ export function sessionKey(threadId) {
150
164
  return `${SESSION_PREFIX}${threadId}`;
151
165
  }
152
166
  //#endregion
@@ -58,6 +58,14 @@ export interface LedgerFence {
58
58
  }
59
59
  /** @internal True when `storage` can compare-and-set. */
60
60
  export declare function canSwap(storage: StorageAdapter | undefined): storage is SwapStorage;
61
+ /**
62
+ * @internal
63
+ * A prefix of its own. Under `session:`, the lease of thread `a` and the session
64
+ * of a thread named `a:lease` would be one key.
65
+ */
66
+ export declare function leaseKey(threadId: string): string;
67
+ /** @internal The prefix every thread's lease key starts with. */
68
+ export declare const LEASE_PREFIX = "turn-lease:";
61
69
  /** @internal True when a harness other than `opts.holder` holds the thread's lease now. */
62
70
  /**
63
71
  * @internal
@@ -119,6 +127,8 @@ export declare class TurnLease implements LedgerFence {
119
127
  renew(): Promise<void>;
120
128
  private renewOnce;
121
129
  verify(): Promise<void>;
130
+ /** Stop renewing, and wait for a renewal in flight, keeping the lease as it stands. */
131
+ stop(): Promise<void>;
122
132
  /** Hand the lease back so the next turn need not wait for it to run out. */
123
133
  release(): Promise<void>;
124
134
  private markLost;
@@ -52,12 +52,15 @@ function isHeldBy(record, holder, now) {
52
52
  return record !== null && record.holder !== holder && record.heldUntil > now;
53
53
  }
54
54
  /**
55
+ * @internal
55
56
  * A prefix of its own. Under `session:`, the lease of thread `a` and the session
56
57
  * of a thread named `a:lease` would be one key.
57
58
  */
58
- function leaseKey(threadId) {
59
- return `turn-lease:${threadId}`;
59
+ export function leaseKey(threadId) {
60
+ return `${LEASE_PREFIX}${threadId}`;
60
61
  }
62
+ /** @internal The prefix every thread's lease key starts with. */
63
+ export const LEASE_PREFIX = 'turn-lease:';
61
64
  /**
62
65
  * The term to take the lease at. It only ever goes up: a lease that went back to
63
66
  * term 1 would lose every write to the entries a higher term left in the ledger,
@@ -261,6 +264,11 @@ export class TurnLease {
261
264
  }
262
265
  this.assert();
263
266
  }
267
+ /** Stop renewing, and wait for a renewal in flight, keeping the lease as it stands. */
268
+ async stop() {
269
+ this.stopTimer();
270
+ await this.renewing;
271
+ }
264
272
  /** Hand the lease back so the next turn need not wait for it to run out. */
265
273
  async release() {
266
274
  this.stopTimer();
@@ -1,4 +1,5 @@
1
1
  import type { StreamEvent } from '@noetic-tools/types';
2
+ type Observer = (event: StreamEvent) => void;
2
3
  interface EventBroadcasterOpts {
3
4
  maxBufferSize?: number;
4
5
  }
@@ -24,8 +25,15 @@ export declare class EventBroadcaster {
24
25
  private err?;
25
26
  private readonly iterators;
26
27
  private hasHadConsumers;
28
+ private readonly observers;
27
29
  constructor(opts?: EventBroadcasterOpts);
28
- /** Push an event to all active iterators and the replay buffer. */
30
+ /**
31
+ * Hear every event as it is emitted, whether or not a consumer is attached: the
32
+ * replay buffer stops filling once every consumer has left, an observer does not.
33
+ * Nothing is replayed to it. Returns the function that stops it.
34
+ */
35
+ observe(observer: Observer): () => void;
36
+ /** Push an event to every observer, all active iterators and the replay buffer. */
29
37
  emit(event: StreamEvent): void;
30
38
  /** Signal that no more events will be emitted. */
31
39
  complete(): void;