@noetic-tools/core 5.21.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 (83) 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.js +8 -0
  30. package/dist/harness/model-rounds.d.ts +30 -0
  31. package/dist/harness/model-rounds.js +146 -1
  32. package/dist/harness/model-tool-round.d.ts +3 -0
  33. package/dist/harness/model-tool-round.js +201 -19
  34. package/dist/harness/park-watchers.d.ts +93 -0
  35. package/dist/harness/park-watchers.js +217 -0
  36. package/dist/harness/read-decision.d.ts +23 -0
  37. package/dist/harness/read-decision.js +100 -0
  38. package/dist/harness/spend.js +4 -0
  39. package/dist/harness/steer-inbox.js +3 -1
  40. package/dist/harness/thread-record.d.ts +77 -1
  41. package/dist/harness/thread-record.js +272 -13
  42. package/dist/index.d.ts +17 -7
  43. package/dist/index.js +10 -2
  44. package/dist/interpreter/acp-resume.d.ts +77 -0
  45. package/dist/interpreter/acp-resume.js +164 -0
  46. package/dist/interpreter/acp-tools.d.ts +11 -0
  47. package/dist/interpreter/acp-tools.js +94 -7
  48. package/dist/interpreter/connection-steps.d.ts +24 -1
  49. package/dist/interpreter/connection-steps.js +77 -2
  50. package/dist/interpreter/execute-acp-agent.js +111 -15
  51. package/dist/interpreter/execute-action.js +7 -0
  52. package/dist/interpreter/execute-call.js +30 -4
  53. package/dist/interpreter/execute-control.js +21 -0
  54. package/dist/interpreter/execute-invoke-tool.js +149 -5
  55. package/dist/interpreter/execute-wait.js +67 -9
  56. package/dist/interpreter/execute.js +4 -0
  57. package/dist/interpreter/turn-ending.d.ts +15 -0
  58. package/dist/interpreter/turn-ending.js +46 -0
  59. package/dist/portable/builders.d.ts +1 -1
  60. package/dist/portable/builders.js +1 -1
  61. package/dist/runtime/durable/parking.d.ts +61 -0
  62. package/dist/runtime/durable/parking.js +137 -0
  63. package/dist/runtime/durable/session-store.d.ts +38 -0
  64. package/dist/runtime/durable/session-store.js +79 -1
  65. package/dist/runtime/durable/step-ledger.d.ts +121 -2
  66. package/dist/runtime/durable/step-ledger.js +352 -15
  67. package/dist/runtime/durable/turn-lease.d.ts +128 -0
  68. package/dist/runtime/durable/turn-lease.js +307 -0
  69. package/dist/runtime/held-calls.d.ts +192 -0
  70. package/dist/runtime/held-calls.js +496 -0
  71. package/dist/runtime/in-memory-storage.d.ts +10 -1
  72. package/dist/runtime/in-memory-storage.js +20 -2
  73. package/dist/runtime/message-queue.d.ts +2 -0
  74. package/dist/runtime/message-queue.js +8 -0
  75. package/dist/runtime/session-runner.d.ts +18 -2
  76. package/dist/runtime/session-runner.js +88 -3
  77. package/dist/runtime/tool-approval.d.ts +46 -6
  78. package/dist/runtime/tool-approval.js +160 -38
  79. package/dist/runtime/tool-call.d.ts +34 -2
  80. package/dist/runtime/tool-call.js +182 -13
  81. package/dist/runtime/tool-context.d.ts +15 -1
  82. package/dist/runtime/tool-context.js +38 -2
  83. package/package.json +3 -3
@@ -1,6 +1,7 @@
1
1
  import type { ConnectionEntries, ConnectionStatus } from '@noetic-tools/types';
2
2
  import type { HarnessConnectionsOptions } from '../connections/harness-wiring.js';
3
3
  import type { ConnectionRuntime } from '../connections/registry.js';
4
+ import type { TriggerRunner } from '../connections/triggers.js';
4
5
  import type { Context, ContextLayer, Step, StorageAdapter, Tool } from './deps/types.js';
