@noetic-tools/core 5.21.0 → 5.22.0-next.2
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/openrouter.d.ts +6 -1
- package/dist/adapters/openrouter.js +10 -0
- package/dist/builders/decide-builders.d.ts +7 -0
- package/dist/builders/tool-builder.d.ts +25 -1
- package/dist/builders/tool-builder.js +25 -1
- package/dist/builders/workflow-control-nodes.js +1 -0
- package/dist/builders/workflow-hydrator.d.ts +19 -0
- package/dist/builders/workflow-hydrator.js +19 -0
- package/dist/builders/workflow-step.js +7 -1
- package/dist/connections/cron-schedule.js +12 -3
- package/dist/connections/durability.d.ts +1 -2
- package/dist/connections/durability.js +1 -4
- package/dist/connections/gates.js +6 -2
- package/dist/connections/harness-wiring.d.ts +5 -0
- package/dist/connections/harness-wiring.js +76 -10
- package/dist/connections/in-memory-connection.d.ts +4 -0
- package/dist/connections/in-memory-connection.js +10 -0
- package/dist/connections/model-tools.js +5 -1
- package/dist/connections/registry.d.ts +6 -2
- package/dist/connections/registry.js +10 -0
- package/dist/connections/sources.js +261 -20
- package/dist/connections/triggers.d.ts +62 -2
- package/dist/connections/triggers.js +375 -35
- package/dist/harness/agent-harness.d.ts +317 -4
- package/dist/harness/agent-harness.js +1264 -96
- package/dist/harness/connection-gate.d.ts +3 -0
- package/dist/harness/connection-gate.js +4 -0
- package/dist/harness/decide-call.d.ts +15 -0
- package/dist/harness/decide-call.js +57 -7
- package/dist/harness/deps/runtime.d.ts +3 -0
- package/dist/harness/deps/runtime.js +2 -0
- package/dist/harness/flow-version.d.ts +13 -0
- package/dist/harness/flow-version.js +66 -0
- package/dist/harness/harness-options.d.ts +91 -0
- package/dist/harness/llm-client.d.ts +2 -0
- package/dist/harness/llm-client.js +9 -5
- package/dist/harness/model-call.js +8 -0
- package/dist/harness/model-rounds.d.ts +30 -0
- package/dist/harness/model-rounds.js +146 -1
- package/dist/harness/model-tool-round.d.ts +3 -0
- package/dist/harness/model-tool-round.js +249 -22
- package/dist/harness/park-watchers.d.ts +93 -0
- package/dist/harness/park-watchers.js +217 -0
- package/dist/harness/read-decision.d.ts +23 -0
- package/dist/harness/read-decision.js +100 -0
- package/dist/harness/spend.js +4 -0
- package/dist/harness/steer-inbox.js +3 -1
- package/dist/harness/thread-record.d.ts +77 -1
- package/dist/harness/thread-record.js +272 -13
- package/dist/index.d.ts +22 -8
- package/dist/index.js +12 -2
- package/dist/interpreter/acp-resume.d.ts +77 -0
- package/dist/interpreter/acp-resume.js +164 -0
- package/dist/interpreter/acp-tools.d.ts +11 -0
- package/dist/interpreter/acp-tools.js +94 -7
- package/dist/interpreter/connection-steps.d.ts +24 -1
- package/dist/interpreter/connection-steps.js +77 -2
- package/dist/interpreter/execute-acp-agent.js +111 -15
- package/dist/interpreter/execute-action.js +7 -0
- package/dist/interpreter/execute-call.js +30 -4
- package/dist/interpreter/execute-control.js +21 -0
- package/dist/interpreter/execute-decide.js +5 -0
- package/dist/interpreter/execute-invoke-tool.js +149 -5
- package/dist/interpreter/execute-wait.js +67 -9
- package/dist/interpreter/execute.js +4 -0
- package/dist/interpreter/turn-ending.d.ts +15 -0
- package/dist/interpreter/turn-ending.js +46 -0
- package/dist/portable/builders.d.ts +1 -1
- package/dist/portable/builders.js +1 -1
- package/dist/portable/runtime.d.ts +4 -0
- package/dist/portable/runtime.js +2 -0
- package/dist/runtime/durable/parking.d.ts +61 -0
- package/dist/runtime/durable/parking.js +137 -0
- package/dist/runtime/durable/session-store.d.ts +38 -0
- package/dist/runtime/durable/session-store.js +79 -1
- package/dist/runtime/durable/step-ledger.d.ts +121 -2
- package/dist/runtime/durable/step-ledger.js +352 -15
- package/dist/runtime/durable/turn-lease.d.ts +128 -0
- package/dist/runtime/durable/turn-lease.js +307 -0
- package/dist/runtime/event-broadcaster.d.ts +9 -1
- package/dist/runtime/event-broadcaster.js +16 -1
- package/dist/runtime/held-calls.d.ts +192 -0
- package/dist/runtime/held-calls.js +496 -0
- package/dist/runtime/in-memory-storage.d.ts +10 -1
- package/dist/runtime/in-memory-storage.js +20 -2
- package/dist/runtime/message-queue.d.ts +2 -0
- package/dist/runtime/message-queue.js +8 -0
- package/dist/runtime/output-store.d.ts +88 -0
- package/dist/runtime/output-store.js +241 -0
- package/dist/runtime/session-runner.d.ts +18 -2
- package/dist/runtime/session-runner.js +88 -3
- package/dist/runtime/session-streams.d.ts +28 -7
- package/dist/runtime/session-streams.js +112 -67
- package/dist/runtime/tool-approval.d.ts +46 -6
- package/dist/runtime/tool-approval.js +160 -38
- package/dist/runtime/tool-call.d.ts +34 -2
- package/dist/runtime/tool-call.js +182 -13
- package/dist/runtime/tool-context.d.ts +15 -1
- package/dist/runtime/tool-context.js +38 -2
- package/package.json +3 -3
- package/schema/noetic-workflow.schema.json +27 -0
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { ItemStream } from './session-streams.js';
|
|
3
|
+
//#region Types
|
|
4
|
+
const OutputSnapshotSchema = z
|
|
5
|
+
.object({
|
|
6
|
+
type: z.string(),
|
|
7
|
+
id: z.string().optional(),
|
|
8
|
+
isComplete: z.boolean().optional(),
|
|
9
|
+
})
|
|
10
|
+
.catchall(z.unknown());
|
|
11
|
+
/**
|
|
12
|
+
* @public A thread's display output could not be read or written. `scope` is the
|
|
13
|
+
* thread id; `cause` is what storage, or the snapshot check, failed with.
|
|
14
|
+
*/
|
|
15
|
+
export class OutputStoreError extends Error {
|
|
16
|
+
scope;
|
|
17
|
+
constructor(options) {
|
|
18
|
+
super(options.message, {
|
|
19
|
+
cause: options.cause,
|
|
20
|
+
});
|
|
21
|
+
this.name = 'OutputStoreError';
|
|
22
|
+
this.scope = options.scope;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region Helpers
|
|
27
|
+
/** How many times one write is tried before the failure is kept. */
|
|
28
|
+
const WRITE_ATTEMPTS = 3;
|
|
29
|
+
/** How many times a write may lose to another writer before it is a failure. */
|
|
30
|
+
const SWAP_ATTEMPTS = 20;
|
|
31
|
+
const WRITE_RETRY_MS = 10;
|
|
32
|
+
/** @internal The storage key a thread's display output is kept under. */
|
|
33
|
+
export function outputKey(scope) {
|
|
34
|
+
return `output:${scope}`;
|
|
35
|
+
}
|
|
36
|
+
/** What makes two snapshots the same item: its id, else its call, else its content. */
|
|
37
|
+
function keyOf(item) {
|
|
38
|
+
if (typeof item.id === 'string') {
|
|
39
|
+
return item.id;
|
|
40
|
+
}
|
|
41
|
+
if (typeof item.callId === 'string') {
|
|
42
|
+
return `${item.type}:${item.callId}`;
|
|
43
|
+
}
|
|
44
|
+
return JSON.stringify(item);
|
|
45
|
+
}
|
|
46
|
+
function wait(ms) {
|
|
47
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
48
|
+
}
|
|
49
|
+
//#endregion
|
|
50
|
+
//#region OutputStore
|
|
51
|
+
/**
|
|
52
|
+
* @public A thread's display output, kept in storage under `output:<scope>`:
|
|
53
|
+
* the latest snapshot of every item its stream produced, including items that
|
|
54
|
+
* never finished. It is for showing a thread again, in a new process or after a
|
|
55
|
+
* failed run. Nothing resumes from it: checkpoints, the step ledger and the
|
|
56
|
+
* model's history are stored apart and never read here.
|
|
57
|
+
*
|
|
58
|
+
* `record` and `write` queue snapshots and save them in the background, one
|
|
59
|
+
* write at a time, each holding the whole output. `flush` and `read` wait for
|
|
60
|
+
* what is queued and throw `OutputStoreError` when it could not be saved; the
|
|
61
|
+
* snapshots stay queued, so the next call tries again. On storage with `swap` a
|
|
62
|
+
* write never replaces what another store saved meanwhile.
|
|
63
|
+
*/
|
|
64
|
+
export class OutputStore {
|
|
65
|
+
storage;
|
|
66
|
+
scope;
|
|
67
|
+
stream;
|
|
68
|
+
pending = new Map();
|
|
69
|
+
writing;
|
|
70
|
+
failure;
|
|
71
|
+
constructor(storage, scope, schemas) {
|
|
72
|
+
this.storage = storage;
|
|
73
|
+
this.scope = scope;
|
|
74
|
+
this.stream = new ItemStream(schemas);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Fold one stream event into the output. Never throws: an event that cannot be
|
|
78
|
+
* read as display output is left out, with a warning, and the run goes on.
|
|
79
|
+
*/
|
|
80
|
+
record(event) {
|
|
81
|
+
try {
|
|
82
|
+
for (const item of this.stream.push(event)) {
|
|
83
|
+
this.queue(OutputSnapshotSchema.parse(item));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
catch (cause) {
|
|
87
|
+
console.warn(`[noetic] left a stream event out of the display output of "${this.scope}":`, cause);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
this.start();
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Save display snapshots, each replacing the stored one with its id, and resolve
|
|
94
|
+
* the whole stored output.
|
|
95
|
+
*
|
|
96
|
+
* @throws OutputStoreError when `items` are not snapshots, or storage fails.
|
|
97
|
+
*/
|
|
98
|
+
async write(items) {
|
|
99
|
+
const parsed = OutputSnapshotSchema.array().safeParse(items);
|
|
100
|
+
if (!parsed.success) {
|
|
101
|
+
throw this.error('Could not read display snapshots.', parsed.error);
|
|
102
|
+
}
|
|
103
|
+
for (const item of parsed.data) {
|
|
104
|
+
this.queue(item);
|
|
105
|
+
}
|
|
106
|
+
return this.read();
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The stored output, after everything queued is saved.
|
|
110
|
+
*
|
|
111
|
+
* @throws OutputStoreError when storage fails or holds something else.
|
|
112
|
+
*/
|
|
113
|
+
async read() {
|
|
114
|
+
await this.flush();
|
|
115
|
+
return (await this.load()).items;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Wait until everything queued is saved.
|
|
119
|
+
*
|
|
120
|
+
* @throws OutputStoreError when it could not be. What was queued stays queued,
|
|
121
|
+
* and every flush throws until a later one saves it.
|
|
122
|
+
*/
|
|
123
|
+
async flush() {
|
|
124
|
+
this.start();
|
|
125
|
+
while (this.writing) {
|
|
126
|
+
await this.writing;
|
|
127
|
+
}
|
|
128
|
+
// Not cleared here: two callers waiting on one failed write are both told.
|
|
129
|
+
if (this.failure) {
|
|
130
|
+
throw this.failure;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
queue(item) {
|
|
134
|
+
this.pending.set(keyOf(item), structuredClone(item));
|
|
135
|
+
}
|
|
136
|
+
start() {
|
|
137
|
+
if (this.pending.size === 0 || this.writing) {
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
this.writing = this.drain().then(() => {
|
|
141
|
+
this.failure = undefined;
|
|
142
|
+
this.writing = undefined;
|
|
143
|
+
this.start();
|
|
144
|
+
}, (cause) => {
|
|
145
|
+
this.failure =
|
|
146
|
+
cause instanceof OutputStoreError
|
|
147
|
+
? cause
|
|
148
|
+
: this.error('Could not write streamed output.', cause);
|
|
149
|
+
this.writing = undefined;
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
/** What storage holds under the key, as it is stored and as snapshots. */
|
|
153
|
+
async load() {
|
|
154
|
+
try {
|
|
155
|
+
const raw = (await this.storage.get(outputKey(this.scope))) ?? null;
|
|
156
|
+
return {
|
|
157
|
+
raw,
|
|
158
|
+
items: OutputSnapshotSchema.array().parse(raw ?? []),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
catch (cause) {
|
|
162
|
+
throw this.error('Could not read streamed output.', cause);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/** Save what is queued over what is stored, until nothing is queued. */
|
|
166
|
+
async drain() {
|
|
167
|
+
while (this.pending.size > 0) {
|
|
168
|
+
const batch = new Map(this.pending);
|
|
169
|
+
this.pending.clear();
|
|
170
|
+
try {
|
|
171
|
+
await this.save(batch);
|
|
172
|
+
}
|
|
173
|
+
catch (cause) {
|
|
174
|
+
// Put back what was not saved, behind anything newer queued meanwhile.
|
|
175
|
+
for (const [key, item] of batch) {
|
|
176
|
+
if (!this.pending.has(key)) {
|
|
177
|
+
this.pending.set(key, item);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
throw cause;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
async save(batch) {
|
|
185
|
+
let lost = 0;
|
|
186
|
+
for (let attempt = 1;;) {
|
|
187
|
+
try {
|
|
188
|
+
if (await this.saveOver(batch)) {
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
catch (cause) {
|
|
193
|
+
if (cause instanceof OutputStoreError) {
|
|
194
|
+
throw cause;
|
|
195
|
+
}
|
|
196
|
+
if (attempt >= WRITE_ATTEMPTS) {
|
|
197
|
+
throw this.error('Could not write streamed output.', cause);
|
|
198
|
+
}
|
|
199
|
+
attempt++;
|
|
200
|
+
await wait(WRITE_RETRY_MS);
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
// Another writer saved first: merge over what it wrote.
|
|
204
|
+
lost++;
|
|
205
|
+
if (lost >= SWAP_ATTEMPTS) {
|
|
206
|
+
throw this.error('Could not write streamed output.', new Error(`Lost to another writer ${lost} times.`));
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Write `batch` over what is stored now. On storage with `swap` the write lands
|
|
212
|
+
* only if nothing else was saved since the read, and false means it did not.
|
|
213
|
+
*/
|
|
214
|
+
async saveOver(batch) {
|
|
215
|
+
const stored = await this.load();
|
|
216
|
+
const held = new Map(stored.items.map((item) => [
|
|
217
|
+
keyOf(item),
|
|
218
|
+
item,
|
|
219
|
+
]));
|
|
220
|
+
for (const [key, item] of batch) {
|
|
221
|
+
held.set(key, item);
|
|
222
|
+
}
|
|
223
|
+
const next = [
|
|
224
|
+
...held.values(),
|
|
225
|
+
];
|
|
226
|
+
const key = outputKey(this.scope);
|
|
227
|
+
if (!this.storage.swap) {
|
|
228
|
+
await this.storage.set(key, next);
|
|
229
|
+
return true;
|
|
230
|
+
}
|
|
231
|
+
return this.storage.swap(key, stored.raw, next);
|
|
232
|
+
}
|
|
233
|
+
error(message, cause) {
|
|
234
|
+
return new OutputStoreError({
|
|
235
|
+
scope: this.scope,
|
|
236
|
+
message,
|
|
237
|
+
cause,
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
//#endregion
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Context, HarnessResponse, HarnessStatus, Item, SessionUsage } from '@noetic-tools/types';
|
|
1
|
+
import type { Context, HarnessResponse, HarnessStatus, HeldCall, Item, SessionUsage } from '@noetic-tools/types';
|
|
2
2
|
import { EventBroadcaster } from './event-broadcaster.js';
|
|
3
3
|
import type { QueuedMessage } from './message-queue.js';
|
|
4
4
|
import { MessageQueue } from './message-queue.js';
|
|
@@ -17,7 +17,7 @@ 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 | Promise<Context>;
|
|
20
|
+
export type CreateContextFn = (items: ReadonlyArray<Item>, turnId: string, messages: ReadonlyArray<QueuedMessage>) => Context | undefined | Promise<Context | undefined>;
|
|
21
21
|
/** @internal What one turn spent: its context's usage at the end, less at the start. */
|
|
22
22
|
export interface TurnUsage {
|
|
23
23
|
inputTokens: number;
|
|
@@ -36,6 +36,8 @@ export interface SessionRunnerOpts {
|
|
|
36
36
|
* writes it to storage and hands the stored totals back through `seedUsage`.
|
|
37
37
|
*/
|
|
38
38
|
readonly onTurnUsage?: (usage: TurnUsage) => Promise<void>;
|
|
39
|
+
/** The tool calls the turn on `ctx` holds for a person, for a parked response. */
|
|
40
|
+
readonly heldCalls?: (ctx: Context) => Promise<ReadonlyArray<HeldCall>>;
|
|
39
41
|
}
|
|
40
42
|
/**
|
|
41
43
|
* @internal
|
|
@@ -70,9 +72,12 @@ export declare class SessionRunner {
|
|
|
70
72
|
private totalCost;
|
|
71
73
|
private totalBilledCost;
|
|
72
74
|
private readonly onTurnUsage?;
|
|
75
|
+
private readonly heldCalls?;
|
|
73
76
|
private currentController?;
|
|
74
77
|
private currentCtx?;
|
|
75
78
|
private loopPromise?;
|
|
79
|
+
/** The message ids of the turn being started or run, set before anything is awaited. */
|
|
80
|
+
private currentIds;
|
|
76
81
|
private lastResponse?;
|
|
77
82
|
private lastError?;
|
|
78
83
|
private readonly responseWaiters;
|
|
@@ -83,6 +88,10 @@ export declare class SessionRunner {
|
|
|
83
88
|
/** Queue a message. A steer that arrives mid-turn is announced first, so
|
|
84
89
|
* `steer_accepted` always precedes the `inbox_injected` that applies it. */
|
|
85
90
|
enqueue(message: QueuedMessage): void;
|
|
91
|
+
/** True while the turn being started or run took the message with this id. */
|
|
92
|
+
isRunning(messageId: string): boolean;
|
|
93
|
+
/** Resolves once the queue loop has gone idle: no turn running or closing out. */
|
|
94
|
+
whenIdle(): Promise<void>;
|
|
86
95
|
/** Cumulative token usage and cost across all turns this session has run. */
|
|
87
96
|
getUsage(): SessionUsage;
|
|
88
97
|
/** Replace the totals with ones a durable host read back from storage. */
|
|
@@ -95,6 +104,13 @@ export declare class SessionRunner {
|
|
|
95
104
|
* queued, the caller is asking about the NEXT response — we must wait
|
|
96
105
|
* for that turn rather than reject with the stale error. */
|
|
97
106
|
getAgentResponse(): Promise<HarnessResponse>;
|
|
107
|
+
/**
|
|
108
|
+
* Answer whoever is waiting with a response no turn of this runner produced: the
|
|
109
|
+
* recorded answer to a message that was delivered again.
|
|
110
|
+
*/
|
|
111
|
+
answerWith(response: HarnessResponse, messageId: string): void;
|
|
112
|
+
/** The abort signal of the turn in flight, from before its context is built. */
|
|
113
|
+
get signal(): AbortSignal | undefined;
|
|
98
114
|
/** Cancel the in-flight turn. Does NOT re-kick — callers that want restart
|
|
99
115
|
* behaviour should enqueue a message before/after calling abort. */
|
|
100
116
|
abort(reason?: string): Promise<void>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isNoeticError } from '@noetic-tools/types';
|
|
2
2
|
import { emitFrameworkEvent } from './broadcaster-utils.js';
|
|
3
|
+
import { ContextImpl } from './context-impl.js';
|
|
3
4
|
import { EventBroadcaster } from './event-broadcaster.js';
|
|
4
5
|
import { inputToItems, isSteer, MessageQueue } from './message-queue.js';
|
|
5
6
|
//#endregion
|
|
@@ -48,9 +49,12 @@ export class SessionRunner {
|
|
|
48
49
|
totalCost = 0;
|
|
49
50
|
totalBilledCost = 0;
|
|
50
51
|
onTurnUsage;
|
|
52
|
+
heldCalls;
|
|
51
53
|
currentController;
|
|
52
54
|
currentCtx;
|
|
53
55
|
loopPromise;
|
|
56
|
+
/** The message ids of the turn being started or run, set before anything is awaited. */
|
|
57
|
+
currentIds = [];
|
|
54
58
|
lastResponse;
|
|
55
59
|
lastError;
|
|
56
60
|
responseWaiters = [];
|
|
@@ -60,6 +64,7 @@ export class SessionRunner {
|
|
|
60
64
|
this.runTurn = opts.runTurn;
|
|
61
65
|
this.createContext = opts.createContext;
|
|
62
66
|
this.onTurnUsage = opts.onTurnUsage;
|
|
67
|
+
this.heldCalls = opts.heldCalls;
|
|
63
68
|
this.queue.subscribe(() => {
|
|
64
69
|
this.kick();
|
|
65
70
|
});
|
|
@@ -88,6 +93,16 @@ export class SessionRunner {
|
|
|
88
93
|
}
|
|
89
94
|
this.queue.enqueue(message);
|
|
90
95
|
}
|
|
96
|
+
/** True while the turn being started or run took the message with this id. */
|
|
97
|
+
isRunning(messageId) {
|
|
98
|
+
return this.status.kind !== 'idle' && this.currentIds.includes(messageId);
|
|
99
|
+
}
|
|
100
|
+
/** Resolves once the queue loop has gone idle: no turn running or closing out. */
|
|
101
|
+
async whenIdle() {
|
|
102
|
+
while (this.loopPromise) {
|
|
103
|
+
await this.loopPromise.catch(() => undefined);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
91
106
|
/** Cumulative token usage and cost across all turns this session has run. */
|
|
92
107
|
getUsage() {
|
|
93
108
|
return {
|
|
@@ -127,6 +142,31 @@ export class SessionRunner {
|
|
|
127
142
|
});
|
|
128
143
|
});
|
|
129
144
|
}
|
|
145
|
+
/**
|
|
146
|
+
* Answer whoever is waiting with a response no turn of this runner produced: the
|
|
147
|
+
* recorded answer to a message that was delivered again.
|
|
148
|
+
*/
|
|
149
|
+
answerWith(response, messageId) {
|
|
150
|
+
this.lastResponse = response;
|
|
151
|
+
this.lastError = undefined;
|
|
152
|
+
emitFrameworkEvent({
|
|
153
|
+
broadcaster: this.broadcaster,
|
|
154
|
+
agentName: this.agentName,
|
|
155
|
+
eventType: 'turn_replayed',
|
|
156
|
+
data: {
|
|
157
|
+
messageIds: [
|
|
158
|
+
messageId,
|
|
159
|
+
],
|
|
160
|
+
// Nothing streams for a replayed turn: its answer is here for those who post it.
|
|
161
|
+
text: response.text,
|
|
162
|
+
},
|
|
163
|
+
});
|
|
164
|
+
this.resolveWaiters(response);
|
|
165
|
+
}
|
|
166
|
+
/** The abort signal of the turn in flight, from before its context is built. */
|
|
167
|
+
get signal() {
|
|
168
|
+
return this.currentController?.signal;
|
|
169
|
+
}
|
|
130
170
|
/** Cancel the in-flight turn. Does NOT re-kick — callers that want restart
|
|
131
171
|
* behaviour should enqueue a message before/after calling abort. */
|
|
132
172
|
async abort(reason) {
|
|
@@ -176,6 +216,7 @@ export class SessionRunner {
|
|
|
176
216
|
async runOneTurn(messages) {
|
|
177
217
|
const turnId = crypto.randomUUID();
|
|
178
218
|
const startedAt = Date.now();
|
|
219
|
+
this.currentIds = messages.map((message) => message.id);
|
|
179
220
|
this.status = {
|
|
180
221
|
kind: 'generating',
|
|
181
222
|
startedAt,
|
|
@@ -189,7 +230,20 @@ export class SessionRunner {
|
|
|
189
230
|
const items = mergeInputsToItems(messages);
|
|
190
231
|
let ctx;
|
|
191
232
|
try {
|
|
192
|
-
|
|
233
|
+
const built = await this.createContext(items, turnId, messages);
|
|
234
|
+
if (built === undefined) {
|
|
235
|
+
// The host set these messages aside (the thread's turn is parked or stuck):
|
|
236
|
+
// no turn starts, and whoever is waiting keeps the answer they had.
|
|
237
|
+
this.currentController = undefined;
|
|
238
|
+
this.status = {
|
|
239
|
+
kind: 'idle',
|
|
240
|
+
};
|
|
241
|
+
if (this.lastResponse) {
|
|
242
|
+
this.resolveWaiters(this.lastResponse);
|
|
243
|
+
}
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
ctx = built;
|
|
193
247
|
}
|
|
194
248
|
catch (err) {
|
|
195
249
|
this.failBeforeStart(turnId, err);
|
|
@@ -227,16 +281,38 @@ export class SessionRunner {
|
|
|
227
281
|
try {
|
|
228
282
|
const text = await this.runTurn(ctx, turn, controller.signal);
|
|
229
283
|
await this.settleUsage(start, ctx);
|
|
230
|
-
const
|
|
284
|
+
const wakeAt = parkedUntilOf(ctx);
|
|
285
|
+
const held = wakeAt === undefined ? [] : ((await this.heldCalls?.(ctx)) ?? []);
|
|
286
|
+
const response = wakeAt === undefined
|
|
287
|
+
? buildResponse(text, ctx)
|
|
288
|
+
: {
|
|
289
|
+
...buildResponse(text, ctx),
|
|
290
|
+
...(held.length > 0
|
|
291
|
+
? {
|
|
292
|
+
held,
|
|
293
|
+
}
|
|
294
|
+
: {}),
|
|
295
|
+
// A turn parked on a held call alone has no time to wake at.
|
|
296
|
+
parked: Number.isFinite(wakeAt)
|
|
297
|
+
? {
|
|
298
|
+
wakeAt,
|
|
299
|
+
}
|
|
300
|
+
: {},
|
|
301
|
+
};
|
|
231
302
|
this.lastResponse = response;
|
|
232
303
|
this.lastError = undefined;
|
|
233
304
|
emitFrameworkEvent({
|
|
234
305
|
broadcaster: this.broadcaster,
|
|
235
306
|
agentName: this.agentName,
|
|
236
|
-
eventType: 'turn_completed',
|
|
307
|
+
eventType: wakeAt === undefined ? 'turn_completed' : 'turn_parked',
|
|
237
308
|
data: {
|
|
238
309
|
turnId,
|
|
239
310
|
durationMs: Date.now() - startedAt,
|
|
311
|
+
...(wakeAt === undefined
|
|
312
|
+
? {}
|
|
313
|
+
: {
|
|
314
|
+
wakeAt,
|
|
315
|
+
}),
|
|
240
316
|
},
|
|
241
317
|
});
|
|
242
318
|
// Only resolve waiters when the queue is fully drained; otherwise let
|
|
@@ -252,6 +328,11 @@ export class SessionRunner {
|
|
|
252
328
|
await this.settleUsage(start, ctx);
|
|
253
329
|
const error = err instanceof Error ? err : new Error(String(err));
|
|
254
330
|
this.lastError = error;
|
|
331
|
+
// A turn that parked and then failed once woken did not end parked: stop
|
|
332
|
+
// answering with the parked response.
|
|
333
|
+
if (this.lastResponse?.parked) {
|
|
334
|
+
this.lastResponse = undefined;
|
|
335
|
+
}
|
|
255
336
|
emitFrameworkEvent({
|
|
256
337
|
broadcaster: this.broadcaster,
|
|
257
338
|
agentName: this.agentName,
|
|
@@ -345,6 +426,10 @@ function usageSince(start, ctx) {
|
|
|
345
426
|
billedCost: now.billedCost - start.billedCost,
|
|
346
427
|
};
|
|
347
428
|
}
|
|
429
|
+
/** When the turn on `ctx` parked until, or undefined when it ran to its end. */
|
|
430
|
+
function parkedUntilOf(ctx) {
|
|
431
|
+
return ctx instanceof ContextImpl ? ctx.ledger?.parking.parkedUntil : undefined;
|
|
432
|
+
}
|
|
348
433
|
function buildResponse(text, ctx) {
|
|
349
434
|
return {
|
|
350
435
|
items: ctx.itemLog.items,
|
|
@@ -1,14 +1,35 @@
|
|
|
1
|
-
import type { ItemSchemaRegistry, StreamingItem } from '@noetic-tools/types';
|
|
1
|
+
import type { ItemSchemaRegistry, StreamEvent, StreamingItem } from '@noetic-tools/types';
|
|
2
2
|
import type { EventBroadcaster } from './event-broadcaster.js';
|
|
3
3
|
/** @internal Yield text deltas from the session broadcaster. */
|
|
4
4
|
export declare function filterTextStream(broadcaster: EventBroadcaster): AsyncIterable<string>;
|
|
5
5
|
/** @internal Yield reasoning-token deltas from the session broadcaster. */
|
|
6
6
|
export declare function filterReasoningStream(broadcaster: EventBroadcaster): AsyncIterable<string>;
|
|
7
|
-
/**
|
|
8
|
-
*
|
|
9
|
-
* multiple turns within a session don't collide.
|
|
7
|
+
/**
|
|
8
|
+
* @internal Yield cumulative StreamingItem snapshots.
|
|
10
9
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
10
|
+
* SDK events cover model output only; framework-authored items — turn input
|
|
11
|
+
* messages, between-rounds injections, tool results — arrive via the
|
|
12
|
+
* `item_appended` framework event and are yielded already complete.
|
|
13
|
+
*/
|
|
14
14
|
export declare function buildItemStream(broadcaster: EventBroadcaster, itemSchemas?: ItemSchemaRegistry): AsyncIterable<StreamingItem>;
|
|
15
|
+
/**
|
|
16
|
+
* @internal Folds stream events into item snapshots, one event at a time: what
|
|
17
|
+
* `getItemStream` yields and what an `OutputStore` keeps.
|
|
18
|
+
*
|
|
19
|
+
* An event that names its item is matched by that id, which keeps model calls
|
|
20
|
+
* running at once apart. One that does not is matched by round and output index,
|
|
21
|
+
* the round counted from `response.created`, so the items of later tool rounds
|
|
22
|
+
* and later turns do not collide.
|
|
23
|
+
*/
|
|
24
|
+
export declare class ItemStream {
|
|
25
|
+
private readonly accumulators;
|
|
26
|
+
private readonly byId;
|
|
27
|
+
private roundOffset;
|
|
28
|
+
private readonly itemSchemas;
|
|
29
|
+
constructor(itemSchemas?: ItemSchemaRegistry);
|
|
30
|
+
/** The snapshots `event` produces: none, or one. */
|
|
31
|
+
push(event: StreamEvent): Generator<StreamingItem>;
|
|
32
|
+
private add;
|
|
33
|
+
/** The accumulator `event` is about. `missingIndex` stands in for an absent output index. */
|
|
34
|
+
private find;
|
|
35
|
+
}
|