@noetic-tools/core 5.12.0 → 5.14.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/decide-builders.d.ts +2 -2
- package/dist/builders/dynamic-workflow.js +2 -0
- package/dist/builders/provide-builder.d.ts +2 -2
- package/dist/builders/spawn-builder.d.ts +2 -2
- package/dist/builders/step-builders.d.ts +5 -5
- package/dist/builders/workflow-hydrator.d.ts +1 -1
- package/dist/builders/workflow-hydrator.js +54 -6
- package/dist/expression/check.js +14 -0
- package/dist/expression/jsonata.d.ts +7 -0
- package/dist/expression/jsonata.js +11 -1
- package/dist/harness/agent-harness.d.ts +59 -5
- package/dist/harness/agent-harness.js +176 -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 +7 -3
- package/dist/index.js +2 -0
- package/dist/interpreter/emit-items.d.ts +19 -0
- package/dist/interpreter/emit-items.js +106 -0
- package/dist/interpreter/execute-action.js +3 -0
- package/dist/interpreter/execute-control.js +3 -0
- package/dist/interpreter/execute.js +67 -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 +106 -4
- package/dist/runtime/context-impl.js +224 -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 +77 -40
- package/dist/runtime/durable/step-ledger.js +193 -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/schemas/workflow.d.ts +1 -1
- 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
- package/schema/noetic-workflow.schema.json +391 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable rounds for the model loop.
|
|
3
|
+
*
|
|
4
|
+
* One `callModel` step can run many rounds: the model asks for tools, the harness
|
|
5
|
+
* runs them, the model answers again. The step ledger records the step only when the
|
|
6
|
+
* whole loop ends, so without this a failure on round five throws rounds one to four
|
|
7
|
+
* away — each paid for again on resume, and each tool run again.
|
|
8
|
+
*
|
|
9
|
+
* Each finished round is recorded under `<step path>/round#<n>`, carrying what it
|
|
10
|
+
* added to the loop: the model's output and tool results, the conversation input
|
|
11
|
+
* those became, the items appended to the item log (messages injected between rounds),
|
|
12
|
+
* and the round's usage. A resumed loop replays rounds in order and stops at the first
|
|
13
|
+
* one it does not find; every round after that runs live, because a recorded round
|
|
14
|
+
* belongs to the conversation the earlier recorded rounds built. When the step
|
|
15
|
+
* finishes and records, the ledger prunes its rounds.
|
|
16
|
+
*/
|
|
17
|
+
import { frameworkCast } from '@noetic-tools/types';
|
|
18
|
+
import { z } from 'zod';
|
|
19
|
+
import { ContextImpl } from './deps/runtime.js';
|
|
20
|
+
//#region Types
|
|
21
|
+
const ROUND_KIND = 'callModel:round';
|
|
22
|
+
const RoundOutputSchema = z.object({
|
|
23
|
+
items: z.array(z.unknown()),
|
|
24
|
+
input: z.array(z.unknown()),
|
|
25
|
+
usage: z.object({
|
|
26
|
+
inputTokens: z.number(),
|
|
27
|
+
outputTokens: z.number(),
|
|
28
|
+
cachedTokens: z.number().optional(),
|
|
29
|
+
cacheWriteTokens: z.number().optional(),
|
|
30
|
+
}),
|
|
31
|
+
cost: z.number(),
|
|
32
|
+
});
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region Public API
|
|
35
|
+
/**
|
|
36
|
+
* The round ledger for one model loop. `open` gives none when the call is not running
|
|
37
|
+
* as a step on a context with a ledger.
|
|
38
|
+
*/
|
|
39
|
+
export class RoundLedger {
|
|
40
|
+
ctx;
|
|
41
|
+
dispatch;
|
|
42
|
+
replaying = true;
|
|
43
|
+
constructor(ctx, dispatch) {
|
|
44
|
+
this.ctx = ctx;
|
|
45
|
+
this.dispatch = dispatch;
|
|
46
|
+
}
|
|
47
|
+
/** Undefined when the loop has nothing to record into. */
|
|
48
|
+
static open(ctx) {
|
|
49
|
+
if (!(ctx instanceof ContextImpl) || !ctx.ledger) {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
const dispatch = ctx.currentDispatch();
|
|
53
|
+
return dispatch ? new RoundLedger(ctx, dispatch) : undefined;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The recorded round `round`, with its items parsed, or undefined once replay has
|
|
57
|
+
* stopped — at the first round with no usable record, and for good after that.
|
|
58
|
+
*/
|
|
59
|
+
take(round, schemas) {
|
|
60
|
+
const ledger = this.ctx.ledger;
|
|
61
|
+
if (!this.replaying || !ledger || ledger.isEmpty) {
|
|
62
|
+
this.replaying = false;
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
const entry = ledger.take(this.key(round), {
|
|
66
|
+
id: this.dispatch.stepId,
|
|
67
|
+
kind: ROUND_KIND,
|
|
68
|
+
inputHash: this.dispatch.inputHash,
|
|
69
|
+
});
|
|
70
|
+
const parsed = entry ? RoundOutputSchema.safeParse(entry.output) : undefined;
|
|
71
|
+
if (!entry || !parsed?.success) {
|
|
72
|
+
this.replaying = false;
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
return {
|
|
77
|
+
items: schemas.parseMany(parsed.data.items),
|
|
78
|
+
input: parsed.data.input,
|
|
79
|
+
usage: parsed.data.usage,
|
|
80
|
+
cost: parsed.data.cost,
|
|
81
|
+
appended: schemas.parseMany(entry.items ?? []),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
this.replaying = false;
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** Mark where the log stood when a round began, so its appends can be recorded. */
|
|
90
|
+
mark() {
|
|
91
|
+
return this.ctx.appendedItems().length;
|
|
92
|
+
}
|
|
93
|
+
/** Record a finished round. `logMark` is what `mark()` returned when it began. */
|
|
94
|
+
async record(round, logMark, record) {
|
|
95
|
+
this.replaying = false;
|
|
96
|
+
const appended = this.ctx.appendedItems().slice(logMark);
|
|
97
|
+
await this.ctx.ledger?.record({
|
|
98
|
+
path: this.key(round),
|
|
99
|
+
stepId: this.dispatch.stepId,
|
|
100
|
+
kind: ROUND_KIND,
|
|
101
|
+
inputHash: this.dispatch.inputHash,
|
|
102
|
+
output: frameworkCast(record),
|
|
103
|
+
...(appended.length > 0
|
|
104
|
+
? {
|
|
105
|
+
items: appended,
|
|
106
|
+
}
|
|
107
|
+
: {}),
|
|
108
|
+
completedAt: new Date().toISOString(),
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
key(round) {
|
|
112
|
+
return `${this.dispatch.path}/round#${round}`;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
//#endregion
|
|
@@ -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
|
@@ -119,7 +119,7 @@ export type { Expression } from '@noetic-tools/types';
|
|
|
119
119
|
/** @public */
|
|
120
120
|
export { defaultItemSchemaRegistry, ExpressionSchema, ItemSchema, ItemSchemaRegistry, } from '@noetic-tools/types';
|
|
121
121
|
/** @public */
|
|
122
|
-
export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, MergeStrategy, RouteSwitchWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowDocument, WorkflowNode, } from './schemas/workflow.js';
|
|
122
|
+
export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, MergeStrategy, RouteSwitchWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowDocument, WorkflowEmitItems, WorkflowNode, } from './schemas/workflow.js';
|
|
123
123
|
/** @public */
|
|
124
124
|
export { MergeStrategySchema, UntilPredicateSchema, validateWorkflow, WorkflowDocumentSchema, WorkflowNodeSchema, walkWorkflow, workflowDepth, } from './schemas/workflow.js';
|
|
125
125
|
/** @public */
|
|
@@ -166,7 +166,7 @@ export type { AfterModelCallParams, AfterModelCallResult, ApproveToolCallParams,
|
|
|
166
166
|
/** @public */
|
|
167
167
|
export { LedgerEntryKind, SteeringAction } from '@noetic-tools/types';
|
|
168
168
|
/** @public */
|
|
169
|
-
export type { ExecuteStepFn, MergeFn, SettleResult, Snapshot, Step, StepAcpAgent, StepCallModel, StepConditional, StepInParallel, StepInParallelAll, StepInParallelRace, StepInParallelSettle, StepInvokeTool, StepLoop, StepReplay, StepRunCode, StepSpawn, StepWithContext, Until, UntilRun, Verdict, } from '@noetic-tools/types';
|
|
169
|
+
export type { ExecuteStepFn, MergeFn, SettleResult, Snapshot, Step, StepAcpAgent, StepCallModel, StepConditional, StepEmitItems, StepEmitItemsFn, StepEmitItemsOption, StepEmitItemsResult, StepInParallel, StepInParallelAll, StepInParallelRace, StepInParallelSettle, StepInvokeTool, StepLoop, StepReplay, StepRunCode, StepSpawn, StepWithContext, Until, UntilRun, Verdict, } from '@noetic-tools/types';
|
|
170
170
|
/** @public */
|
|
171
171
|
export type { AnsweredAll, AnswerFor, BooleanAnswer, BooleanQuestion, CaseKeyOf, ChoiceAnswer, ChoiceQuestion, ChoiceValues, DecideAnswer, DecideAnswers, DecideQuestion, DecideQuestions, DecideRequest, DecideResponse, DecideStatePart, DecideStep, DecideView, DecisionMeta, DecisionRecord, DecisionSource, LevelLabels, OnDecisionParams, RecallOptions, ScoreAnswer, ScoreLevel, ScoreQuestion, StepDecide, } from '@noetic-tools/types';
|
|
172
172
|
/** @public */
|
|
@@ -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 */
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Context, Item, Step } from '@noetic-tools/types';
|
|
2
|
+
/**
|
|
3
|
+
* Emits what a finished step asks to (`step.emitItems`): appends the items to the item
|
|
4
|
+
* log and streams each as `item_appended` at once, so they reach `getItemStream` while
|
|
5
|
+
* the rest of the workflow still runs. Like the SDK item events, it ignores
|
|
6
|
+
* `step.emit` filtering. Each item is marked in the step's lane record, so the ledger
|
|
7
|
+
* entry that holds it can stream it again on replay.
|
|
8
|
+
*
|
|
9
|
+
* @throws `NoeticError` with kind `item_schema_mismatch` when an item's type is not
|
|
10
|
+
* one the context's item schemas accept.
|
|
11
|
+
*/
|
|
12
|
+
export declare function emitStepItems<TContext, I, O>(step: Step<TContext, I, O>, output: O, ctx: Context<TContext>): Promise<void>;
|
|
13
|
+
/**
|
|
14
|
+
* Puts a replayed entry's items back on the log. The ones at `emitted` (the entry's
|
|
15
|
+
* `streamed` indices) keep their mark, so a parent that records on this resumed run
|
|
16
|
+
* carries it on, and stream again as `item_appended` when the harness sets
|
|
17
|
+
* `emitItemsOnReplay`. The rest go back quietly, as all of them do by default.
|
|
18
|
+
*/
|
|
19
|
+
export declare function appendReplayed<TContext>(ctx: Context<TContext>, items: ReadonlyArray<Item>, emitted: ReadonlyArray<number>): void;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { frameworkCast } from '@noetic-tools/types';
|
|
2
|
+
import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
|
|
3
|
+
import { ContextImpl } from '../runtime/context-impl.js';
|
|
4
|
+
//#region Public API
|
|
5
|
+
/**
|
|
6
|
+
* Emits what a finished step asks to (`step.emitItems`): appends the items to the item
|
|
7
|
+
* log and streams each as `item_appended` at once, so they reach `getItemStream` while
|
|
8
|
+
* the rest of the workflow still runs. Like the SDK item events, it ignores
|
|
9
|
+
* `step.emit` filtering. Each item is marked in the step's lane record, so the ledger
|
|
10
|
+
* entry that holds it can stream it again on replay.
|
|
11
|
+
*
|
|
12
|
+
* @throws `NoeticError` with kind `item_schema_mismatch` when an item's type is not
|
|
13
|
+
* one the context's item schemas accept.
|
|
14
|
+
*/
|
|
15
|
+
export async function emitStepItems(step, output, ctx) {
|
|
16
|
+
const option = step.emitItems;
|
|
17
|
+
if (!option) {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
const items = toItems(option === true ? outputText(output) : await option(output, ctx));
|
|
21
|
+
for (const item of items) {
|
|
22
|
+
appendEmitted(ctx, item);
|
|
23
|
+
streamItem(ctx, item);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Puts a replayed entry's items back on the log. The ones at `emitted` (the entry's
|
|
28
|
+
* `streamed` indices) keep their mark, so a parent that records on this resumed run
|
|
29
|
+
* carries it on, and stream again as `item_appended` when the harness sets
|
|
30
|
+
* `emitItemsOnReplay`. The rest go back quietly, as all of them do by default.
|
|
31
|
+
*/
|
|
32
|
+
export function appendReplayed(ctx, items, emitted) {
|
|
33
|
+
const marked = new Set(emitted);
|
|
34
|
+
const stream = ctx.harness.config.emitItemsOnReplay === true;
|
|
35
|
+
items.forEach((item, i) => {
|
|
36
|
+
if (!marked.has(i)) {
|
|
37
|
+
ctx.itemLog.append(item);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
appendEmitted(ctx, item);
|
|
41
|
+
if (stream) {
|
|
42
|
+
streamItem(ctx, item);
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region Helpers
|
|
48
|
+
function appendEmitted(ctx, item) {
|
|
49
|
+
if (ctx instanceof ContextImpl) {
|
|
50
|
+
ctx.appendEmitted(item);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
ctx.itemLog.append(item);
|
|
54
|
+
}
|
|
55
|
+
function streamItem(ctx, item) {
|
|
56
|
+
emitFrameworkEvent({
|
|
57
|
+
broadcaster: getBroadcaster(frameworkCast(ctx)),
|
|
58
|
+
agentName: ctx.harness.config.name,
|
|
59
|
+
eventType: 'item_appended',
|
|
60
|
+
data: {
|
|
61
|
+
item,
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
function outputText(output) {
|
|
66
|
+
if (typeof output === 'string') {
|
|
67
|
+
return output;
|
|
68
|
+
}
|
|
69
|
+
return output === undefined || output === null ? undefined : JSON.stringify(output);
|
|
70
|
+
}
|
|
71
|
+
function toItems(result) {
|
|
72
|
+
if (result === undefined || result === '') {
|
|
73
|
+
return [];
|
|
74
|
+
}
|
|
75
|
+
if (typeof result === 'string') {
|
|
76
|
+
return [
|
|
77
|
+
assistantMessage(result),
|
|
78
|
+
];
|
|
79
|
+
}
|
|
80
|
+
return isItemList(result)
|
|
81
|
+
? [
|
|
82
|
+
...result,
|
|
83
|
+
]
|
|
84
|
+
: [
|
|
85
|
+
result,
|
|
86
|
+
];
|
|
87
|
+
}
|
|
88
|
+
function isItemList(result) {
|
|
89
|
+
return Array.isArray(result);
|
|
90
|
+
}
|
|
91
|
+
function assistantMessage(text) {
|
|
92
|
+
return {
|
|
93
|
+
id: `emitted-${crypto.randomUUID()}`,
|
|
94
|
+
type: 'message',
|
|
95
|
+
role: 'assistant',
|
|
96
|
+
status: 'completed',
|
|
97
|
+
content: [
|
|
98
|
+
{
|
|
99
|
+
type: 'output_text',
|
|
100
|
+
text,
|
|
101
|
+
annotations: [],
|
|
102
|
+
},
|
|
103
|
+
],
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
//#endregion
|
|
@@ -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
|
],
|