@noetic-tools/core 5.12.0 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/in-memory-subprocess/step-completion.d.ts +2 -2
- package/dist/adapters/in-memory-subprocess/step-completion.js +48 -52
- package/dist/adapters/in-memory-subprocess/types.d.ts +3 -6
- package/dist/adapters/in-memory-subprocess-adapter.js +30 -48
- package/dist/adapters/live-handles.d.ts +26 -0
- package/dist/adapters/live-handles.js +50 -0
- package/dist/builders/workflow-hydrator.js +1 -3
- package/dist/harness/agent-harness.d.ts +52 -5
- package/dist/harness/agent-harness.js +175 -25
- package/dist/harness/deps/runtime.d.ts +4 -0
- package/dist/harness/deps/runtime.js +2 -0
- package/dist/harness/model-call.js +69 -0
- package/dist/harness/model-rounds.d.ts +52 -0
- package/dist/harness/model-rounds.js +115 -0
- package/dist/harness/thread-record.d.ts +54 -0
- package/dist/harness/thread-record.js +159 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +2 -0
- package/dist/interpreter/execute-action.js +3 -0
- package/dist/interpreter/execute-control.js +3 -0
- package/dist/interpreter/execute.js +59 -12
- package/dist/interpreter/step-dispatcher.d.ts +2 -2
- package/dist/interpreter/step-dispatcher.js +3 -5
- package/dist/runtime/context-impl.d.ts +93 -4
- package/dist/runtime/context-impl.js +191 -14
- package/dist/runtime/durable/harness-checkpoints.d.ts +13 -3
- package/dist/runtime/durable/harness-checkpoints.js +66 -7
- package/dist/runtime/durable/session-store.d.ts +37 -0
- package/dist/runtime/durable/session-store.js +58 -0
- package/dist/runtime/durable/step-ledger.d.ts +76 -40
- package/dist/runtime/durable/step-ledger.js +188 -73
- package/dist/runtime/item-log-impl.d.ts +6 -0
- package/dist/runtime/item-log-impl.js +12 -0
- package/dist/runtime/session-runner.d.ts +25 -1
- package/dist/runtime/session-runner.js +83 -11
- package/dist/types/checkpoint.d.ts +21 -4
- package/dist/types/checkpoint.js +33 -3
- package/dist/util/detached-handle.d.ts +9 -20
- package/dist/util/detached-handle.js +7 -108
- package/package.json +2 -2
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable sessions: what lets a new harness pick up a thread that `execute()` drove on
|
|
3
|
+
* an earlier one. See `runtime/durable/session-store` for the stored shape.
|
|
4
|
+
*
|
|
5
|
+
* Storage is the only record. Nothing here is cached between calls: every turn reads
|
|
6
|
+
* the thread's history and in-flight turn from the store, and every change is a
|
|
7
|
+
* read-modify-write of the stored record, so a harness that served the last turn and
|
|
8
|
+
* a harness built a moment ago behave the same.
|
|
9
|
+
*/
|
|
10
|
+
import type { Context, Item, SessionUsage } from '@noetic-tools/types';
|
|
11
|
+
import type { RestoreCheckpointOptions, SessionStore, TurnUsage } from './deps/runtime.js';
|
|
12
|
+
/** @internal The harness surface a thread record needs. */
|
|
13
|
+
export interface ThreadRecordHost {
|
|
14
|
+
readonly store: SessionStore;
|
|
15
|
+
restore(executionId: string, opts: RestoreCheckpointOptions): Promise<Context | null>;
|
|
16
|
+
clearCheckpoint(executionId: string): Promise<void>;
|
|
17
|
+
parseItems(raw: unknown[]): Item[];
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* @internal
|
|
21
|
+
* One thread's stored session. Turns call `history` → `resume` → `begin` → `end`; a
|
|
22
|
+
* turn that throws never reaches `end`, so its record stays for a re-delivery of the
|
|
23
|
+
* same messages to resume. Operations run one at a time, in call order, so a read
|
|
24
|
+
* never overtakes a write issued before it.
|
|
25
|
+
*/
|
|
26
|
+
export declare class ThreadRecord {
|
|
27
|
+
private readonly host;
|
|
28
|
+
private readonly threadId;
|
|
29
|
+
private queue;
|
|
30
|
+
constructor(host: ThreadRecordHost, threadId: string);
|
|
31
|
+
/** The history the thread's next turn builds on: what storage holds, or none. */
|
|
32
|
+
history(): Promise<Item[]>;
|
|
33
|
+
/** Replace the stored history (`seedSessionHistory`). */
|
|
34
|
+
seed(items: ReadonlyArray<Item>): Promise<void>;
|
|
35
|
+
/**
|
|
36
|
+
* The context of the cut-off turn, when `messageIds` re-deliver exactly its
|
|
37
|
+
* messages. A cut-off turn that is not re-delivered is abandoned: its record is
|
|
38
|
+
* dropped, its checkpoint cleared, and the new messages start a fresh turn.
|
|
39
|
+
*/
|
|
40
|
+
resume(messageIds: ReadonlyArray<string>, opts: RestoreCheckpointOptions): Promise<Context | undefined>;
|
|
41
|
+
/** Record the turn about to run on `ctx`, before any of it runs. */
|
|
42
|
+
begin(ctx: Context, messageIds: ReadonlyArray<string>): Promise<void>;
|
|
43
|
+
/** The turn on `ctx` finished: store the history it left and drop its checkpoint. */
|
|
44
|
+
end(ctx: Context, history: ReadonlyArray<Item>): Promise<void>;
|
|
45
|
+
/** Add one turn's spend to the stored totals, and return the totals now stored. */
|
|
46
|
+
addUsage(spent: TurnUsage): Promise<SessionUsage>;
|
|
47
|
+
/** The stored totals. */
|
|
48
|
+
usage(): Promise<SessionUsage>;
|
|
49
|
+
private update;
|
|
50
|
+
/** Read-modify-write the stored record. Call only from inside `run`. */
|
|
51
|
+
private write;
|
|
52
|
+
private load;
|
|
53
|
+
private run;
|
|
54
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable sessions: what lets a new harness pick up a thread that `execute()` drove on
|
|
3
|
+
* an earlier one. See `runtime/durable/session-store` for the stored shape.
|
|
4
|
+
*
|
|
5
|
+
* Storage is the only record. Nothing here is cached between calls: every turn reads
|
|
6
|
+
* the thread's history and in-flight turn from the store, and every change is a
|
|
7
|
+
* read-modify-write of the stored record, so a harness that served the last turn and
|
|
8
|
+
* a harness built a moment ago behave the same.
|
|
9
|
+
*/
|
|
10
|
+
const EMPTY_USAGE = {
|
|
11
|
+
inputTokens: 0,
|
|
12
|
+
outputTokens: 0,
|
|
13
|
+
};
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region ThreadRecord
|
|
16
|
+
/**
|
|
17
|
+
* @internal
|
|
18
|
+
* One thread's stored session. Turns call `history` → `resume` → `begin` → `end`; a
|
|
19
|
+
* turn that throws never reaches `end`, so its record stays for a re-delivery of the
|
|
20
|
+
* same messages to resume. Operations run one at a time, in call order, so a read
|
|
21
|
+
* never overtakes a write issued before it.
|
|
22
|
+
*/
|
|
23
|
+
export class ThreadRecord {
|
|
24
|
+
host;
|
|
25
|
+
threadId;
|
|
26
|
+
queue = Promise.resolve();
|
|
27
|
+
constructor(host, threadId) {
|
|
28
|
+
this.host = host;
|
|
29
|
+
this.threadId = threadId;
|
|
30
|
+
}
|
|
31
|
+
/** The history the thread's next turn builds on: what storage holds, or none. */
|
|
32
|
+
history() {
|
|
33
|
+
return this.run(async () => this.host.parseItems((await this.load())?.items ?? []));
|
|
34
|
+
}
|
|
35
|
+
/** Replace the stored history (`seedSessionHistory`). */
|
|
36
|
+
seed(items) {
|
|
37
|
+
return this.update((record) => ({
|
|
38
|
+
...record,
|
|
39
|
+
items: [
|
|
40
|
+
...items,
|
|
41
|
+
],
|
|
42
|
+
}));
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The context of the cut-off turn, when `messageIds` re-deliver exactly its
|
|
46
|
+
* messages. A cut-off turn that is not re-delivered is abandoned: its record is
|
|
47
|
+
* dropped, its checkpoint cleared, and the new messages start a fresh turn.
|
|
48
|
+
*/
|
|
49
|
+
resume(messageIds, opts) {
|
|
50
|
+
return this.run(async () => {
|
|
51
|
+
const turn = (await this.load())?.turn;
|
|
52
|
+
if (!turn) {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
if (sameIds(turn.messageIds, messageIds)) {
|
|
56
|
+
return (await this.host.restore(turn.executionId, opts)) ?? undefined;
|
|
57
|
+
}
|
|
58
|
+
await this.write(withoutTurn);
|
|
59
|
+
await this.host.clearCheckpoint(turn.executionId);
|
|
60
|
+
return undefined;
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/** Record the turn about to run on `ctx`, before any of it runs. */
|
|
64
|
+
begin(ctx, messageIds) {
|
|
65
|
+
return this.update((record) => ({
|
|
66
|
+
...record,
|
|
67
|
+
turn: {
|
|
68
|
+
executionId: ctx.id,
|
|
69
|
+
messageIds: [
|
|
70
|
+
...messageIds,
|
|
71
|
+
],
|
|
72
|
+
},
|
|
73
|
+
}));
|
|
74
|
+
}
|
|
75
|
+
/** The turn on `ctx` finished: store the history it left and drop its checkpoint. */
|
|
76
|
+
async end(ctx, history) {
|
|
77
|
+
await this.update((record) => ({
|
|
78
|
+
...withoutTurn(record),
|
|
79
|
+
items: [
|
|
80
|
+
...history,
|
|
81
|
+
],
|
|
82
|
+
}));
|
|
83
|
+
await this.host.clearCheckpoint(ctx.id);
|
|
84
|
+
}
|
|
85
|
+
/** Add one turn's spend to the stored totals, and return the totals now stored. */
|
|
86
|
+
addUsage(spent) {
|
|
87
|
+
return this.run(async () => {
|
|
88
|
+
const usage = addUsage((await this.load())?.usage ?? EMPTY_USAGE, spent);
|
|
89
|
+
await this.write((record) => ({
|
|
90
|
+
...record,
|
|
91
|
+
usage,
|
|
92
|
+
}));
|
|
93
|
+
return usage;
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
/** The stored totals. */
|
|
97
|
+
usage() {
|
|
98
|
+
return this.run(async () => (await this.load())?.usage ?? EMPTY_USAGE);
|
|
99
|
+
}
|
|
100
|
+
update(change) {
|
|
101
|
+
return this.run(() => this.write(change));
|
|
102
|
+
}
|
|
103
|
+
/** Read-modify-write the stored record. Call only from inside `run`. */
|
|
104
|
+
async write(change) {
|
|
105
|
+
const record = change((await this.load()) ?? {
|
|
106
|
+
items: [],
|
|
107
|
+
});
|
|
108
|
+
try {
|
|
109
|
+
await this.host.store.save(this.threadId, record);
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
// Same rule as checkpoints: losing the record costs resumability, not the turn.
|
|
113
|
+
console.warn(`AgentHarness: failed to persist session "${this.threadId}":`, error instanceof Error ? error.message : String(error));
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
load() {
|
|
117
|
+
return this.host.store.load(this.threadId);
|
|
118
|
+
}
|
|
119
|
+
run(op) {
|
|
120
|
+
const next = this.queue.then(op);
|
|
121
|
+
this.queue = next.catch(() => { });
|
|
122
|
+
return next;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
function withoutTurn(record) {
|
|
126
|
+
const { turn, ...rest } = record;
|
|
127
|
+
void turn;
|
|
128
|
+
return rest;
|
|
129
|
+
}
|
|
130
|
+
function sameIds(a, b) {
|
|
131
|
+
return a.length === b.length && a.every((id, i) => id === b[i]);
|
|
132
|
+
}
|
|
133
|
+
function addUsage(total, spent) {
|
|
134
|
+
const cost = (total.cost ?? 0) + spent.cost;
|
|
135
|
+
const billedCost = (total.billedCost ?? 0) + spent.billedCost;
|
|
136
|
+
const cachedTokens = spent.cachedTokens === undefined
|
|
137
|
+
? total.cachedTokens
|
|
138
|
+
: (total.cachedTokens ?? 0) + spent.cachedTokens;
|
|
139
|
+
return {
|
|
140
|
+
inputTokens: total.inputTokens + spent.inputTokens,
|
|
141
|
+
outputTokens: total.outputTokens + spent.outputTokens,
|
|
142
|
+
...(cachedTokens !== undefined
|
|
143
|
+
? {
|
|
144
|
+
cachedTokens,
|
|
145
|
+
}
|
|
146
|
+
: {}),
|
|
147
|
+
...(cost > 0
|
|
148
|
+
? {
|
|
149
|
+
cost,
|
|
150
|
+
}
|
|
151
|
+
: {}),
|
|
152
|
+
...(billedCost > 0
|
|
153
|
+
? {
|
|
154
|
+
billedCost,
|
|
155
|
+
}
|
|
156
|
+
: {}),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
//#endregion
|
package/dist/index.d.ts
CHANGED
|
@@ -181,11 +181,15 @@ export { ACP_AGENT_STEP_KIND, AcpCapabilityError, AcpConnectError, AcpPermission
|
|
|
181
181
|
export type { FsAdapter, FsStats } from '@noetic-tools/types';
|
|
182
182
|
/** @public */
|
|
183
183
|
/** @public */
|
|
184
|
-
export type { ProcessSubprocessRequest, SerializedError, ShellAdapter, ShellExecOptions, ShellExecResult, StepSubprocessOverrides, StepSubprocessRequest, SubprocessAdapter, SubprocessControlResult, SubprocessHandle, SubprocessHandleMetadata, SubprocessRequest, SubprocessStatus, SubprocessStopResult, } from '@noetic-tools/types';
|
|
184
|
+
export type { ProcessSubprocessRequest, SerializedError, ShellAdapter, ShellExecOptions, ShellExecResult, SpawnedSubprocess, StepSubprocessOverrides, StepSubprocessRequest, SubprocessAdapter, SubprocessControlResult, SubprocessHandle, SubprocessHandleMetadata, SubprocessRequest, SubprocessStatus, SubprocessStopResult, } from '@noetic-tools/types';
|
|
185
185
|
/** @public */
|
|
186
186
|
export { TIMEOUT_ERROR_PREFIX } from '@noetic-tools/types';
|
|
187
187
|
/** @public Reusable error-serialiser used by custom SubprocessAdapter implementations. */
|
|
188
188
|
export { serializeError } from './adapters/in-memory-subprocess/metadata.js';
|
|
189
|
+
/** @public Running-handle table that custom SubprocessAdapter implementations settle through. */
|
|
190
|
+
export type { LiveHandles } from './adapters/live-handles.js';
|
|
191
|
+
/** @public */
|
|
192
|
+
export { createLiveHandles } from './adapters/live-handles.js';
|
|
189
193
|
/** @public */
|
|
190
194
|
export type { ToolContext, ToolExecutionContext } from '@noetic-tools/types';
|
|
191
195
|
/** @public */
|
package/dist/index.js
CHANGED
|
@@ -110,6 +110,8 @@ export { ACP_AGENT_STEP_KIND, AcpCapabilityError, AcpConnectError, AcpPermission
|
|
|
110
110
|
export { TIMEOUT_ERROR_PREFIX } from '@noetic-tools/types';
|
|
111
111
|
/** @public Reusable error-serialiser used by custom SubprocessAdapter implementations. */
|
|
112
112
|
export { serializeError } from './adapters/in-memory-subprocess/metadata.js';
|
|
113
|
+
/** @public */
|
|
114
|
+
export { createLiveHandles } from './adapters/live-handles.js';
|
|
113
115
|
//#endregion
|
|
114
116
|
//#region Until
|
|
115
117
|
/** @public */
|
|
@@ -439,6 +439,7 @@ function recordTurnOutcome(params) {
|
|
|
439
439
|
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
440
440
|
usage: response.usage,
|
|
441
441
|
cost: response.cost,
|
|
442
|
+
billedCost: response.billedCost,
|
|
442
443
|
serviceTier: response.serviceTier,
|
|
443
444
|
responseItems: response.items,
|
|
444
445
|
};
|
|
@@ -736,6 +737,8 @@ export async function executeSpawn(step, input, ctx, executeStep, opts) {
|
|
|
736
737
|
// with the ones recorded inside the same spawn rather than at the root.
|
|
737
738
|
pathPrefix: baseCtx instanceof ContextImpl ? baseCtx.currentPath() : '',
|
|
738
739
|
ledger: baseCtx instanceof ContextImpl ? baseCtx.ledger : undefined,
|
|
740
|
+
// The child's steps checkpoint the root, as an inParallel path's do.
|
|
741
|
+
checkpointFn: () => baseCtx.checkpoint(),
|
|
739
742
|
});
|
|
740
743
|
// `childExecutionCtx` predates the spawn span; the child's hooks trace onto that span.
|
|
741
744
|
const childTracedCtx = {
|
|
@@ -42,6 +42,9 @@ function createChildContexts(ctx, paths, stepId) {
|
|
|
42
42
|
* restart at the root and collide with its siblings. */
|
|
43
43
|
pathPrefix: `${parentPath}[${index}]`,
|
|
44
44
|
ledger: parentLedger,
|
|
45
|
+
// A path's steps checkpoint the root: its usage, state, and layer folds roll
|
|
46
|
+
// into what a resumed root restores.
|
|
47
|
+
checkpointFn: () => ctx.checkpoint(),
|
|
45
48
|
items: [
|
|
46
49
|
...ctx.itemLog.items,
|
|
47
50
|
],
|
|
@@ -81,12 +81,10 @@ async function dispatchViaAdapter(step, input, ctx, executionId, executor) {
|
|
|
81
81
|
},
|
|
82
82
|
_localExecutor: () => executor(),
|
|
83
83
|
};
|
|
84
|
-
const spawnPromise = adapter.spawn(request);
|
|
85
84
|
const handle = new DetachedHandleImpl({
|
|
86
85
|
id: executionId,
|
|
87
86
|
stepId: step.id,
|
|
88
|
-
adapter,
|
|
89
|
-
spawnPromise,
|
|
87
|
+
spawned: adapter.spawn(request),
|
|
90
88
|
});
|
|
91
89
|
return handle.await();
|
|
92
90
|
}
|
|
@@ -146,13 +144,16 @@ export function resolveLedgerKey(step, input, ctx) {
|
|
|
146
144
|
}
|
|
147
145
|
}
|
|
148
146
|
/**
|
|
149
|
-
* Resume path: when a previous run recorded this exact step at `ledgerKey
|
|
150
|
-
* replay its output instead of re-running,
|
|
151
|
-
* `{ hit: false }` when there
|
|
152
|
-
* step normally.
|
|
147
|
+
* Resume path: when a previous run recorded this exact step at `ledgerKey` on the same
|
|
148
|
+
* input, replay its output instead of re-running, put the items it appended back on
|
|
149
|
+
* `stepCtx`'s item log, and emit `step_replayed`. Returns `{ hit: false }` when there
|
|
150
|
+
* is nothing to replay so the caller dispatches the step normally.
|
|
151
|
+
*
|
|
152
|
+
* The items go back through `stepCtx` so the lanes above it note them too: a parent
|
|
153
|
+
* that completes on this resumed run records everything beneath it, replayed or not.
|
|
153
154
|
*/
|
|
154
155
|
function replayFromLedger(opts) {
|
|
155
|
-
const { ledger, ledgerKey, step, broadcaster, agentName } = opts;
|
|
156
|
+
const { ledger, ledgerKey, inputHash, step, stepCtx, broadcaster, agentName } = opts;
|
|
156
157
|
if (!ledger || ledgerKey === undefined || ledger.isEmpty) {
|
|
157
158
|
return {
|
|
158
159
|
hit: false,
|
|
@@ -161,12 +162,22 @@ function replayFromLedger(opts) {
|
|
|
161
162
|
const replayed = ledger.take(ledgerKey, {
|
|
162
163
|
id: step.id,
|
|
163
164
|
kind: step.kind,
|
|
165
|
+
inputHash,
|
|
164
166
|
});
|
|
165
167
|
if (!replayed) {
|
|
166
168
|
return {
|
|
167
169
|
hit: false,
|
|
168
170
|
};
|
|
169
171
|
}
|
|
172
|
+
const items = parseRecordedItems(stepCtx, replayed.items ?? []);
|
|
173
|
+
if (!items) {
|
|
174
|
+
return {
|
|
175
|
+
hit: false,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
for (const item of items) {
|
|
179
|
+
stepCtx.itemLog.append(item);
|
|
180
|
+
}
|
|
170
181
|
emitFrameworkEvent({
|
|
171
182
|
broadcaster,
|
|
172
183
|
agentName,
|
|
@@ -182,20 +193,44 @@ function replayFromLedger(opts) {
|
|
|
182
193
|
};
|
|
183
194
|
}
|
|
184
195
|
/**
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
196
|
+
* Recorded items, parsed through the context's item schemas, or null when one no longer
|
|
197
|
+
* parses — a registry that changed since the run was recorded. The step then runs fresh
|
|
198
|
+
* rather than half-replaying its history.
|
|
199
|
+
*/
|
|
200
|
+
function parseRecordedItems(ctx, raw) {
|
|
201
|
+
if (raw.length === 0) {
|
|
202
|
+
return [];
|
|
203
|
+
}
|
|
204
|
+
try {
|
|
205
|
+
return frameworkCast(ctx).itemSchemas?.parseMany(raw) ?? frameworkCast(raw);
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Record a completed step's output, input hash, and the items it appended, so a resumed
|
|
213
|
+
* run replays this step rather than re-executing it. A no-op without a ledger or ledger
|
|
214
|
+
* key. Only successes reach here — a step that threw skips this call in `execute` and
|
|
215
|
+
* runs again on resume.
|
|
188
216
|
*/
|
|
189
217
|
async function recordToLedger(opts) {
|
|
190
|
-
const { ledger, ledgerKey, step, output } = opts;
|
|
218
|
+
const { ledger, ledgerKey, inputHash, lane, step, output } = opts;
|
|
191
219
|
if (!ledger || ledgerKey === undefined) {
|
|
192
220
|
return;
|
|
193
221
|
}
|
|
222
|
+
const items = lane?.appendedItems() ?? [];
|
|
194
223
|
await ledger.record({
|
|
195
224
|
path: ledgerKey,
|
|
196
225
|
stepId: step.id,
|
|
197
226
|
kind: step.kind,
|
|
198
227
|
output,
|
|
228
|
+
inputHash,
|
|
229
|
+
...(items.length > 0
|
|
230
|
+
? {
|
|
231
|
+
items,
|
|
232
|
+
}
|
|
233
|
+
: {}),
|
|
199
234
|
completedAt: new Date().toISOString(),
|
|
200
235
|
});
|
|
201
236
|
}
|
|
@@ -265,11 +300,17 @@ export async function execute(step, input, ctx) {
|
|
|
265
300
|
* output instead of re-running it. `ledgerKey`/`ledger` are captured before
|
|
266
301
|
* dispatch and reused by the record below. */
|
|
267
302
|
const ledgerKey = resolveLedgerKey(step, input, stepCtx);
|
|
303
|
+
if (ledgerKey === undefined) {
|
|
304
|
+
lane?.skipLedger();
|
|
305
|
+
}
|
|
306
|
+
const inputHash = ledgerKey === undefined ? undefined : lane?.currentDispatch()?.inputHash;
|
|
268
307
|
const ledger = impl?.ledger;
|
|
269
308
|
const replay = replayFromLedger({
|
|
270
309
|
ledger,
|
|
271
310
|
ledgerKey,
|
|
311
|
+
inputHash,
|
|
272
312
|
step,
|
|
313
|
+
stepCtx,
|
|
273
314
|
broadcaster,
|
|
274
315
|
agentName,
|
|
275
316
|
});
|
|
@@ -339,6 +380,10 @@ export async function execute(step, input, ctx) {
|
|
|
339
380
|
}
|
|
340
381
|
}
|
|
341
382
|
}
|
|
383
|
+
catch (error) {
|
|
384
|
+
lane?.releaseDispatch();
|
|
385
|
+
throw error;
|
|
386
|
+
}
|
|
342
387
|
finally {
|
|
343
388
|
lane?.leaveStep(frame);
|
|
344
389
|
}
|
|
@@ -361,6 +406,8 @@ export async function execute(step, input, ctx) {
|
|
|
361
406
|
await recordToLedger({
|
|
362
407
|
ledger,
|
|
363
408
|
ledgerKey,
|
|
409
|
+
inputHash,
|
|
410
|
+
lane,
|
|
364
411
|
step,
|
|
365
412
|
output: result,
|
|
366
413
|
});
|
|
@@ -43,8 +43,8 @@ export interface DetachedSpawnOverrides {
|
|
|
43
43
|
}
|
|
44
44
|
/**
|
|
45
45
|
* Route a step through the configured subprocess adapter and return a
|
|
46
|
-
* `DetachedHandle` that
|
|
47
|
-
*
|
|
46
|
+
* `DetachedHandle` that settles when the adapter reports the child
|
|
47
|
+
* finished. The adapter's `spawn()` may be async (the default in-memory
|
|
48
48
|
* adapter schedules the step body on the microtask queue, and
|
|
49
49
|
* out-of-process adapters may await an OS spawn).
|
|
50
50
|
*
|
|
@@ -24,8 +24,8 @@ export function resolveStepAdapter(step, callOverride, fallback) {
|
|
|
24
24
|
//#region Dispatcher
|
|
25
25
|
/**
|
|
26
26
|
* Route a step through the configured subprocess adapter and return a
|
|
27
|
-
* `DetachedHandle` that
|
|
28
|
-
*
|
|
27
|
+
* `DetachedHandle` that settles when the adapter reports the child
|
|
28
|
+
* finished. The adapter's `spawn()` may be async (the default in-memory
|
|
29
29
|
* adapter schedules the step body on the microtask queue, and
|
|
30
30
|
* out-of-process adapters may await an OS spawn).
|
|
31
31
|
*
|
|
@@ -57,12 +57,10 @@ export function dispatchStepThroughAdapter(h, s, input, parentCtx, overrides) {
|
|
|
57
57
|
},
|
|
58
58
|
_localExecutor: () => executeNoAdapter(s, input, childCtx),
|
|
59
59
|
};
|
|
60
|
-
const spawnPromise = adapter.spawn(request);
|
|
61
60
|
return new DetachedHandleImpl({
|
|
62
61
|
id: childCtx.id,
|
|
63
62
|
stepId: s.id,
|
|
64
|
-
adapter,
|
|
65
|
-
spawnPromise,
|
|
63
|
+
spawned: adapter.spawn(request),
|
|
66
64
|
});
|
|
67
65
|
}
|
|
68
66
|
//#endregion
|
|
@@ -18,6 +18,7 @@ export declare class ContextImpl implements Context<ContextData> {
|
|
|
18
18
|
stepCount: number;
|
|
19
19
|
tokens: TokenUsage;
|
|
20
20
|
cost: number;
|
|
21
|
+
billedCost: number;
|
|
21
22
|
state: unknown;
|
|
22
23
|
readonly parent: Context<ContextData> | null;
|
|
23
24
|
readonly usageParent: Context<ContextData> | null;
|
|
@@ -26,6 +27,8 @@ export declare class ContextImpl implements Context<ContextData> {
|
|
|
26
27
|
readonly threadId: string;
|
|
27
28
|
readonly resourceId?: string;
|
|
28
29
|
readonly itemLog: ItemLog;
|
|
30
|
+
/** The same log, typed for `rebase`. */
|
|
31
|
+
private readonly log;
|
|
29
32
|
lastStepMeta: StepMeta | null;
|
|
30
33
|
lastLayerUsage: LastLayerUsage | undefined;
|
|
31
34
|
readonly harness: AgentHarnessContract;
|
|
@@ -96,6 +99,21 @@ export declare class ContextImpl implements Context<ContextData> {
|
|
|
96
99
|
* @internal
|
|
97
100
|
*/
|
|
98
101
|
readonly ledger?: StepLedger;
|
|
102
|
+
/**
|
|
103
|
+
* The dispatch this view belongs to. Undefined on the context itself; a lane (see
|
|
104
|
+
* `enterStep`) reads its own here.
|
|
105
|
+
* @internal
|
|
106
|
+
*/
|
|
107
|
+
private readonly _lane?;
|
|
108
|
+
/**
|
|
109
|
+
* The item log and dispatch counts as they stood when the outermost run on this
|
|
110
|
+
* context began. A checkpoint persists these rather than the live values, because a
|
|
111
|
+
* resumed run starts that run over: its recorded steps replay and re-append their
|
|
112
|
+
* items, so the log must not already hold them. Unset between runs, and kept after a
|
|
113
|
+
* run that failed — that run is what a resume repeats.
|
|
114
|
+
* @internal
|
|
115
|
+
*/
|
|
116
|
+
private _baseline?;
|
|
99
117
|
constructor(opts: {
|
|
100
118
|
harness: AgentHarnessContract;
|
|
101
119
|
parent?: Context;
|
|
@@ -174,12 +192,29 @@ export declare class ContextImpl implements Context<ContextData> {
|
|
|
174
192
|
/**
|
|
175
193
|
* @internal
|
|
176
194
|
* Register `frame` as in flight and return the lane its step runs on: a view of
|
|
177
|
-
* this context that shares everything except its execution path
|
|
178
|
-
* the lane to the step, so steps the
|
|
179
|
-
* how other dispatches on this context
|
|
180
|
-
* here, at dispatch, never at settle.
|
|
195
|
+
* this context that shares everything except its execution path and the record of
|
|
196
|
+
* items appended through it. `execute()` hands the lane to the step, so steps the
|
|
197
|
+
* step dispatches hang under its path no matter how other dispatches on this context
|
|
198
|
+
* interleave. The occurrence ordinal is taken here, at dispatch, never at settle.
|
|
181
199
|
*/
|
|
182
200
|
enterStep(frame: FrontierFrame): ContextImpl;
|
|
201
|
+
/**
|
|
202
|
+
* @internal
|
|
203
|
+
* Mark this lane's step as kept out of the ledger (`durable: false`, `schedule`, a
|
|
204
|
+
* failed `replayKey`), so nothing running inside it records under its identity.
|
|
205
|
+
*/
|
|
206
|
+
skipLedger(): void;
|
|
207
|
+
/**
|
|
208
|
+
* @internal
|
|
209
|
+
* The dispatch this lane belongs to, or undefined on the context itself and on a
|
|
210
|
+
* lane kept out of the ledger. Lets code running inside a step (the model loop's
|
|
211
|
+
* rounds) record under the step's identity.
|
|
212
|
+
*/
|
|
213
|
+
currentDispatch(): {
|
|
214
|
+
path: string;
|
|
215
|
+
stepId: string;
|
|
216
|
+
inputHash: string | undefined;
|
|
217
|
+
} | undefined;
|
|
183
218
|
/**
|
|
184
219
|
* @internal
|
|
185
220
|
* The execution path of the step this lane belongs to — the ledger key identifying
|
|
@@ -187,12 +222,61 @@ export declare class ContextImpl implements Context<ContextData> {
|
|
|
187
222
|
* what lets a resumed run line recorded outputs up with the steps that produced them.
|
|
188
223
|
*/
|
|
189
224
|
currentPath(): string;
|
|
225
|
+
/**
|
|
226
|
+
* @internal
|
|
227
|
+
* Items appended to the item log through this lane, including by steps it
|
|
228
|
+
* dispatched on the same context. Empty on the context itself.
|
|
229
|
+
*/
|
|
230
|
+
appendedItems(): Item[];
|
|
190
231
|
/**
|
|
191
232
|
* @internal
|
|
192
233
|
* Drop `frame` from the in-flight set. Called when its step resolves, success or
|
|
193
234
|
* failure.
|
|
194
235
|
*/
|
|
195
236
|
leaveStep(frame: FrontierFrame): void;
|
|
237
|
+
/**
|
|
238
|
+
* @internal
|
|
239
|
+
* Give back this lane's ordinal after its step failed, so a retry runs at the same
|
|
240
|
+
* path. A resumed run never sees the failed attempt — nothing records a failure — so
|
|
241
|
+
* without this a retry would take the next ordinal and every later dispatch would sit
|
|
242
|
+
* one position past where the resume looks for it. Only the latest dispatch of a key
|
|
243
|
+
* can give its ordinal back; once a later one has taken the next, the ordinal stays.
|
|
244
|
+
*/
|
|
245
|
+
releaseDispatch(): void;
|
|
246
|
+
/**
|
|
247
|
+
* @internal
|
|
248
|
+
* Mark the start of the outermost run on this context. See `_baseline`.
|
|
249
|
+
*/
|
|
250
|
+
beginRun(): void;
|
|
251
|
+
/**
|
|
252
|
+
* @internal
|
|
253
|
+
* Mark a run as finished, so checkpoints record the live log and counts again.
|
|
254
|
+
*/
|
|
255
|
+
endRun(): void;
|
|
256
|
+
/**
|
|
257
|
+
* @internal
|
|
258
|
+
* What a checkpoint persists for the item log and dispatch counts — see `_baseline`.
|
|
259
|
+
*/
|
|
260
|
+
runBaseline(): RunBaseline;
|
|
261
|
+
/**
|
|
262
|
+
* @internal
|
|
263
|
+
* Whether a run on this context began and never finished — it failed, or is in
|
|
264
|
+
* flight. A run starting now repeats it.
|
|
265
|
+
*/
|
|
266
|
+
hasUnfinishedRun(): boolean;
|
|
267
|
+
/**
|
|
268
|
+
* @internal
|
|
269
|
+
* Stand the context back at a stored run baseline: the item log and dispatch counts
|
|
270
|
+
* a checkpoint recorded. For a run retried in place, which must see what a resume on
|
|
271
|
+
* a new harness would — not the items and counts its failed attempt left in memory.
|
|
272
|
+
*/
|
|
273
|
+
rebase(baseline: RunBaseline): void;
|
|
274
|
+
/**
|
|
275
|
+
* @internal
|
|
276
|
+
* Seed the dispatch counts a restored run starts from, so a resumed context numbers
|
|
277
|
+
* its dispatches where the recorded run did rather than from zero.
|
|
278
|
+
*/
|
|
279
|
+
restoreOccurrences(occurrences: Record<string, number>): void;
|
|
196
280
|
/**
|
|
197
281
|
* @internal
|
|
198
282
|
* Return a defensive copy of the current frontier. Consumed by the
|
|
@@ -200,6 +284,11 @@ export declare class ContextImpl implements Context<ContextData> {
|
|
|
200
284
|
*/
|
|
201
285
|
serialiseFrontier(): FrontierFrame[];
|
|
202
286
|
}
|
|
287
|
+
/** @internal Item log and dispatch counts at the start of a run — see `ContextImpl._baseline`. */
|
|
288
|
+
export interface RunBaseline {
|
|
289
|
+
items: Item[];
|
|
290
|
+
occurrences: Record<string, number>;
|
|
291
|
+
}
|
|
203
292
|
/**
|
|
204
293
|
* @internal
|
|
205
294
|
* The context a lane views, or `ctx` itself when it is not a lane. For per-execution
|