5
6
  /**
6
7
  * A harness's connections, as the harness drives them: providers and triggers,
@@ -63,6 +64,8 @@ export declare class ConnectionGate {
63
64
  readonly layers: ContextLayer[];
64
65
  bind(root: Context): void;
65
66
  };
67
+ /** The harness's triggers: its own, and those added while it runs. */
68
+ get triggers(): TriggerRunner;
66
69
  /** Connects providers and starts triggers. Idempotent. */
67
70
  start(): Promise<void>;
68
71
  /** Each connection's state, identity and pool usage; one entry for `name`, or all. */
@@ -136,6 +136,10 @@ export class ConnectionGate {
136
136
  },
137
137
  };
138
138
  }
139
+ /** The harness's triggers: its own, and those added while it runs. */
140
+ get triggers() {
141
+ return this.#connections.triggers;
142
+ }
139
143
  /** Connects providers and starts triggers. Idempotent. */
140
144
  async start() {
141
145
  await this.#connections.start();
@@ -7,11 +7,14 @@ export type { CheckpointStore } from '../../runtime/durable/checkpoint-store.js'
7
7
  export { createCheckpointStore } from '../../runtime/durable/checkpoint-store.js';
8
8
  export type { RestoreCheckpointOptions } from '../../runtime/durable/harness-checkpoints.js';
9
9
  export { captureCheckpoint, clearCheckpoint, restoreFromCheckpoint, } from '../../runtime/durable/harness-checkpoints.js';
10
+ export { DEFAULT_PARK_GRACE_MS, PARK_REASON } from '../../runtime/durable/parking.js';
10
11
  export type { SessionStore } from '../../runtime/durable/session-store.js';
11
12
  export { createSessionStore } from '../../runtime/durable/session-store.js';
12
13
  export { createSpendLog } from '../../runtime/durable/spend-log.js';
13
14
  export type { StepLedgerEntry, StepLedgerRetention, StepLedgerStore, } from '../../runtime/durable/step-ledger.js';
14
15
  export { createStepLedgerStore, resolveStepLedgerRetention, StepLedger, } from '../../runtime/durable/step-ledger.js';
16
+ export type { TurnLeaseOptions } from '../../runtime/durable/turn-lease.js';
17
+ export { canSwap, DEFAULT_LEASE_TTL_MS, heldElsewhere, heldElsewhereUntil, TurnLease, } from '../../runtime/durable/turn-lease.js';
15
18
  export type { EventBroadcaster } from '../../runtime/event-broadcaster.js';
16
19
  export { createInMemoryStorage } from '../../runtime/in-memory-storage.js';
17
20
  export { customItemGates } from '../../runtime/item-gates.js';
@@ -4,9 +4,11 @@ export { snapshotCwdState } from '../../runtime/cwd-helpers.js';
4
4
  export { Drains } from '../../runtime/drain.js';
5
5
  export { createCheckpointStore } from '../../runtime/durable/checkpoint-store.js';
6
6
  export { captureCheckpoint, clearCheckpoint, restoreFromCheckpoint, } from '../../runtime/durable/harness-checkpoints.js';
7
+ export { DEFAULT_PARK_GRACE_MS, PARK_REASON } from '../../runtime/durable/parking.js';
7
8
  export { createSessionStore } from '../../runtime/durable/session-store.js';
8
9
  export { createSpendLog } from '../../runtime/durable/spend-log.js';
9
10
  export { createStepLedgerStore, resolveStepLedgerRetention, StepLedger, } from '../../runtime/durable/step-ledger.js';
11
+ export { canSwap, DEFAULT_LEASE_TTL_MS, heldElsewhere, heldElsewhereUntil, TurnLease, } from '../../runtime/durable/turn-lease.js';
10
12
  export { createInMemoryStorage } from '../../runtime/in-memory-storage.js';
11
13
  export { customItemGates } from '../../runtime/item-gates.js';
12
14
  export { INTERRUPT_REASON, isSteer } from '../../runtime/message-queue.js';
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The version of a flow that runs JSON workflows, for a harness that was given no
3
+ * `version` (spec 23 § Versions): a hash of every document the flow can run, so
4
+ * an edited document is a new version without the host naming one.
5
+ */
6
+ import type { Step } from '@noetic-tools/types';
7
+ /**
8
+ * The version of the flows in `graph`: a hash of each JSON workflow document it
9
+ * runs and of the named workflows those can refer to, the same whatever order
10
+ * their keys were written in. Undefined when `graph` runs no JSON workflow, or one
11
+ * of its documents cannot be encoded.
12
+ */
13
+ export declare function flowVersionOf(graph: Step | undefined): string | undefined;
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The version of a flow that runs JSON workflows, for a harness that was given no
3
+ * `version` (spec 23 § Versions): a hash of every document the flow can run, so
4
+ * an edited document is a new version without the host naming one.
5
+ */
6
+ import { flowSourceOf } from '../builders/workflow-hydrator.js';
7
+ import { stepChildren } from '../interpreter/step-walk.js';
8
+ import { hashText } from '../runtime/durable/step-ledger.js';
9
+ //#region Helpers
10
+ /** Every step in the tree under `root`, itself included, as far as it is statically known. */
11
+ function stepsIn(root) {
12
+ const found = [];
13
+ const seen = new Set();
14
+ const queue = [
15
+ root,
16
+ ];
17
+ for (let next = queue.pop(); next !== undefined; next = queue.pop()) {
18
+ if (seen.has(next)) {
19
+ continue;
20
+ }
21
+ seen.add(next);
22
+ found.push(next);
23
+ queue.push(...stepChildren(next));
24
+ }
25
+ return found;
26
+ }
27
+ /** A plain object's entries in key order, so two spellings of one document hash alike. */
28
+ function sortKeys(_key, value) {
29
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
30
+ return value;
31
+ }
32
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
33
+ }
34
+ /** What of a flow's source goes into its version. */
35
+ function describe(source) {
36
+ return {
37
+ document: source.document ?? null,
38
+ ref: source.ref ?? null,
39
+ // A subflow `ref` runs one of these: an edit to it is an edit to the flow.
40
+ workflows: source.workflows ? Object.fromEntries(source.workflows) : null,
41
+ };
42
+ }
43
+ //#endregion
44
+ //#region Public API
45
+ /**
46
+ * The version of the flows in `graph`: a hash of each JSON workflow document it
47
+ * runs and of the named workflows those can refer to, the same whatever order
48
+ * their keys were written in. Undefined when `graph` runs no JSON workflow, or one
49
+ * of its documents cannot be encoded.
50
+ */
51
+ export function flowVersionOf(graph) {
52
+ if (!graph) {
53
+ return undefined;
54
+ }
55
+ const sources = stepsIn(graph).flatMap((step) => flowSourceOf(step) ?? []);
56
+ if (sources.length === 0) {
57
+ return undefined;
58
+ }
59
+ try {
60
+ return `workflow-${hashText(JSON.stringify(sources.map(describe), sortKeys))}`;
61
+ }
62
+ catch {
63
+ return undefined;
64
+ }
65
+ }
66
+ //#endregion
@@ -33,6 +33,72 @@ export interface StorageEnvironmentConfig {
33
33
  * never correctness.
34
34
  */
35
35
  stepLedgerRetention?: StepLedgerRetention;
36
+ /**
37
+ * The turn lease (spec 23 § One writer per turn). Used only when `adapter`
38
+ * implements `swap`: each session turn then takes its thread's lease, so two
39
+ * harnesses on one storage cannot both drive a turn, and a failed durable write
40
+ * stops the turn instead of being logged.
41
+ */
42
+ lease?: TurnLeaseConfig;
43
+ /**
44
+ * Park a turn when every step in flight is a wait that can be resumed without
45
+ * loss (spec 23 § Parked turns). The turn's lease is handed back, its response
46
+ * resolves with `parked`, and `harness.wake()` resumes it. Needs a lease, so it
47
+ * has no effect on storage without `swap`. Default `false`: a waiting turn holds
48
+ * its process. `true` uses `DEFAULT_PARK_GRACE_MS`.
49
+ */
50
+ park?: boolean | ParkConfig;
51
+ }
52
+ /**
53
+ * @public
54
+ * Hears the harness's next wake time when it changes (`harness.onWakeTimeChange`):
55
+ * epoch ms, or `undefined` when there is nothing to wake for.
56
+ */
57
+ export type WakeTimeListener = (at: number | undefined) => void | Promise<void>;
58
+ /** @public Settings for parking. */
59
+ export interface ParkConfig {
60
+ /**
61
+ * How long every step in flight must stay waiting before the turn parks, in ms.
62
+ * Keeps a turn whose event is about to arrive from parking and waking at once.
63
+ * Default `DEFAULT_PARK_GRACE_MS` (100).
64
+ */
65
+ graceMs?: number;
66
+ /**
67
+ * Whether this harness wakes the turns it parked: at their deadline, and when an
68
+ * event they wait for arrives on a harness connection. Default `true`, which
69
+ * suits a long-lived process. Set `false` where no process lives between
70
+ * requests; the host then calls `harness.wake()` itself.
71
+ */
72
+ autoWake?: boolean;
73
+ /**
74
+ * How long auto-wake waits after an event before waking the turn, in ms, so a
75
+ * burst of events wakes it once. Default `DEFAULT_WAKE_DEBOUNCE_MS` (250).
76
+ */
77
+ wakeDebounceMs?: number;
78
+ /**
79
+ * How often auto-wake reads the state of a long operation a parked turn's call
80
+ * waits on, in ms. Default `DEFAULT_TASK_POLL_MS` (5000).
81
+ */
82
+ taskPollMs?: number;
83
+ }
84
+ /** @public Settings for the turn lease. Every field has a default. */
85
+ export interface TurnLeaseConfig {
86
+ /** This harness's name in the lease record. Default: a random id per harness. */
87
+ holder?: string;
88
+ /**
89
+ * How long a lease lasts between renewals, in ms. It is renewed every third of
90
+ * this while a turn runs; a harness that goes quiet for longer can be replaced.
91
+ * Default `DEFAULT_LEASE_TTL_MS` (30 s).
92
+ */
93
+ ttlMs?: number;
94
+ /**
95
+ * How long a turn waits for a lease another harness holds, in ms, before it fails
96
+ * with `lease_lost`. A holder that died stops renewing, so waiting one `ttlMs`
97
+ * is enough to take over from it. Default: `ttlMs`.
98
+ */
99
+ waitMs?: number;
100
+ /** The clock leases are timed by. Default `Date.now`. */
101
+ now?: () => number;
36
102
  }
