@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,496 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Held tool calls: a call left open for a person (spec 08 § Held tool calls).
|
|
3
|
+
*
|
|
4
|
+
* A call is held when the approver answers `hold`, when a tool that needs
|
|
5
|
+
* approval has no approver, or when a tool returns `hold()` in place of a
|
|
6
|
+
* result. Nothing is written to the conversation for it. Its record sits in
|
|
7
|
+
* storage until a decision passed to `harness.execute()` settles it; then the round walks its calls
|
|
8
|
+
* again, and this time the call has an answer.
|
|
9
|
+
*
|
|
10
|
+
* The record is the whole state, so a held call survives the process: a parked
|
|
11
|
+
* turn resumed on another harness finds the same record and the same answer.
|
|
12
|
+
*/
|
|
13
|
+
import { NoeticErrorImpl } from '@noetic-tools/types';
|
|
14
|
+
import { z } from 'zod';
|
|
15
|
+
import { emitFrameworkEvent, getBroadcaster } from './broadcaster-utils.js';
|
|
16
|
+
import { ContextImpl, rootIdOf } from './context-impl.js';
|
|
17
|
+
import { hashStepInput } from './durable/step-ledger.js';
|
|
18
|
+
import { createInMemoryStorage } from './in-memory-storage.js';
|
|
19
|
+
//#region Types
|
|
20
|
+
const ResolutionSchema = z.object({
|
|
21
|
+
/** An approval's answer. */
|
|
22
|
+
action: z
|
|
23
|
+
.enum([
|
|
24
|
+
'allow',
|
|
25
|
+
'deny',
|
|
26
|
+
'guide',
|
|
27
|
+
])
|
|
28
|
+
.optional(),
|
|
29
|
+
guidance: z.string().optional(),
|
|
30
|
+
/** A held result's value. Present, even as `null`, when `hasOutput` is set. */
|
|
31
|
+
output: z.unknown().optional(),
|
|
32
|
+
hasOutput: z.boolean().optional(),
|
|
33
|
+
});
|
|
34
|
+
const HeldRecordSchema = z.object({
|
|
35
|
+
callId: z.string(),
|
|
36
|
+
name: z.string(),
|
|
37
|
+
args: z.unknown(),
|
|
38
|
+
/** Hash of the call's name and arguments: an answer is for this call and no other. */
|
|
39
|
+
argsHash: z.string(),
|
|
40
|
+
/** Why the call is held: see `HeldCall.reason`. */
|
|
41
|
+
reason: z.enum([
|
|
42
|
+
'approval',
|
|
43
|
+
'result',
|
|
44
|
+
'outcome',
|
|
45
|
+
]),
|
|
46
|
+
dueAt: z.number().optional(),
|
|
47
|
+
onDue: z
|
|
48
|
+
.enum([
|
|
49
|
+
'deny',
|
|
50
|
+
'keep',
|
|
51
|
+
])
|
|
52
|
+
.optional(),
|
|
53
|
+
/** Passed back by a tool's `hold()`, for whoever answers. */
|
|
54
|
+
request: z.unknown().optional(),
|
|
55
|
+
resolution: ResolutionSchema.optional(),
|
|
56
|
+
});
|
|
57
|
+
/**
|
|
58
|
+
* @internal
|
|
59
|
+
* Thrown by an approval seam to say "hold this call". Caught where the call's
|
|
60
|
+
* record can be written; never reaches a caller of the harness.
|
|
61
|
+
*/
|
|
62
|
+
export class HoldSignal extends Error {
|
|
63
|
+
due;
|
|
64
|
+
constructor(due = {}) {
|
|
65
|
+
super('The tool call is held for a person.');
|
|
66
|
+
this.due = due;
|
|
67
|
+
this.name = 'HoldSignal';
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
//#endregion
|
|
71
|
+
//#region Helpers
|
|
72
|
+
/** The hash that ties an answer to one call: its tool name and arguments. */
|
|
73
|
+
export function heldArgsHash(name, args) {
|
|
74
|
+
return (hashStepInput({
|
|
75
|
+
name,
|
|
76
|
+
args,
|
|
77
|
+
}) ?? '');
|
|
78
|
+
}
|
|
79
|
+
const IntentSchema = z.object({
|
|
80
|
+
argsHash: z.string(),
|
|
81
|
+
});
|
|
82
|
+
function intentPrefix(executionId) {
|
|
83
|
+
return `execution:${executionId}:intent:`;
|
|
84
|
+
}
|
|
85
|
+
/** How often a live turn re-reads held calls that another process may have answered. */
|
|
86
|
+
const HELD_POLL_MS = 2e3;
|
|
87
|
+
function heldPrefix(executionId) {
|
|
88
|
+
return `execution:${executionId}:held:`;
|
|
89
|
+
}
|
|
90
|
+
function refused(callId, reason) {
|
|
91
|
+
return new NoeticErrorImpl({
|
|
92
|
+
kind: 'hold_refused',
|
|
93
|
+
callId,
|
|
94
|
+
reason,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
function sameResolution(a, b) {
|
|
98
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
99
|
+
}
|
|
100
|
+
function toResolutionRecord(resolution) {
|
|
101
|
+
if ('action' in resolution) {
|
|
102
|
+
return {
|
|
103
|
+
action: resolution.action,
|
|
104
|
+
...(resolution.guidance === undefined
|
|
105
|
+
? {}
|
|
106
|
+
: {
|
|
107
|
+
guidance: resolution.guidance,
|
|
108
|
+
}),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
output: resolution.output,
|
|
113
|
+
hasOutput: true,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/** A held record as hosts see it. */
|
|
117
|
+
export function toHeldCall(record) {
|
|
118
|
+
return {
|
|
119
|
+
callId: record.callId,
|
|
120
|
+
name: record.name,
|
|
121
|
+
args: record.args,
|
|
122
|
+
argsHash: record.argsHash,
|
|
123
|
+
reason: record.reason,
|
|
124
|
+
...(record.dueAt === undefined
|
|
125
|
+
? {}
|
|
126
|
+
: {
|
|
127
|
+
dueAt: record.dueAt,
|
|
128
|
+
}),
|
|
129
|
+
...(record.onDue === undefined
|
|
130
|
+
? {}
|
|
131
|
+
: {
|
|
132
|
+
onDue: record.onDue,
|
|
133
|
+
}),
|
|
134
|
+
...(record.request === undefined
|
|
135
|
+
? {}
|
|
136
|
+
: {
|
|
137
|
+
request: record.request,
|
|
138
|
+
}),
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
//#endregion
|
|
142
|
+
//#region HeldCalls
|
|
143
|
+
/** @internal One harness's held calls: their records, and who is waiting on them here. */
|
|
144
|
+
export class HeldCalls {
|
|
145
|
+
storage;
|
|
146
|
+
clock;
|
|
147
|
+
waiters = new Map();
|
|
148
|
+
constructor(storage, clock) {
|
|
149
|
+
this.storage = storage;
|
|
150
|
+
this.clock = clock;
|
|
151
|
+
}
|
|
152
|
+
now() {
|
|
153
|
+
return this.clock();
|
|
154
|
+
}
|
|
155
|
+
/** The record of `callId`, when the call is held. */
|
|
156
|
+
async load(executionId, callId) {
|
|
157
|
+
const raw = await this.storage.get(`${heldPrefix(executionId)}${callId}`);
|
|
158
|
+
const parsed = raw === null ? undefined : HeldRecordSchema.safeParse(raw);
|
|
159
|
+
return parsed?.success ? parsed.data : undefined;
|
|
160
|
+
}
|
|
161
|
+
/** Answers being taken, by execution and call, so two never overlap. */
|
|
162
|
+
answering = new Map();
|
|
163
|
+
/** Every held call of an execution. */
|
|
164
|
+
async list(executionId) {
|
|
165
|
+
const found = [];
|
|
166
|
+
for (const key of await this.storage.list(heldPrefix(executionId))) {
|
|
167
|
+
const parsed = HeldRecordSchema.safeParse(await this.storage.get(key));
|
|
168
|
+
if (parsed.success) {
|
|
169
|
+
found.push(parsed.data);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return found;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Hold a call. A call already held for the same thing keeps its record, and with
|
|
176
|
+
* it any answer. A record held for another reason is an earlier stage of the call
|
|
177
|
+
* (its approval, since given) and is replaced: a call is held for one thing at a
|
|
178
|
+
* time, and an old answer must not pass for the new question.
|
|
179
|
+
*/
|
|
180
|
+
async open(executionId, record) {
|
|
181
|
+
const existing = await this.load(executionId, record.callId);
|
|
182
|
+
const same = existing !== undefined &&
|
|
183
|
+
existing.argsHash === record.argsHash &&
|
|
184
|
+
existing.reason === record.reason;
|
|
185
|
+
if (same) {
|
|
186
|
+
return existing;
|
|
187
|
+
}
|
|
188
|
+
await this.storage.set(`${heldPrefix(executionId)}${record.callId}`, record);
|
|
189
|
+
return record;
|
|
190
|
+
}
|
|
191
|
+
/** Drop every held call and intent of an execution that is over or was abandoned. */
|
|
192
|
+
async clear(executionId) {
|
|
193
|
+
for (const prefix of [
|
|
194
|
+
heldPrefix(executionId),
|
|
195
|
+
intentPrefix(executionId),
|
|
196
|
+
]) {
|
|
197
|
+
for (const key of await this.storage.list(prefix)) {
|
|
198
|
+
await this.storage.delete(key);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Note that a `durable` tool call is about to run. Written before the tool does
|
|
204
|
+
* anything, so a resumed run that finds it knows the call had started.
|
|
205
|
+
*/
|
|
206
|
+
async arm(executionId, callId, argsHash) {
|
|
207
|
+
await this.storage.set(`${intentPrefix(executionId)}${callId}`, {
|
|
208
|
+
argsHash,
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
/** True when a call with these arguments was started and never finished. */
|
|
212
|
+
async wasStarted(executionId, callId, argsHash) {
|
|
213
|
+
const raw = await this.storage.get(`${intentPrefix(executionId)}${callId}`);
|
|
214
|
+
const parsed = IntentSchema.safeParse(raw);
|
|
215
|
+
return parsed.success && parsed.data.argsHash === argsHash;
|
|
216
|
+
}
|
|
217
|
+
/** The call finished and its result is on record. */
|
|
218
|
+
async disarm(executionId, callId) {
|
|
219
|
+
await this.storage.delete(`${intentPrefix(executionId)}${callId}`);
|
|
220
|
+
}
|
|
221
|
+
/** The call was settled and its result recorded: drop its record. */
|
|
222
|
+
async close(executionId, callId) {
|
|
223
|
+
await this.storage.delete(`${heldPrefix(executionId)}${callId}`);
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Answer a held call. The first answer wins: the same answer again is a no-op, a
|
|
227
|
+
* different one is refused.
|
|
228
|
+
*
|
|
229
|
+
* @throws NoeticError `hold_refused` when the call is not held, `argsHash` names a
|
|
230
|
+
* different call, the answer is the wrong kind for the hold, or another answer
|
|
231
|
+
* already landed.
|
|
232
|
+
*/
|
|
233
|
+
resolve(executionId, answer) {
|
|
234
|
+
// One answer at a time per call. Storage with `swap` settles a race between
|
|
235
|
+
// processes; without it nothing else stops two answers here from both landing.
|
|
236
|
+
const key = `${executionId}\u0000${answer.callId}`;
|
|
237
|
+
const turn = (this.answering.get(key) ?? Promise.resolve())
|
|
238
|
+
.catch(() => undefined)
|
|
239
|
+
.then(() => this.resolveOne(executionId, answer));
|
|
240
|
+
this.answering.set(key, turn);
|
|
241
|
+
const forget = () => {
|
|
242
|
+
if (this.answering.get(key) === turn) {
|
|
243
|
+
this.answering.delete(key);
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
turn.then(forget, forget);
|
|
247
|
+
return turn;
|
|
248
|
+
}
|
|
249
|
+
async resolveOne(executionId, answer) {
|
|
250
|
+
const { callId } = answer;
|
|
251
|
+
const record = await this.load(executionId, callId);
|
|
252
|
+
if (!record) {
|
|
253
|
+
throw refused(callId, 'no call with this id is held');
|
|
254
|
+
}
|
|
255
|
+
if (answer.argsHash !== undefined && answer.argsHash !== record.argsHash) {
|
|
256
|
+
throw refused(callId, 'the answer is for a call with different arguments');
|
|
257
|
+
}
|
|
258
|
+
const resolution = toResolutionRecord(answer.resolution);
|
|
259
|
+
// An unknown outcome takes either answer: "it landed, here is the result", or
|
|
260
|
+
// a decision on whether to run it again.
|
|
261
|
+
const wrongKind = record.reason !== 'outcome' &&
|
|
262
|
+
(record.reason === 'result') !== (resolution.hasOutput === true);
|
|
263
|
+
if (wrongKind) {
|
|
264
|
+
throw refused(callId, record.reason === 'result'
|
|
265
|
+
? 'the call waits for a result, not an approval'
|
|
266
|
+
: 'the call waits for an approval, not a result');
|
|
267
|
+
}
|
|
268
|
+
if (record.resolution) {
|
|
269
|
+
if (sameResolution(record.resolution, resolution)) {
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
throw refused(callId, 'the call was already answered differently');
|
|
273
|
+
}
|
|
274
|
+
const next = {
|
|
275
|
+
...record,
|
|
276
|
+
resolution,
|
|
277
|
+
};
|
|
278
|
+
const key = `${heldPrefix(executionId)}${callId}`;
|
|
279
|
+
// With compare-and-set, two answers racing from two processes cannot both land.
|
|
280
|
+
const landed = this.storage.swap ? await this.storage.swap(key, record, next) : true;
|
|
281
|
+
if (!this.storage.swap) {
|
|
282
|
+
await this.storage.set(key, next);
|
|
283
|
+
}
|
|
284
|
+
if (!landed) {
|
|
285
|
+
const now = await this.load(executionId, callId);
|
|
286
|
+
if (now?.resolution && sameResolution(now.resolution, resolution)) {
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
throw refused(callId, 'the call was already answered differently');
|
|
290
|
+
}
|
|
291
|
+
this.notify(executionId);
|
|
292
|
+
}
|
|
293
|
+
/** True when other processes may share this storage, and so may answer a call. */
|
|
294
|
+
get shared() {
|
|
295
|
+
return this.storage.swap !== undefined;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Start listening for a change to the execution's held calls. Listening begins
|
|
299
|
+
* when this returns, so an answer that lands while the caller is still reading
|
|
300
|
+
* the records is not missed. `changed` resolves on the first change or when
|
|
301
|
+
* `signal` aborts; call `stop` when done either way.
|
|
302
|
+
*/
|
|
303
|
+
listen(executionId, signal) {
|
|
304
|
+
const waiters = this.waiters.get(executionId) ?? new Set();
|
|
305
|
+
this.waiters.set(executionId, waiters);
|
|
306
|
+
let wake = () => { };
|
|
307
|
+
const changed = new Promise((resolve) => {
|
|
308
|
+
wake = resolve;
|
|
309
|
+
});
|
|
310
|
+
const stop = () => {
|
|
311
|
+
waiters.delete(wake);
|
|
312
|
+
signal.removeEventListener('abort', wake);
|
|
313
|
+
};
|
|
314
|
+
waiters.add(wake);
|
|
315
|
+
signal.addEventListener('abort', wake, {
|
|
316
|
+
once: true,
|
|
317
|
+
});
|
|
318
|
+
if (signal.aborted) {
|
|
319
|
+
wake();
|
|
320
|
+
}
|
|
321
|
+
return {
|
|
322
|
+
changed,
|
|
323
|
+
stop,
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
/** Wake whoever in this process waits on the execution's held calls. */
|
|
327
|
+
notify(executionId) {
|
|
328
|
+
for (const wake of [
|
|
329
|
+
...(this.waiters.get(executionId) ?? []),
|
|
330
|
+
]) {
|
|
331
|
+
wake();
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
const stores = new WeakMap();
|
|
336
|
+
/** @internal The held calls of `harness`, over its storage and clock. */
|
|
337
|
+
export function heldCallsOf(harness) {
|
|
338
|
+
const existing = stores.get(harness);
|
|
339
|
+
if (existing) {
|
|
340
|
+
return existing;
|
|
341
|
+
}
|
|
342
|
+
const created = new HeldCalls(harness.config.storage ?? createInMemoryStorage(), () => harness.config.now?.() ?? Date.now());
|
|
343
|
+
stores.set(harness, created);
|
|
344
|
+
return created;
|
|
345
|
+
}
|
|
346
|
+
/** @internal The execution a context's held calls are kept under: its root. */
|
|
347
|
+
export function heldScopeOf(ctx) {
|
|
348
|
+
return rootIdOf(ctx);
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* @internal
|
|
352
|
+
* Wait until something about these held calls may have changed: an answer arrived,
|
|
353
|
+
* or a hold's deadline passed. While it waits the step is only waiting, so the
|
|
354
|
+
* turn may park (spec 23 § Parked turns).
|
|
355
|
+
*
|
|
356
|
+
* @throws NoeticError `cancelled` when the context is aborted, which is also how a
|
|
357
|
+
* parked turn leaves here.
|
|
358
|
+
*/
|
|
359
|
+
export async function waitOnHeldCalls(opts) {
|
|
360
|
+
const { ctx } = opts;
|
|
361
|
+
const holds = heldCallsOf(opts.harness);
|
|
362
|
+
const executionId = heldScopeOf(ctx);
|
|
363
|
+
const impl = ctx instanceof ContextImpl ? ctx : undefined;
|
|
364
|
+
const signals = [
|
|
365
|
+
impl?.abortSignal,
|
|
366
|
+
opts.signal,
|
|
367
|
+
].filter((given) => given !== undefined);
|
|
368
|
+
const signal = signals.length === 0
|
|
369
|
+
? new AbortController().signal
|
|
370
|
+
: signals.length === 1 && signals[0]
|
|
371
|
+
? signals[0]
|
|
372
|
+
: AbortSignal.any(signals);
|
|
373
|
+
// Listen before reading: an answer that lands in between must still wake this.
|
|
374
|
+
const listening = holds.listen(executionId, signal);
|
|
375
|
+
let stopWaiting;
|
|
376
|
+
let timer;
|
|
377
|
+
try {
|
|
378
|
+
let earliest = Number.POSITIVE_INFINITY;
|
|
379
|
+
for (const callId of opts.callIds) {
|
|
380
|
+
const record = await holds.load(executionId, callId);
|
|
381
|
+
if (!record || record.resolution) {
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
if (record.dueAt !== undefined && record.onDue !== 'keep') {
|
|
385
|
+
earliest = Math.min(earliest, record.dueAt);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
stopWaiting =
|
|
389
|
+
opts.park === false
|
|
390
|
+
? undefined
|
|
391
|
+
: impl?.ledger?.parking.wait(impl.currentDispatch()?.path, earliest);
|
|
392
|
+
// Another process answering cannot wake this one, so shared storage is read again
|
|
393
|
+
// every so often. A deadline wakes it too.
|
|
394
|
+
const untilDue = earliest - holds.now();
|
|
395
|
+
const wakeIn = Math.min(untilDue, holds.shared ? HELD_POLL_MS : Number.POSITIVE_INFINITY);
|
|
396
|
+
await Promise.race([
|
|
397
|
+
listening.changed,
|
|
398
|
+
new Promise((resolve) => {
|
|
399
|
+
if (Number.isFinite(wakeIn)) {
|
|
400
|
+
timer = setTimeout(resolve, Math.max(0, wakeIn));
|
|
401
|
+
}
|
|
402
|
+
}),
|
|
403
|
+
]);
|
|
404
|
+
}
|
|
405
|
+
finally {
|
|
406
|
+
clearTimeout(timer);
|
|
407
|
+
stopWaiting?.();
|
|
408
|
+
listening.stop();
|
|
409
|
+
}
|
|
410
|
+
if (signal.aborted) {
|
|
411
|
+
throw new NoeticErrorImpl({
|
|
412
|
+
kind: 'cancelled',
|
|
413
|
+
reason: ctx.abortReason ?? 'context aborted',
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* @internal
|
|
419
|
+
* False once the context's execution writes under a lease it no longer holds: a
|
|
420
|
+
* harness that was replaced must not open, close or disarm the new holder's calls
|
|
421
|
+
* (spec 23 § One writer per turn). An answer (`resolve`) is not a turn's write and
|
|
422
|
+
* is not fenced; it is a compare-and-set any harness may make.
|
|
423
|
+
*/
|
|
424
|
+
export function mayWriteHolds(ctx) {
|
|
425
|
+
let node = ctx;
|
|
426
|
+
while (node.parent) {
|
|
427
|
+
node = node.parent;
|
|
428
|
+
}
|
|
429
|
+
for (const candidate of [
|
|
430
|
+
ctx,
|
|
431
|
+
node,
|
|
432
|
+
]) {
|
|
433
|
+
if (candidate instanceof ContextImpl && candidate.ledger) {
|
|
434
|
+
return candidate.ledger.isHeld;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
return true;
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* @internal
|
|
441
|
+
* Hold a call from a caller with no model round to come back to (a step), and wait
|
|
442
|
+
* for its answer. While it waits the step is only waiting, so the turn may park; a
|
|
443
|
+
* resumed step calls this again and finds the same record, and its answer.
|
|
444
|
+
*
|
|
445
|
+
* @throws NoeticError `cancelled` when the context is aborted while it waits.
|
|
446
|
+
*/
|
|
447
|
+
export async function holdAndWait(opts) {
|
|
448
|
+
const holds = heldCallsOf(opts.harness);
|
|
449
|
+
const executionId = heldScopeOf(opts.ctx);
|
|
450
|
+
const { callId } = opts.record;
|
|
451
|
+
const opened = mayWriteHolds(opts.ctx) ? await holds.open(executionId, opts.record) : opts.record;
|
|
452
|
+
if (opened.resolution === undefined) {
|
|
453
|
+
(opts.onHeld ?? announcerOf(opts.harness, opts.ctx))(toHeldCall(opened));
|
|
454
|
+
}
|
|
455
|
+
for (;;) {
|
|
456
|
+
const current = await holds.load(executionId, callId);
|
|
457
|
+
const settled = current?.resolution !== undefined;
|
|
458
|
+
if (!current || settled || isOverdue(current, holds.now())) {
|
|
459
|
+
if (mayWriteHolds(opts.ctx)) {
|
|
460
|
+
await holds.close(executionId, callId);
|
|
461
|
+
}
|
|
462
|
+
return {
|
|
463
|
+
resolution: current?.resolution,
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
await waitOnHeldCalls({
|
|
467
|
+
harness: opts.harness,
|
|
468
|
+
ctx: opts.ctx,
|
|
469
|
+
callIds: [
|
|
470
|
+
callId,
|
|
471
|
+
],
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* @internal
|
|
477
|
+
* Says on the stream that a call is held: `{name}:tool_call_held`, with the fields
|
|
478
|
+
* `harness.pending()` returns. What a hold does when its caller gives no `onHeld`.
|
|
479
|
+
*/
|
|
480
|
+
export function announcerOf(harness, ctx) {
|
|
481
|
+
return (held) => {
|
|
482
|
+
emitFrameworkEvent({
|
|
483
|
+
broadcaster: getBroadcaster(ctx),
|
|
484
|
+
agentName: harness.config.name,
|
|
485
|
+
eventType: 'tool_call_held',
|
|
486
|
+
data: {
|
|
487
|
+
...held,
|
|
488
|
+
},
|
|
489
|
+
});
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
/** True once a hold with a `deny` deadline has run out. */
|
|
493
|
+
export function isOverdue(record, now) {
|
|
494
|
+
return record.dueAt !== undefined && record.onDue !== 'keep' && record.dueAt <= now;
|
|
495
|
+
}
|
|
496
|
+
//#endregion
|
|
@@ -1,4 +1,13 @@
|
|
|
1
1
|
import type { StorageAdapter } from '@noetic-tools/context';
|
|
2
|
+
/** @public Options for `createInMemoryStorage`. */
|
|
3
|
+
export interface CreateInMemoryStorageOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Implement `swap`, so harnesses sharing this storage take turn leases (spec 23
|
|
6
|
+
* § One writer per turn). Off by default: the Map lives in one process, where a
|
|
7
|
+
* lease only matters to a test that puts two harnesses on one storage.
|
|
8
|
+
*/
|
|
9
|
+
swap?: boolean;
|
|
10
|
+
}
|
|
2
11
|
/**
|
|
3
12
|
* @public Process-local, Map-backed StorageAdapter.
|
|
4
13
|
*
|
|
@@ -6,4 +15,4 @@ import type { StorageAdapter } from '@noetic-tools/context';
|
|
|
6
15
|
* for the lifetime of the Map (i.e., this harness instance). Durable backends
|
|
7
16
|
* must be supplied explicitly by the caller.
|
|
8
17
|
*/
|
|
9
|
-
export declare function createInMemoryStorage(): StorageAdapter;
|
|
18
|
+
export declare function createInMemoryStorage(options?: CreateInMemoryStorageOptions): StorageAdapter;
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { frameworkCast } from '@noetic-tools/types';
|
|
2
|
-
//#region Public API
|
|
3
2
|
/**
|
|
4
3
|
* @public Process-local, Map-backed StorageAdapter.
|
|
5
4
|
*
|
|
@@ -7,8 +6,27 @@ import { frameworkCast } from '@noetic-tools/types';
|
|
|
7
6
|
* for the lifetime of the Map (i.e., this harness instance). Durable backends
|
|
8
7
|
* must be supplied explicitly by the caller.
|
|
9
8
|
*/
|
|
10
|
-
export function createInMemoryStorage() {
|
|
9
|
+
export function createInMemoryStorage(options) {
|
|
11
10
|
const store = new Map();
|
|
11
|
+
const base = inMemoryAdapter(store);
|
|
12
|
+
if (!options?.swap) {
|
|
13
|
+
return base;
|
|
14
|
+
}
|
|
15
|
+
return {
|
|
16
|
+
...base,
|
|
17
|
+
// Single-threaded: nothing runs between the compare and the write.
|
|
18
|
+
async swap(key, prev, next) {
|
|
19
|
+
const stored = store.get(key);
|
|
20
|
+
const matches = prev === null ? stored === undefined : JSON.stringify(stored) === JSON.stringify(prev);
|
|
21
|
+
if (!matches) {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
store.set(key, next);
|
|
25
|
+
return true;
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function inMemoryAdapter(store) {
|
|
12
30
|
return {
|
|
13
31
|
async get(key) {
|
|
14
32
|
const val = store.get(key);
|
|
@@ -32,6 +32,8 @@ export declare class MessageQueue {
|
|
|
32
32
|
private readonly items;
|
|
33
33
|
private readonly listeners;
|
|
34
34
|
enqueue(message: QueuedMessage): void;
|
|
35
|
+
/** Queue several messages as one arrival, so a listener sees them all at once. */
|
|
36
|
+
enqueueAll(messages: ReadonlyArray<QueuedMessage>): void;
|
|
35
37
|
prepend(message: QueuedMessage): void;
|
|
36
38
|
drainAll(): QueuedMessage[];
|
|
37
39
|
/** Remove and return the messages `match` accepts, keeping the rest in order. */
|
|
@@ -49,6 +49,14 @@ export class MessageQueue {
|
|
|
49
49
|
this.items.push(message);
|
|
50
50
|
this.notify();
|
|
51
51
|
}
|
|
52
|
+
/** Queue several messages as one arrival, so a listener sees them all at once. */
|
|
53
|
+
enqueueAll(messages) {
|
|
54
|
+
if (messages.length === 0) {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
this.items.push(...messages);
|
|
58
|
+
this.notify();
|
|
59
|
+
}
|
|
52
60
|
prepend(message) {
|
|
53
61
|
this.items.unshift(message);
|
|
54
62
|
this.notify();
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { ItemSchemaRegistry, StorageAdapter, StreamEvent } from '@noetic-tools/types';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
declare const OutputSnapshotSchema: z.ZodObject<{
|
|
4
|
+
type: z.ZodString;
|
|
5
|
+
id: z.ZodOptional<z.ZodString>;
|
|
6
|
+
isComplete: z.ZodOptional<z.ZodBoolean>;
|
|
7
|
+
}, z.core.$catchall<z.ZodUnknown>>;
|
|
8
|
+
/**
|
|
9
|
+
* @public One item of a thread's display output: an item snapshot as the item
|
|
10
|
+
* stream yields it, unfinished ones included (`isComplete: false`), or whatever
|
|
11
|
+
* a protocol adapter saved in its place.
|
|
12
|
+
*/
|
|
13
|
+
export type OutputSnapshot = z.infer<typeof OutputSnapshotSchema>;
|
|
14
|
+
/**
|
|
15
|
+
* @public A thread's display output could not be read or written. `scope` is the
|
|
16
|
+
* thread id; `cause` is what storage, or the snapshot check, failed with.
|
|
17
|
+
*/
|
|
18
|
+
export declare class OutputStoreError extends Error {
|
|
19
|
+
readonly scope: string;
|
|
20
|
+
constructor(options: {
|
|
21
|
+
scope: string;
|
|
22
|
+
message: string;
|
|
23
|
+
cause: unknown;
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/** @internal The storage key a thread's display output is kept under. */
|
|
27
|
+
export declare function outputKey(scope: string): string;
|
|
28
|
+
/**
|
|
29
|
+
* @public A thread's display output, kept in storage under `output:<scope>`:
|
|
30
|
+
* the latest snapshot of every item its stream produced, including items that
|
|
31
|
+
* never finished. It is for showing a thread again, in a new process or after a
|
|
32
|
+
* failed run. Nothing resumes from it: checkpoints, the step ledger and the
|
|
33
|
+
* model's history are stored apart and never read here.
|
|
34
|
+
*
|
|
35
|
+
* `record` and `write` queue snapshots and save them in the background, one
|
|
36
|
+
* write at a time, each holding the whole output. `flush` and `read` wait for
|
|
37
|
+
* what is queued and throw `OutputStoreError` when it could not be saved; the
|
|
38
|
+
* snapshots stay queued, so the next call tries again. On storage with `swap` a
|
|
39
|
+
* write never replaces what another store saved meanwhile.
|
|
40
|
+
*/
|
|
41
|
+
export declare class OutputStore {
|
|
42
|
+
private readonly storage;
|
|
43
|
+
private readonly scope;
|
|
44
|
+
private readonly stream;
|
|
45
|
+
private readonly pending;
|
|
46
|
+
private writing?;
|
|
47
|
+
private failure?;
|
|
48
|
+
constructor(storage: StorageAdapter, scope: string, schemas?: ItemSchemaRegistry);
|
|
49
|
+
/**
|
|
50
|
+
* Fold one stream event into the output. Never throws: an event that cannot be
|
|
51
|
+
* read as display output is left out, with a warning, and the run goes on.
|
|
52
|
+
*/
|
|
53
|
+
record(event: StreamEvent): void;
|
|
54
|
+
/**
|
|
55
|
+
* Save display snapshots, each replacing the stored one with its id, and resolve
|
|
56
|
+
* the whole stored output.
|
|
57
|
+
*
|
|
58
|
+
* @throws OutputStoreError when `items` are not snapshots, or storage fails.
|
|
59
|
+
*/
|
|
60
|
+
write(items: ReadonlyArray<unknown>): Promise<OutputSnapshot[]>;
|
|
61
|
+
/**
|
|
62
|
+
* The stored output, after everything queued is saved.
|
|
63
|
+
*
|
|
64
|
+
* @throws OutputStoreError when storage fails or holds something else.
|
|
65
|
+
*/
|
|
66
|
+
read(): Promise<OutputSnapshot[]>;
|
|
67
|
+
/**
|
|
68
|
+
* Wait until everything queued is saved.
|
|
69
|
+
*
|
|
70
|
+
* @throws OutputStoreError when it could not be. What was queued stays queued,
|
|
71
|
+
* and every flush throws until a later one saves it.
|
|
72
|
+
*/
|
|
73
|
+
flush(): Promise<void>;
|
|
74
|
+
private queue;
|
|
75
|
+
private start;
|
|
76
|
+
/** What storage holds under the key, as it is stored and as snapshots. */
|
|
77
|
+
private load;
|
|
78
|
+
/** Save what is queued over what is stored, until nothing is queued. */
|
|
79
|
+
private drain;
|
|
80
|
+
private save;
|
|
81
|
+
/**
|
|
82
|
+
* Write `batch` over what is stored now. On storage with `swap` the write lands
|
|
83
|
+
* only if nothing else was saved since the read, and false means it did not.
|
|
84
|
+
*/
|
|
85
|
+
private saveOver;
|
|
86
|
+
private error;
|
|
87
|
+
}
|
|
88
|
+
export {};
|