@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
|
@@ -17,12 +17,25 @@ export interface TurnContext {
|
|
|
17
17
|
* plus the messages being delivered this turn so the harness can honour
|
|
18
18
|
* per-turn `ExecuteOptions` (the first message's options establish
|
|
19
19
|
* resourceId/state/context for the turn). */
|
|
20
|
-
export type CreateContextFn = (items: ReadonlyArray<Item>, turnId: string, messages: ReadonlyArray<QueuedMessage>) => Context
|
|
20
|
+
export type CreateContextFn = (items: ReadonlyArray<Item>, turnId: string, messages: ReadonlyArray<QueuedMessage>) => Context | Promise<Context>;
|
|
21
|
+
/** @internal What one turn spent: its context's usage at the end, less at the start. */
|
|
22
|
+
export interface TurnUsage {
|
|
23
|
+
inputTokens: number;
|
|
24
|
+
outputTokens: number;
|
|
25
|
+
cachedTokens?: number;
|
|
26
|
+
cost: number;
|
|
27
|
+
billedCost: number;
|
|
28
|
+
}
|
|
21
29
|
export interface SessionRunnerOpts {
|
|
22
30
|
readonly threadId: string;
|
|
23
31
|
readonly agentName: string;
|
|
24
32
|
readonly runTurn: RunTurnFn;
|
|
25
33
|
readonly createContext: CreateContextFn;
|
|
34
|
+
/**
|
|
35
|
+
* Called once per turn, success or not, with what the turn spent. A durable host
|
|
36
|
+
* writes it to storage and hands the stored totals back through `seedUsage`.
|
|
37
|
+
*/
|
|
38
|
+
readonly onTurnUsage?: (usage: TurnUsage) => Promise<void>;
|
|
26
39
|
}
|
|
27
40
|
/**
|
|
28
41
|
* @internal
|
|
@@ -55,6 +68,8 @@ export declare class SessionRunner {
|
|
|
55
68
|
* that reports nothing about caching at all (see `SessionUsage`). */
|
|
56
69
|
private totalCachedTokens;
|
|
57
70
|
private totalCost;
|
|
71
|
+
private totalBilledCost;
|
|
72
|
+
private readonly onTurnUsage?;
|
|
58
73
|
private currentController?;
|
|
59
74
|
private currentCtx?;
|
|
60
75
|
private loopPromise?;
|
|
@@ -65,6 +80,8 @@ export declare class SessionRunner {
|
|
|
65
80
|
getStatus(): HarnessStatus;
|
|
66
81
|
/** Cumulative token usage and cost across all turns this session has run. */
|
|
67
82
|
getUsage(): SessionUsage;
|
|
83
|
+
/** Replace the totals with ones a durable host read back from storage. */
|
|
84
|
+
seedUsage(usage: SessionUsage): void;
|
|
68
85
|
/** Resolves once the queue has been drained and the runner is idle with a
|
|
69
86
|
* response available. If nothing has run yet, waits for the first turn.
|
|
70
87
|
*
|
|
@@ -80,6 +97,13 @@ export declare class SessionRunner {
|
|
|
80
97
|
kick(): void;
|
|
81
98
|
private drain;
|
|
82
99
|
private runOneTurn;
|
|
100
|
+
/**
|
|
101
|
+
* Add what the turn spent to the session's totals, before anyone waiting on the turn
|
|
102
|
+
* hears it settled — so `getUsage()` after `getAgentResponse()` includes it.
|
|
103
|
+
*/
|
|
104
|
+
private settleUsage;
|
|
105
|
+
/** A turn whose context could not be built: report it like any other failed turn. */
|
|
106
|
+
private failBeforeStart;
|
|
83
107
|
private resolveWaiters;
|
|
84
108
|
private rejectWaiters;
|
|
85
109
|
}
|
|
@@ -74,6 +74,8 @@ export class SessionRunner {
|
|
|
74
74
|
* that reports nothing about caching at all (see `SessionUsage`). */
|
|
75
75
|
totalCachedTokens;
|
|
76
76
|
totalCost = 0;
|
|
77
|
+
totalBilledCost = 0;
|
|
78
|
+
onTurnUsage;
|
|
77
79
|
currentController;
|
|
78
80
|
currentCtx;
|
|
79
81
|
loopPromise;
|
|
@@ -85,6 +87,7 @@ export class SessionRunner {
|
|
|
85
87
|
this.agentName = opts.agentName;
|
|
86
88
|
this.runTurn = opts.runTurn;
|
|
87
89
|
this.createContext = opts.createContext;
|
|
90
|
+
this.onTurnUsage = opts.onTurnUsage;
|
|
88
91
|
this.queue.subscribe(() => {
|
|
89
92
|
this.kick();
|
|
90
93
|
});
|
|
@@ -99,8 +102,17 @@ export class SessionRunner {
|
|
|
99
102
|
outputTokens: this.totalOutputTokens,
|
|
100
103
|
cachedTokens: this.totalCachedTokens,
|
|
101
104
|
cost: this.totalCost > 0 ? this.totalCost : undefined,
|
|
105
|
+
billedCost: this.totalBilledCost > 0 ? this.totalBilledCost : undefined,
|
|
102
106
|
};
|
|
103
107
|
}
|
|
108
|
+
/** Replace the totals with ones a durable host read back from storage. */
|
|
109
|
+
seedUsage(usage) {
|
|
110
|
+
this.totalInputTokens = usage.inputTokens;
|
|
111
|
+
this.totalOutputTokens = usage.outputTokens;
|
|
112
|
+
this.totalCachedTokens = usage.cachedTokens;
|
|
113
|
+
this.totalCost = usage.cost ?? 0;
|
|
114
|
+
this.totalBilledCost = usage.billedCost ?? 0;
|
|
115
|
+
}
|
|
104
116
|
/** Resolves once the queue has been drained and the runner is idle with a
|
|
105
117
|
* response available. If nothing has run yet, waits for the first turn.
|
|
106
118
|
*
|
|
@@ -182,8 +194,18 @@ export class SessionRunner {
|
|
|
182
194
|
// the harness's createContext callback receives Item[] directly and
|
|
183
195
|
// seeds the context without re-converting.
|
|
184
196
|
const items = mergeInputsToItems(messages);
|
|
185
|
-
|
|
197
|
+
let ctx;
|
|
198
|
+
try {
|
|
199
|
+
ctx = await this.createContext(items, turnId, messages);
|
|
200
|
+
}
|
|
201
|
+
catch (err) {
|
|
202
|
+
this.failBeforeStart(turnId, err);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
186
205
|
this.currentCtx = ctx;
|
|
206
|
+
// A resumed turn's context already carries what the cut-off attempt spent; only
|
|
207
|
+
// the increase belongs to this turn.
|
|
208
|
+
const start = usageOf(ctx);
|
|
187
209
|
emitFrameworkEvent({
|
|
188
210
|
broadcaster: this.broadcaster,
|
|
189
211
|
agentName: this.agentName,
|
|
@@ -211,6 +233,7 @@ export class SessionRunner {
|
|
|
211
233
|
};
|
|
212
234
|
try {
|
|
213
235
|
const text = await this.runTurn(ctx, turn, controller.signal);
|
|
236
|
+
await this.settleUsage(start, ctx);
|
|
214
237
|
const response = buildResponse(text, ctx);
|
|
215
238
|
this.lastResponse = response;
|
|
216
239
|
this.lastError = undefined;
|
|
@@ -232,6 +255,8 @@ export class SessionRunner {
|
|
|
232
255
|
}
|
|
233
256
|
}
|
|
234
257
|
catch (err) {
|
|
258
|
+
// An aborted turn still consumed whatever the model billed before the cut.
|
|
259
|
+
await this.settleUsage(start, ctx);
|
|
235
260
|
const error = err instanceof Error ? err : new Error(String(err));
|
|
236
261
|
this.lastError = error;
|
|
237
262
|
emitFrameworkEvent({
|
|
@@ -249,16 +274,6 @@ export class SessionRunner {
|
|
|
249
274
|
this.rejectWaiters(error);
|
|
250
275
|
}
|
|
251
276
|
finally {
|
|
252
|
-
// Accumulate the turn's token accounting whatever the outcome — an
|
|
253
|
-
// aborted turn still consumed whatever the model billed before the cut.
|
|
254
|
-
this.totalInputTokens += ctx.tokens.input;
|
|
255
|
-
this.totalOutputTokens += ctx.tokens.output;
|
|
256
|
-
// Only ever leave `undefined` behind when NO turn reported a figure —
|
|
257
|
-
// a turn that reported 0 must surface as 0, not "unreported".
|
|
258
|
-
if (ctx.tokens.cached !== undefined) {
|
|
259
|
-
this.totalCachedTokens = (this.totalCachedTokens ?? 0) + ctx.tokens.cached;
|
|
260
|
-
}
|
|
261
|
-
this.totalCost += ctx.cost;
|
|
262
277
|
this.currentCtx = undefined;
|
|
263
278
|
this.currentController = undefined;
|
|
264
279
|
this.status = {
|
|
@@ -266,6 +281,43 @@ export class SessionRunner {
|
|
|
266
281
|
};
|
|
267
282
|
}
|
|
268
283
|
}
|
|
284
|
+
/**
|
|
285
|
+
* Add what the turn spent to the session's totals, before anyone waiting on the turn
|
|
286
|
+
* hears it settled — so `getUsage()` after `getAgentResponse()` includes it.
|
|
287
|
+
*/
|
|
288
|
+
async settleUsage(start, ctx) {
|
|
289
|
+
const spent = usageSince(start, ctx);
|
|
290
|
+
this.totalInputTokens += spent.inputTokens;
|
|
291
|
+
this.totalOutputTokens += spent.outputTokens;
|
|
292
|
+
// Only ever leave `undefined` behind when NO turn reported a figure —
|
|
293
|
+
// a turn that reported 0 must surface as 0, not "unreported".
|
|
294
|
+
if (spent.cachedTokens !== undefined) {
|
|
295
|
+
this.totalCachedTokens = (this.totalCachedTokens ?? 0) + spent.cachedTokens;
|
|
296
|
+
}
|
|
297
|
+
this.totalCost += spent.cost;
|
|
298
|
+
this.totalBilledCost += spent.billedCost;
|
|
299
|
+
await this.onTurnUsage?.(spent);
|
|
300
|
+
}
|
|
301
|
+
/** A turn whose context could not be built: report it like any other failed turn. */
|
|
302
|
+
failBeforeStart(turnId, err) {
|
|
303
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
304
|
+
this.lastError = error;
|
|
305
|
+
emitFrameworkEvent({
|
|
306
|
+
broadcaster: this.broadcaster,
|
|
307
|
+
agentName: this.agentName,
|
|
308
|
+
eventType: 'turn_aborted',
|
|
309
|
+
data: {
|
|
310
|
+
turnId,
|
|
311
|
+
reason: error.message,
|
|
312
|
+
errorKind: isNoeticError(error) ? error.noeticError.kind : undefined,
|
|
313
|
+
},
|
|
314
|
+
});
|
|
315
|
+
this.rejectWaiters(error);
|
|
316
|
+
this.currentController = undefined;
|
|
317
|
+
this.status = {
|
|
318
|
+
kind: 'idle',
|
|
319
|
+
};
|
|
320
|
+
}
|
|
269
321
|
resolveWaiters(response) {
|
|
270
322
|
const pending = this.responseWaiters.splice(0, this.responseWaiters.length);
|
|
271
323
|
for (const w of pending) {
|
|
@@ -281,6 +333,25 @@ export class SessionRunner {
|
|
|
281
333
|
}
|
|
282
334
|
//#endregion
|
|
283
335
|
//#region buildResponse
|
|
336
|
+
function usageOf(ctx) {
|
|
337
|
+
return {
|
|
338
|
+
inputTokens: ctx.tokens.input,
|
|
339
|
+
outputTokens: ctx.tokens.output,
|
|
340
|
+
cachedTokens: ctx.tokens.cached,
|
|
341
|
+
cost: ctx.cost,
|
|
342
|
+
billedCost: ctx.billedCost,
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
function usageSince(start, ctx) {
|
|
346
|
+
const now = usageOf(ctx);
|
|
347
|
+
return {
|
|
348
|
+
inputTokens: now.inputTokens - start.inputTokens,
|
|
349
|
+
outputTokens: now.outputTokens - start.outputTokens,
|
|
350
|
+
cachedTokens: now.cachedTokens === undefined ? undefined : now.cachedTokens - (start.cachedTokens ?? 0),
|
|
351
|
+
cost: now.cost - start.cost,
|
|
352
|
+
billedCost: now.billedCost - start.billedCost,
|
|
353
|
+
};
|
|
354
|
+
}
|
|
284
355
|
function buildResponse(text, ctx) {
|
|
285
356
|
return {
|
|
286
357
|
items: ctx.itemLog.items,
|
|
@@ -294,6 +365,7 @@ function buildResponse(text, ctx) {
|
|
|
294
365
|
cachedTokens: ctx.tokens.cached,
|
|
295
366
|
},
|
|
296
367
|
cost: ctx.cost > 0 ? ctx.cost : undefined,
|
|
368
|
+
billedCost: ctx.billedCost > 0 ? ctx.billedCost : undefined,
|
|
297
369
|
text,
|
|
298
370
|
lastLayerUsage: ctx.lastLayerUsage,
|
|
299
371
|
};
|
|
@@ -14,8 +14,13 @@ import { z } from 'zod';
|
|
|
14
14
|
* layer id, so a v1 snapshot carries state under ids no current layer reads
|
|
15
15
|
* — restoring it would silently drop that state. There is no migration;
|
|
16
16
|
* discard via `CheckpointStore.clear()` and start fresh.
|
|
17
|
+
* - v2 → v3: `itemLog` holds the log as it stood when the run in flight began, not
|
|
18
|
+
* at the moment of capture, and `occurrences` records the dispatch counts from that
|
|
19
|
+
* same moment. A resumed run replays its recorded steps, which put their items
|
|
20
|
+
* back; a v2 log already holds them, so restoring it would duplicate history. No
|
|
21
|
+
* migration — discard and start fresh.
|
|
17
22
|
*/
|
|
18
|
-
export declare const CheckpointSchemaVersion =
|
|
23
|
+
export declare const CheckpointSchemaVersion = 3;
|
|
19
24
|
/**
|
|
20
25
|
* @public
|
|
21
26
|
* One entry in the execution frontier — a pointer to a step currently in
|
|
@@ -60,8 +65,9 @@ export declare const PendingAskUserSnapshotSchema: z.ZodObject<{
|
|
|
60
65
|
export type PendingAskUserSnapshot = z.infer<typeof PendingAskUserSnapshotSchema>;
|
|
61
66
|
/**
|
|
62
67
|
* @public
|
|
63
|
-
* Item log state captured in a snapshot
|
|
64
|
-
*
|
|
68
|
+
* Item log state captured in a snapshot: the log as it stood when the run in
|
|
69
|
+
* flight began, or the live log when no run is in flight. The steps a resumed run
|
|
70
|
+
* replays put the rest back, from the items the step ledger recorded for each.
|
|
65
71
|
*
|
|
66
72
|
* Items are carried as `unknown` here and re-parsed on restore via the
|
|
67
73
|
* harness's `ItemSchemaRegistry`, which is the same gate production traffic
|
|
@@ -99,7 +105,7 @@ export type ChannelSnapshot = z.infer<typeof ChannelSnapshotSchema>;
|
|
|
99
105
|
* instead of producing a silently corrupt restored context.
|
|
100
106
|
*/
|
|
101
107
|
export declare const CheckpointSnapshotSchema: z.ZodObject<{
|
|
102
|
-
schemaVersion: z.ZodLiteral<
|
|
108
|
+
schemaVersion: z.ZodLiteral<3>;
|
|
103
109
|
executionId: z.ZodString;
|
|
104
110
|
threadId: z.ZodOptional<z.ZodString>;
|
|
105
111
|
resourceId: z.ZodOptional<z.ZodString>;
|
|
@@ -121,6 +127,17 @@ export declare const CheckpointSnapshotSchema: z.ZodObject<{
|
|
|
121
127
|
itemLog: z.ZodObject<{
|
|
122
128
|
items: z.ZodArray<z.ZodUnknown>;
|
|
123
129
|
}, z.core.$strip>;
|
|
130
|
+
occurrences: z.ZodRecord<z.ZodString, z.ZodNumber>;
|
|
131
|
+
state: z.ZodOptional<z.ZodUnknown>;
|
|
132
|
+
usage: z.ZodOptional<z.ZodObject<{
|
|
133
|
+
tokens: z.ZodObject<{
|
|
134
|
+
input: z.ZodNumber;
|
|
135
|
+
output: z.ZodNumber;
|
|
136
|
+
total: z.ZodNumber;
|
|
137
|
+
cached: z.ZodOptional<z.ZodNumber>;
|
|
138
|
+
}, z.core.$strip>;
|
|
139
|
+
cost: z.ZodNumber;
|
|
140
|
+
}, z.core.$strip>>;
|
|
124
141
|
channels: z.ZodOptional<z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
125
142
|
name: z.ZodString;
|
|
126
143
|
mode: z.ZodLiteral<"value">;
|
package/dist/types/checkpoint.js
CHANGED
|
@@ -15,8 +15,13 @@ import { z } from 'zod';
|
|
|
15
15
|
* layer id, so a v1 snapshot carries state under ids no current layer reads
|
|
16
16
|
* — restoring it would silently drop that state. There is no migration;
|
|
17
17
|
* discard via `CheckpointStore.clear()` and start fresh.
|
|
18
|
+
* - v2 → v3: `itemLog` holds the log as it stood when the run in flight began, not
|
|
19
|
+
* at the moment of capture, and `occurrences` records the dispatch counts from that
|
|
20
|
+
* same moment. A resumed run replays its recorded steps, which put their items
|
|
21
|
+
* back; a v2 log already holds them, so restoring it would duplicate history. No
|
|
22
|
+
* migration — discard and start fresh.
|
|
18
23
|
*/
|
|
19
|
-
export const CheckpointSchemaVersion =
|
|
24
|
+
export const CheckpointSchemaVersion = 3;
|
|
20
25
|
/**
|
|
21
26
|
* @public
|
|
22
27
|
* One entry in the execution frontier — a pointer to a step currently in
|
|
@@ -58,8 +63,9 @@ export const PendingAskUserSnapshotSchema = z.object({
|
|
|
58
63
|
});
|
|
59
64
|
/**
|
|
60
65
|
* @public
|
|
61
|
-
* Item log state captured in a snapshot
|
|
62
|
-
*
|
|
66
|
+
* Item log state captured in a snapshot: the log as it stood when the run in
|
|
67
|
+
* flight began, or the live log when no run is in flight. The steps a resumed run
|
|
68
|
+
* replays put the rest back, from the items the step ledger recorded for each.
|
|
63
69
|
*
|
|
64
70
|
* Items are carried as `unknown` here and re-parsed on restore via the
|
|
65
71
|
* harness's `ItemSchemaRegistry`, which is the same gate production traffic
|
|
@@ -107,6 +113,30 @@ export const CheckpointSnapshotSchema = z.object({
|
|
|
107
113
|
cwd: CwdSnapshotSchema.nullable(),
|
|
108
114
|
askUser: z.array(PendingAskUserSnapshotSchema),
|
|
109
115
|
itemLog: ItemLogSnapshotSchema,
|
|
116
|
+
/**
|
|
117
|
+
* Dispatch counts per `<parent path>/<step id>`, taken at the same moment as
|
|
118
|
+
* `itemLog`. A restored context numbers its dispatches from here, so a resumed run
|
|
119
|
+
* meets its recorded steps at the paths they were recorded under, and a later run
|
|
120
|
+
* on the same execution does not land on an earlier run's paths.
|
|
121
|
+
*/
|
|
122
|
+
occurrences: z.record(z.string(), z.number()),
|
|
123
|
+
/**
|
|
124
|
+
* The execution's `ctx.state` at capture time. Absent when the state does not survive
|
|
125
|
+
* JSON encoding, in which case restore keeps whatever state the host passes.
|
|
126
|
+
*/
|
|
127
|
+
state: z.unknown().optional(),
|
|
128
|
+
/** Tokens and cost the execution had spent at capture time, so budgets carry over. */
|
|
129
|
+
usage: z
|
|
130
|
+
.object({
|
|
131
|
+
tokens: z.object({
|
|
132
|
+
input: z.number(),
|
|
133
|
+
output: z.number(),
|
|
134
|
+
total: z.number(),
|
|
135
|
+
cached: z.number().optional(),
|
|
136
|
+
}),
|
|
137
|
+
cost: z.number(),
|
|
138
|
+
})
|
|
139
|
+
.optional(),
|
|
110
140
|
/**
|
|
111
141
|
* Stored state of every channel the execution used. Optional so snapshots
|
|
112
142
|
* written before channels were captured still load (they restore with no
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { DetachedHandle,
|
|
1
|
+
import type { DetachedHandle, SpawnedSubprocess } from '@noetic-tools/types';
|
|
2
2
|
import { DetachedStatus } from '@noetic-tools/types';
|
|
3
3
|
interface DetachedHandleOpts {
|
|
4
4
|
/** Id surfaced to callers — usually the execution id (childCtx.id in
|
|
@@ -7,33 +7,23 @@ interface DetachedHandleOpts {
|
|
|
7
7
|
/** Step id — used when the adapter surfaces a generic failure and we need
|
|
8
8
|
* to produce a `NoeticError` with a meaningful `stepId`. */
|
|
9
9
|
stepId: string;
|
|
10
|
-
/** Adapter that produced the handle. */
|
|
11
|
-
adapter: SubprocessAdapter;
|
|
12
10
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* is reachable even before the spawn itself has settled.
|
|
11
|
+
* The in-flight `adapter.spawn(request)` call, passed unawaited so the
|
|
12
|
+
* handle exists (and `.await()` works) before the spawn itself resolves.
|
|
16
13
|
*/
|
|
17
|
-
|
|
14
|
+
spawned: Promise<SpawnedSubprocess>;
|
|
18
15
|
}
|
|
19
16
|
/**
|
|
20
17
|
* @public
|
|
21
|
-
* Thin wrapper over a
|
|
22
|
-
* contract.
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* The polling cadence starts at 10ms and ramps to 100ms after the first
|
|
28
|
-
* second — responsive for short-lived in-memory steps without burning cycles
|
|
29
|
-
* on long-running ones.
|
|
18
|
+
* Thin wrapper over a spawned subprocess that implements the `DetachedHandle`
|
|
19
|
+
* contract. It waits on the adapter's `settled` promise and reads the result
|
|
20
|
+
* (or error) off the final handle's metadata. Waiting starts in the
|
|
21
|
+
* constructor, so `status`, `result`, and `error` settle whether or not the
|
|
22
|
+
* caller ever invokes `.await()`.
|
|
30
23
|
*/
|
|
31
24
|
export declare class DetachedHandleImpl<O> implements DetachedHandle<O> {
|
|
32
25
|
readonly id: string;
|
|
33
26
|
private readonly _stepId;
|
|
34
|
-
private readonly _adapter;
|
|
35
|
-
private readonly _spawnPromise;
|
|
36
|
-
private readonly _startTime;
|
|
37
27
|
private _status;
|
|
38
28
|
private _result;
|
|
39
29
|
private _error;
|
|
@@ -49,7 +39,6 @@ export declare class DetachedHandleImpl<O> implements DetachedHandle<O> {
|
|
|
49
39
|
* observes the final value.
|
|
50
40
|
*/
|
|
51
41
|
await(timeout?: number): Promise<O>;
|
|
52
|
-
private pollUntilSettled;
|
|
53
42
|
private finalise;
|
|
54
43
|
}
|
|
55
44
|
export {};
|
|
@@ -1,35 +1,6 @@
|
|
|
1
1
|
import { DetachedStatus, frameworkCast, NoeticErrorImpl } from '@noetic-tools/types';
|
|
2
2
|
//#endregion
|
|
3
3
|
//#region Helpers
|
|
4
|
-
const INITIAL_POLL_MS = 10;
|
|
5
|
-
const MAX_POLL_MS = 100;
|
|
6
|
-
const POLL_RAMP_AFTER_MS = 1_000;
|
|
7
|
-
/** Upper bound on microtask yields before falling back to timer-based
|
|
8
|
-
* polling. Chosen empirically: in-memory step bodies settle within a
|
|
9
|
-
* handful of microtasks, and 64 gives plenty of headroom for chained
|
|
10
|
-
* awaits inside complex step trees without busy-spinning. */
|
|
11
|
-
const MAX_MICROTASK_YIELDS = 64;
|
|
12
|
-
/** Grace period before treating persistent null `adapter.get(handleId)`
|
|
13
|
-
* results as an eviction. Tolerates transient nulls from adapters that
|
|
14
|
-
* register the handle asynchronously relative to the spawn promise
|
|
15
|
-
* settling, but bounds the worst case so a corrupt adapter doesn't
|
|
16
|
-
* produce an infinite poll. */
|
|
17
|
-
const HANDLE_EVICTED_GRACE_MS = 500;
|
|
18
|
-
/**
|
|
19
|
-
* Yield control to the timer queue so the adapter has a chance to
|
|
20
|
-
* transition the handle before we issue the next `adapter.get()` call.
|
|
21
|
-
* Using a timer (even 0ms) ensures we don't spin-lock when the adapter
|
|
22
|
-
* schedules its completion on a later microtask.
|
|
23
|
-
*/
|
|
24
|
-
function sleep(ms) {
|
|
25
|
-
if (ms <= 0) {
|
|
26
|
-
return Promise.resolve();
|
|
27
|
-
}
|
|
28
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
29
|
-
}
|
|
30
|
-
function isTerminalStatus(status) {
|
|
31
|
-
return (status === 'completed' || status === 'failed' || status === 'stopped' || status === 'stale');
|
|
32
|
-
}
|
|
33
4
|
function isRecord(value) {
|
|
34
5
|
return typeof value === 'object' && value !== null;
|
|
35
6
|
}
|
|
@@ -90,22 +61,15 @@ function extractError(metadata) {
|
|
|
90
61
|
//#region DetachedHandleImpl
|
|
91
62
|
/**
|
|
92
63
|
* @public
|
|
93
|
-
* Thin wrapper over a
|
|
94
|
-
* contract.
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
* The polling cadence starts at 10ms and ramps to 100ms after the first
|
|
100
|
-
* second — responsive for short-lived in-memory steps without burning cycles
|
|
101
|
-
* on long-running ones.
|
|
64
|
+
* Thin wrapper over a spawned subprocess that implements the `DetachedHandle`
|
|
65
|
+
* contract. It waits on the adapter's `settled` promise and reads the result
|
|
66
|
+
* (or error) off the final handle's metadata. Waiting starts in the
|
|
67
|
+
* constructor, so `status`, `result`, and `error` settle whether or not the
|
|
68
|
+
* caller ever invokes `.await()`.
|
|
102
69
|
*/
|
|
103
70
|
export class DetachedHandleImpl {
|
|
104
71
|
id;
|
|
105
72
|
_stepId;
|
|
106
|
-
_adapter;
|
|
107
|
-
_spawnPromise;
|
|
108
|
-
_startTime;
|
|
109
73
|
_status = DetachedStatus.Running;
|
|
110
74
|
_result;
|
|
111
75
|
_error;
|
|
@@ -113,13 +77,8 @@ export class DetachedHandleImpl {
|
|
|
113
77
|
constructor(opts) {
|
|
114
78
|
this.id = opts.id;
|
|
115
79
|
this._stepId = opts.stepId;
|
|
116
|
-
this.
|
|
117
|
-
|
|
118
|
-
this._startTime = Date.now();
|
|
119
|
-
// One shared poll for the handle's life, so repeated `.await()` calls
|
|
120
|
-
// don't start parallel loops. The rejection is swallowed here only to
|
|
121
|
-
// record it; `.await()` surfaces it to the caller.
|
|
122
|
-
this._settlement = this.pollUntilSettled();
|
|
80
|
+
this._settlement = opts.spawned.then((s) => s.settled).then((h) => this.finalise(h));
|
|
81
|
+
// Swallowed here only to record the failure; `.await()` surfaces it.
|
|
123
82
|
this._settlement.catch((err) => {
|
|
124
83
|
if (this._status === DetachedStatus.Running) {
|
|
125
84
|
this._status = DetachedStatus.Failed;
|
|
@@ -170,66 +129,6 @@ export class DetachedHandleImpl {
|
|
|
170
129
|
}
|
|
171
130
|
}
|
|
172
131
|
}
|
|
173
|
-
async pollUntilSettled() {
|
|
174
|
-
// Wait for the spawn itself to succeed before we start polling —
|
|
175
|
-
// otherwise we'd be polling with an undefined handle id.
|
|
176
|
-
const initialHandle = await this._spawnPromise;
|
|
177
|
-
if (isTerminalStatus(initialHandle.status)) {
|
|
178
|
-
return this.finalise(initialHandle);
|
|
179
|
-
}
|
|
180
|
-
// Track when the adapter persistently returns null for this handle.
|
|
181
|
-
// Transient nulls are tolerated for `HANDLE_EVICTED_GRACE_MS`; after
|
|
182
|
-
// that we raise `handle_evicted` instead of looping forever. A
|
|
183
|
-
// non-null observation resets the grace window.
|
|
184
|
-
let firstNullAt = null;
|
|
185
|
-
const observeNull = () => {
|
|
186
|
-
if (firstNullAt === null) {
|
|
187
|
-
firstNullAt = Date.now();
|
|
188
|
-
return;
|
|
189
|
-
}
|
|
190
|
-
if (Date.now() - firstNullAt >= HANDLE_EVICTED_GRACE_MS) {
|
|
191
|
-
throw new NoeticErrorImpl({
|
|
192
|
-
kind: 'handle_evicted',
|
|
193
|
-
handleId: initialHandle.id,
|
|
194
|
-
stepId: this._stepId,
|
|
195
|
-
gracePeriod: HANDLE_EVICTED_GRACE_MS,
|
|
196
|
-
});
|
|
197
|
-
}
|
|
198
|
-
};
|
|
199
|
-
const observeHandle = (h) => {
|
|
200
|
-
if (h === null) {
|
|
201
|
-
observeNull();
|
|
202
|
-
return null;
|
|
203
|
-
}
|
|
204
|
-
firstNullAt = null;
|
|
205
|
-
return h;
|
|
206
|
-
};
|
|
207
|
-
// Fast path: yield through the microtask queue first. The in-memory
|
|
208
|
-
// adapter schedules completion on a microtask, so a handful of yields
|
|
209
|
-
// typically resolves the handle in sub-millisecond time. This keeps the
|
|
210
|
-
// interpreter's "route through adapter" overhead negligible.
|
|
211
|
-
for (let i = 0; i < MAX_MICROTASK_YIELDS; i++) {
|
|
212
|
-
const handle = observeHandle(await this._adapter.get(initialHandle.id));
|
|
213
|
-
if (handle && isTerminalStatus(handle.status)) {
|
|
214
|
-
return this.finalise(handle);
|
|
215
|
-
}
|
|
216
|
-
await Promise.resolve();
|
|
217
|
-
}
|
|
218
|
-
// Slow path: fall back to timer-based polling for genuinely long-running
|
|
219
|
-
// handles (out-of-process adapters, async work that doesn't resolve on
|
|
220
|
-
// the microtask queue).
|
|
221
|
-
let delay = INITIAL_POLL_MS;
|
|
222
|
-
for (;;) {
|
|
223
|
-
const handle = observeHandle(await this._adapter.get(initialHandle.id));
|
|
224
|
-
if (handle && isTerminalStatus(handle.status)) {
|
|
225
|
-
return this.finalise(handle);
|
|
226
|
-
}
|
|
227
|
-
await sleep(delay);
|
|
228
|
-
if (Date.now() - this._startTime >= POLL_RAMP_AFTER_MS) {
|
|
229
|
-
delay = MAX_POLL_MS;
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
132
|
finalise(handle) {
|
|
234
133
|
const metadata = handle.metadata;
|
|
235
134
|
if (handle.status === 'completed') {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@noetic-tools/core",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "6.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Step primitives, interpreter, runtime, and context layer contract for Noetic agents.",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
},
|
|
70
70
|
"dependencies": {
|
|
71
71
|
"@noetic-tools/context": "^1.9.0",
|
|
72
|
-
"@noetic-tools/types": "^
|
|
72
|
+
"@noetic-tools/types": "^4.0.0",
|
|
73
73
|
"@openrouter/agent": "^0.11.0",
|
|
74
74
|
"@openrouter/sdk": "1.4.25",
|
|
75
75
|
"jsonata": "2.2.2",
|