37
103
  /**
38
104
  * Execution-environment configuration for `AgentHarness`: the storage,
@@ -113,6 +179,22 @@ export interface AgentHarnessOpts<TParams extends Record<string, unknown> = Reco
113
179
  * the progress it missed.
114
180
  */
115
181
  emitItemsOnReplay?: boolean;
182
+ /**
183
+ * The version of the flow this harness runs: any string the host changes when the
184
+ * flow changes, such as a release tag or a hash (spec 23 § Versions). Every step a
185
+ * run records carries it, so the trail shows which version handled each step. A
186
+ * turn resumed under another version keeps the steps that still match, and stops
187
+ * as stuck rather than redo one that had a lasting effect. A flow hydrated
188
+ * from a JSON workflow (`hydrateWorkflow`) defaults to a hash of its document, so
189
+ * editing the document is a new version. Any other flow without one behaves as
190
+ * before: a resumed turn discards whatever no longer matches.
191
+ */
192
+ version?: string;
193
+ /**
194
+ * The clock wait deadlines, turn leases and wake times are read from. Default
195
+ * `Date.now`. A host that drives time itself (a test, a replay) passes its own.
196
+ */
197
+ now?: () => number;
116
198
  /**
117
199
  * Approves or refuses calls to tools that declare `needsApproval`, after the
118
200
  * `beforeToolCall` layers allow them. Without one, those calls run
@@ -317,6 +317,7 @@ export class AgentHarnessModelCaller {
317
317
  spans,
318
318
  modelSpan: null,
319
319
  steers,
320
+ calls: roundLedger?.calls(round),
320
321
  });
321
322
  await recordRound(spend.keep());
322
323
  }
@@ -528,6 +529,9 @@ export class AgentHarnessModelCaller {
528
529
  });
529
530
  allItems.push(...roundItems);
530
531
  replayOutput(conversationInput, roundItems);
532
+ // Let the round's cut records land first: each one prunes what is beneath the
533
+ // round's key, which is where the calls about to run are recorded.
534
+ await checkpoints;
531
535
  await runToolRound(this.toolRoundScope(), {
532
536
  roundItems,
533
537
  request,
@@ -538,6 +542,7 @@ export class AgentHarnessModelCaller {
538
542
  spans,
539
543
  modelSpan,
540
544
  steers,
545
+ calls: roundLedger?.calls(round),
541
546
  });
542
547
  await recordRound(bill);
543
548
  round += 1;
@@ -575,6 +580,8 @@ export class AgentHarnessModelCaller {
575
580
  });
576
581
  servedTier = sdkResponse.serviceTier ?? undefined;
577
582
  allItems.push(...roundItems);
583
+ // As above: no cut record may land after a call of this round is recorded.
584
+ await checkpoints;
578
585
  const ranTools = await runToolRound(this.toolRoundScope(), {
579
586
  roundItems,
580
587
  request,
@@ -585,6 +592,7 @@ export class AgentHarnessModelCaller {
585
592
  spans,
586
593
  modelSpan,
587
594
  steers,
595
+ calls: roundLedger?.calls(round),
588
596
  });
589
597
  // A steer staged while the final answer streamed gets its own round, so
590
598
  // the model answers it inside this call rather than in the next turn.
@@ -25,6 +25,30 @@
25
25
  * more.
26
26
  */
27
27
  import type { Item, ItemSchemaRegistry, RoundUsage } from '@noetic-tools/types';
28
+ import type { ToolCallResult } from '../runtime/tool-call.js';
29
+ /** A function call as the call ledger identifies it. */
30
+ interface CalledFunction {
31
+ callId: string;
32
+ name: string;
33
+ arguments: string;
34
+ }
35
+ /**
36
+ * The tool calls of one round, recorded one by one as they finish
37
+ * (spec 23a § Tool calls in a round).
38
+ */
39
+ export interface CallLedger {
40
+ /**
41
+ * Where in the run this round is: the model step's path and the round's number.
42
+ * The same on a resume, and what tells two calls with one call id apart.
43
+ */
44
+ readonly scope: string;
45
+ /** The recorded result of this call, when an earlier attempt of the round finished it. */
46
+ take(call: CalledFunction): ToolCallResult | undefined;
47
+ /** Record what the call produced. Resolves whether the record was stored. */
48
+ record(call: CalledFunction, result: ToolCallResult): Promise<boolean>;
49
+ /** Note that the call has a lasting effect: its record and its round's are marked so. */
50
+ noteEffect(call: CalledFunction): void;
51
+ }
28
52
  /** What one finished round added to the loop. */
29
53
  export interface RoundRecord {
30
54
  /** Model output items and tool result items, in the order the loop gathered them. */
@@ -71,6 +95,11 @@ export declare class RoundLedger {
71
95
  * stops at the first missing round, so the stale rounds past it are never read.
72
96
  */
73
97
  record(round: number, logMark: number, record: RoundRecord): Promise<boolean>;
98
+ /**
99
+ * The call ledger of round `round`. Each call is recorded beneath the round's key,
100
+ * so the round's own record prunes them once it lands.
101
+ */
102
+ calls(round: number): CallLedger;
74
103
  /** Drop the record of round `round`: the loop threw that round away. */
75
104
  drop(round: number): Promise<void>;
76
105
  /** Note that the rounds this loop recorded were charged to its context. */
@@ -79,3 +108,4 @@ export declare class RoundLedger {
79
108
  }
80
109
  /** @internal The ledger key of round `round` of the model loop at step path `path`. */
81
110
  export declare function roundPath(path: string, round: number): string;
111
+ export {};
@@ -27,9 +27,38 @@
27
27
  import { frameworkCast, isAssistantMessage } from '@noetic-tools/types';
28
28
  import { z } from 'zod';
29
29
  import { isFunctionCall } from '../interpreter/typeguards.js';
30
+ import { hashStepInput } from '../runtime/durable/step-ledger.js';
30
31
  import { ContextImpl } from './deps/runtime.js';
31
32
  //#region Types
32
33
  const ROUND_KIND = 'callModel:round';
34
+ const CALL_KIND = 'callModel:call';
35
+ /** What a recorded tool call left: the result the round went on with. */
36
+ const CallOutputSchema = z.object({
37
+ output: z.string(),
38
+ result: z.unknown().optional(),
39
+ /**
40
+ * `result` was left out because `output` holds the same thing: as text, or as
41
+ * its JSON. A record that kept both was twice the size of what it recorded.
42
+ */
43
+ resultAs: z
44
+ .enum([
45
+ 'text',
46
+ 'json',
47
+ ])
48
+ .optional(),
49
+ /** The id of the result item the call appended, which a replay appends again. */
50
+ itemId: z.string().optional(),
51
+ /** The tool's body ran, so its UI showed a call and how it ended. */
52
+ ran: z.boolean().optional(),
53
+ error: z.boolean().optional(),
54
+ approval: z
55
+ .enum([
56
+ 'approved',
57
+ 'denied',
58
+ 'none_configured',
59
+ ])
60
+ .optional(),
61
+ });
33
62
  const RoundOutputSchema = z.object({
34
63
  items: z.array(z.unknown()),
35
64
  input: z.array(z.unknown()),
@@ -152,9 +181,57 @@ export class RoundLedger {
152
181
  this.recorded.add(round);
153
182
  // A new record holds a bill no context has been charged with yet.
154
183
  chargedRounds.get(ledger)?.delete(this.key(round));
155
- await ledger.drop(this.key(round + 1));
184
+ // The next round's record, and the calls recorded beneath it, belong to the
185
+ // conversation an earlier attempt had. This one may ask for other calls.
186
+ await ledger.dropWithin(this.key(round + 1));
156
187
  return true;
157
188
  }
189
+ /**
190
+ * The call ledger of round `round`. Each call is recorded beneath the round's key,
191
+ * so the round's own record prunes them once it lands.
192
+ */
193
+ calls(round) {
194
+ const ledger = this.ctx.ledger;
195
+ const stepId = this.dispatch.stepId;
196
+ const keyOf = (call) => `${this.key(round)}/call:${call.callId}`;
197
+ // A call is the same call only with the same name and arguments, asked for by
198
+ // the same step input: a provider that numbers its calls from one each time
199
+ // would otherwise hand a call the result of another conversation's.
200
+ const hashOf = (call) => hashStepInput({
201
+ name: call.name,
202
+ arguments: call.arguments,
203
+ step: this.dispatch.inputHash,
204
+ });
205
+ return {
206
+ scope: this.key(round),
207
+ noteEffect: (call) => {
208
+ ledger?.noteEffect(keyOf(call));
209
+ ledger?.noteEffect(this.key(round));
210
+ },
211
+ take: (call) => {
212
+ const entry = ledger?.take(keyOf(call), {
213
+ id: stepId,
214
+ kind: CALL_KIND,
215
+ inputHash: hashOf(call),
216
+ });
217
+ const parsed = entry ? CallOutputSchema.safeParse(entry.output) : undefined;
218
+ return parsed?.success ? expandResult(parsed.data) : undefined;
219
+ },
220
+ record: async (call, result) => {
221
+ if (!ledger) {
222
+ return false;
223
+ }
224
+ return ledger.record({
225
+ path: keyOf(call),
226
+ stepId,
227
+ kind: CALL_KIND,
228
+ inputHash: hashOf(call),
229
+ output: compactResult(result),
230
+ completedAt: new Date().toISOString(),
231
+ });
232
+ },
233
+ };
234
+ }
158
235
  /** Drop the record of round `round`: the loop threw that round away. */
159
236
  async drop(round) {
160
237
  await this.ctx.ledger?.drop(this.key(round));
@@ -175,6 +252,74 @@ export class RoundLedger {
175
252
  return roundPath(this.dispatch.path, round);
176
253
  }
177
254
  }
255
+ /** What a call record stores: the result, with `result` left out where `output` says it. */
256
+ function compactResult(result) {
257
+ const kept = {
258
+ output: result.output,
259
+ ...(result.error === undefined
260
+ ? {}
261
+ : {
262
+ error: result.error,
263
+ }),
264
+ ...(result.approval === undefined
265
+ ? {}
266
+ : {
267
+ approval: result.approval,
268
+ }),
269
+ ...(result.itemId === undefined
270
+ ? {}
271
+ : {
272
+ itemId: result.itemId,
273
+ }),
274
+ ...(result.ran === undefined
275
+ ? {}
276
+ : {
277
+ ran: result.ran,
278
+ }),
279
+ };
280
+ if (result.result === undefined) {
281
+ return kept;
282
+ }
283
+ const resultAs = sameAsOutput(result.result, result.output);
284
+ return resultAs === undefined
285
+ ? {
286
+ ...kept,
287
+ result: result.result,
288
+ }
289
+ : {
290
+ ...kept,
291
+ resultAs,
292
+ };
293
+ }
294
+ /** How `output` holds `result`, or undefined when it does not. */
295
+ function sameAsOutput(result, output) {
296
+ if (typeof result === 'string') {
297
+ return result === output ? 'text' : undefined;
298
+ }
299
+ try {
300
+ return JSON.stringify(result) === output ? 'json' : undefined;
301
+ }
302
+ catch {
303
+ return undefined;
304
+ }
305
+ }
306
+ /** The result a call record stands for. */
307
+ function expandResult(stored) {
308
+ const { resultAs, ...result } = stored;
309
+ if (resultAs === 'text') {
310
+ return {
311
+ ...result,
312
+ result: result.output,
313
+ };
314
+ }
315
+ if (resultAs === 'json') {
316
+ return {
317
+ ...result,
318
+ result: JSON.parse(result.output),
319
+ };
320
+ }
321
+ return result;
322
+ }
178
323
  /** A cut round holding a function call or an answer has something to go on from. */
179
324
  function goesOn(item) {
180
325
  return isFunctionCall(item) || isAssistantMessage(item);
@@ -7,6 +7,7 @@ import type { AgentHarnessContract, CallModelRequest, Context, Item, ItemSchemaR
7
7
  import { itemsToInput } from '../adapters/openrouter.js';
8
8
  import type { CallSpanCollector } from './call-span-collector.js';
9
9
  import type { PreparedModelRequest } from './model-request.js';
10
+ import type { CallLedger } from './model-rounds.js';
10
11
  import type { SteerInbox } from './steer-inbox.js';
11
12
  /** What the tool round needs from the model caller that runs it. */
12
13
  export interface ToolRoundScope {
@@ -34,4 +35,6 @@ export declare function runToolRound(scope: ToolRoundScope, params: {
34
35
  spans: CallSpanCollector;
35
36
  modelSpan: Span | null;
36
37
  steers: SteerInbox | undefined;
38
+ /** Where the round's calls are recorded as they finish. */
39
+ calls?: CallLedger;
37
40
  }): Promise<boolean>;