@noetic-tools/core 5.22.0-next.2 → 5.22.0-next.3
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-adapter.js +4 -2
- package/dist/builders/custom-item.d.ts +1 -1
- package/dist/builders/custom-item.js +14 -3
- package/dist/connections/pool.d.ts +18 -0
- package/dist/connections/pool.js +54 -9
- package/dist/connections/registry.js +11 -0
- package/dist/harness/agent-harness.d.ts +76 -3
- package/dist/harness/agent-harness.js +229 -21
- package/dist/harness/deps/types.d.ts +1 -1
- package/dist/harness/forget.d.ts +57 -0
- package/dist/harness/forget.js +496 -0
- package/dist/harness/harness-options.d.ts +15 -1
- package/dist/harness/model-rounds.d.ts +6 -0
- package/dist/harness/model-rounds.js +7 -3
- package/dist/harness/model-tool-round.js +19 -5
- package/dist/harness/recorded-tool-calls.d.ts +16 -0
- package/dist/harness/recorded-tool-calls.js +106 -0
- package/dist/harness/spend.d.ts +13 -1
- package/dist/harness/spend.js +82 -1
- package/dist/harness/steer-inbox.js +9 -5
- package/dist/harness/thread-record.d.ts +12 -1
- package/dist/harness/thread-record.js +63 -19
- package/dist/index.d.ts +4 -5
- package/dist/index.js +2 -3
- package/dist/interpreter/acp-tools.js +21 -4
- package/dist/interpreter/execute-action.js +7 -1
- package/dist/interpreter/execute.js +55 -3
- package/dist/interpreter/step-dispatcher.js +17 -1
- package/dist/interpreter/step-kind-dispatch.js +9 -1
- package/dist/runtime/durable/child-links.d.ts +61 -0
- package/dist/runtime/durable/child-links.js +127 -0
- package/dist/runtime/durable/session-store.d.ts +6 -0
- package/dist/runtime/durable/session-store.js +16 -2
- package/dist/runtime/durable/turn-lease.d.ts +10 -0
- package/dist/runtime/durable/turn-lease.js +10 -2
- package/dist/runtime/held-calls.d.ts +65 -6
- package/dist/runtime/held-calls.js +257 -5
- package/dist/runtime/output-store.d.ts +2 -0
- package/dist/runtime/output-store.js +3 -1
- package/dist/runtime/tool-approval.d.ts +1 -3
- package/dist/runtime/tool-approval.js +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Forgetting a thread or an execution: deleting every record core keeps for it,
|
|
3
|
+
* after settling the spend it left pending, and listing what is stored so a host
|
|
4
|
+
* never builds a storage key itself (spec 23 § Forgetting).
|
|
5
|
+
*/
|
|
6
|
+
import { storageGetMany } from '@noetic-tools/context';
|
|
7
|
+
import { ExecutionPart, NoeticConfigError, NoeticErrorImpl } from '@noetic-tools/types';
|
|
8
|
+
import { poolLeasesOf } from '../connections/pool.js';
|
|
9
|
+
import { adapterOfChild, adaptersUsedBy, ChildAdapterSource, ChildLinkSchema, runsInProcess, } from '../runtime/durable/child-links.js';
|
|
10
|
+
import { SESSION_PREFIX, sessionKey } from '../runtime/durable/session-store.js';
|
|
11
|
+
import { LEASE_PREFIX, leaseKey, TurnLease } from '../runtime/durable/turn-lease.js';
|
|
12
|
+
import { OUTPUT_PREFIX, outputKey } from '../runtime/output-store.js';
|
|
13
|
+
import { lookupStep } from '../runtime/step-registry.js';
|
|
14
|
+
import { executionsOf } from './thread-record.js';
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region Keys
|
|
17
|
+
const EXECUTION_PREFIX = 'execution:';
|
|
18
|
+
const LAYERS_PREFIX = 'layers/';
|
|
19
|
+
/** Each part core writes under an execution, and what may follow its name. */
|
|
20
|
+
const PART_TAILS = {
|
|
21
|
+
snapshot: /^$/,
|
|
22
|
+
ledger: /^:\d+$/,
|
|
23
|
+
trail: /^:\d+$/,
|
|
24
|
+
held: /^:.+$/,
|
|
25
|
+
intent: /^:.+$/,
|
|
26
|
+
pending: /^:.+$/,
|
|
27
|
+
child: /^:[^:]+$/,
|
|
28
|
+
};
|
|
29
|
+
/** Every place a part's name may start in what follows `execution:`. */
|
|
30
|
+
const PART_NAME = /:(snapshot|ledger|trail|held|intent|pending|child)(?=:|$)/g;
|
|
31
|
+
/**
|
|
32
|
+
* The execution id and part of a key core writes, read as the longest id whose
|
|
33
|
+
* part is well formed: `a:child:trail:1` is execution `a:child`'s trail, and
|
|
34
|
+
* `a:child:<id>` is execution `a`'s link to child `<id>`.
|
|
35
|
+
*/
|
|
36
|
+
function parseCoreKey(rest) {
|
|
37
|
+
const starts = [
|
|
38
|
+
...rest.matchAll(PART_NAME),
|
|
39
|
+
].reverse();
|
|
40
|
+
for (const match of starts) {
|
|
41
|
+
const part = match[1] ?? '';
|
|
42
|
+
const at = match.index ?? 0;
|
|
43
|
+
const tail = rest.slice(at + 1 + part.length);
|
|
44
|
+
if (at > 0 && PART_TAILS[part]?.test(tail)) {
|
|
45
|
+
return {
|
|
46
|
+
executionId: rest.slice(0, at),
|
|
47
|
+
part,
|
|
48
|
+
tail: tail.slice(1),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The execution and part of each key under `execution:`. A key core writes is read by
|
|
56
|
+
* its part's suffix. Any other key belongs to the longest execution id, among those
|
|
57
|
+
* core's keys name, that it starts with — else to the id up to its first colon — so
|
|
58
|
+
* `execution:a:b:custom` is execution `a:b`'s when `a:b` has records of its own.
|
|
59
|
+
*/
|
|
60
|
+
function parseExecutionKeys(keys) {
|
|
61
|
+
const known = new Set();
|
|
62
|
+
const parsed = [];
|
|
63
|
+
const unknown = [];
|
|
64
|
+
for (const key of keys) {
|
|
65
|
+
const match = key.startsWith(EXECUTION_PREFIX)
|
|
66
|
+
? parseCoreKey(key.slice(EXECUTION_PREFIX.length))
|
|
67
|
+
: undefined;
|
|
68
|
+
if (match) {
|
|
69
|
+
known.add(match.executionId);
|
|
70
|
+
parsed.push({
|
|
71
|
+
key,
|
|
72
|
+
executionId: match.executionId,
|
|
73
|
+
part: toPart(match.part),
|
|
74
|
+
tail: match.tail,
|
|
75
|
+
});
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
unknown.push(key);
|
|
79
|
+
}
|
|
80
|
+
for (const key of unknown) {
|
|
81
|
+
const owner = ownerOf(key, known);
|
|
82
|
+
if (owner !== undefined) {
|
|
83
|
+
parsed.push({
|
|
84
|
+
key,
|
|
85
|
+
executionId: owner,
|
|
86
|
+
part: ExecutionPart.Other,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return parsed;
|
|
91
|
+
}
|
|
92
|
+
/** The execution a key core does not write belongs to. */
|
|
93
|
+
function ownerOf(key, known) {
|
|
94
|
+
if (!key.startsWith(EXECUTION_PREFIX)) {
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
const rest = key.slice(EXECUTION_PREFIX.length);
|
|
98
|
+
let owner;
|
|
99
|
+
for (const id of known) {
|
|
100
|
+
if (rest.startsWith(`${id}:`) && id.length > (owner?.length ?? -1)) {
|
|
101
|
+
owner = id;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (owner !== undefined) {
|
|
105
|
+
return owner;
|
|
106
|
+
}
|
|
107
|
+
const colon = rest.indexOf(':');
|
|
108
|
+
return colon > 0 ? rest.slice(0, colon) : undefined;
|
|
109
|
+
}
|
|
110
|
+
const PARTS = {
|
|
111
|
+
snapshot: ExecutionPart.Snapshot,
|
|
112
|
+
ledger: ExecutionPart.Ledger,
|
|
113
|
+
trail: ExecutionPart.Trail,
|
|
114
|
+
held: ExecutionPart.Held,
|
|
115
|
+
intent: ExecutionPart.Intent,
|
|
116
|
+
pending: ExecutionPart.Pending,
|
|
117
|
+
child: ExecutionPart.Child,
|
|
118
|
+
};
|
|
119
|
+
function toPart(name) {
|
|
120
|
+
return PARTS[name] ?? ExecutionPart.Other;
|
|
121
|
+
}
|
|
122
|
+
/** Ids of keys under `prefix` that start with `idPrefix`. */
|
|
123
|
+
async function idsUnder(storage, prefix, idPrefix) {
|
|
124
|
+
const keys = await storage.list(`${prefix}${idPrefix}`);
|
|
125
|
+
return keys.map((key) => key.slice(prefix.length));
|
|
126
|
+
}
|
|
127
|
+
async function deleteAll(storage, keys) {
|
|
128
|
+
for (const key of keys) {
|
|
129
|
+
await storage.delete(key);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
//#endregion
|
|
133
|
+
//#region Refusals
|
|
134
|
+
function busy(threadOrExecution, reason) {
|
|
135
|
+
return new NoeticErrorImpl({
|
|
136
|
+
kind: 'lease_lost',
|
|
137
|
+
executionId: threadOrExecution,
|
|
138
|
+
term: 0,
|
|
139
|
+
reason,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* `executionIds` and every execution they had run out of process, their children's
|
|
144
|
+
* included, in the order found: each run before its children.
|
|
145
|
+
*/
|
|
146
|
+
async function withChildren(host, executionIds) {
|
|
147
|
+
const executions = new Set();
|
|
148
|
+
const children = [];
|
|
149
|
+
const queue = [
|
|
150
|
+
...executionIds,
|
|
151
|
+
];
|
|
152
|
+
for (let next = queue.shift(); next !== undefined; next = queue.shift()) {
|
|
153
|
+
if (executions.has(next)) {
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
executions.add(next);
|
|
157
|
+
for (const child of await linksOf(host.storage, next)) {
|
|
158
|
+
if (!children.some((known) => known.childId === child.childId)) {
|
|
159
|
+
children.push(child);
|
|
160
|
+
}
|
|
161
|
+
queue.push(child.childId);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
executions,
|
|
166
|
+
children,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
/** The children the run rooted at `executionId` linked, with their links. */
|
|
170
|
+
async function linksOf(storage, executionId) {
|
|
171
|
+
if (!storage) {
|
|
172
|
+
return [];
|
|
173
|
+
}
|
|
174
|
+
const keys = parseExecutionKeys(await storage.list(`${EXECUTION_PREFIX}${executionId}:child:`)).filter((parsed) => parsed.executionId === executionId && parsed.part === ExecutionPart.Child && parsed.tail);
|
|
175
|
+
const values = await storageGetMany(storage, keys.map((parsed) => parsed.key));
|
|
176
|
+
return keys.map((parsed) => {
|
|
177
|
+
const link = ChildLinkSchema.safeParse(values.get(parsed.key));
|
|
178
|
+
return {
|
|
179
|
+
childId: parsed.tail ?? '',
|
|
180
|
+
link: link.success ? link.data : undefined,
|
|
181
|
+
};
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
/** The adapter that ran `child`, as far as this harness can tell. */
|
|
185
|
+
function runnerOf(host, child) {
|
|
186
|
+
const dispatched = adapterOfChild(host.harness, child.childId);
|
|
187
|
+
if (dispatched) {
|
|
188
|
+
return dispatched;
|
|
189
|
+
}
|
|
190
|
+
if (child.link?.from === ChildAdapterSource.Harness) {
|
|
191
|
+
return host.subprocess;
|
|
192
|
+
}
|
|
193
|
+
if (child.link?.from === ChildAdapterSource.Step) {
|
|
194
|
+
const step = lookupStep(child.link.stepId);
|
|
195
|
+
return step && (step.kind === 'runCode' || step.kind === 'spawn') ? step.subprocess : undefined;
|
|
196
|
+
}
|
|
197
|
+
return undefined;
|
|
198
|
+
}
|
|
199
|
+
/** Stop every handle `adapter` still runs for a covered execution. Resolves the executions it stopped. */
|
|
200
|
+
async function stopLive(adapter, executions) {
|
|
201
|
+
const stopped = new Set();
|
|
202
|
+
for (const handle of await adapter.listLive()) {
|
|
203
|
+
const executionId = handle.metadata?.executionId;
|
|
204
|
+
if (typeof executionId === 'string' && executions.has(executionId)) {
|
|
205
|
+
await adapter.stop(handle.id, 'forgotten');
|
|
206
|
+
stopped.add(executionId);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return stopped;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Stop every covered execution still running out of process, before anything of it
|
|
213
|
+
* is settled or deleted: one that kept running would spend, and write again under
|
|
214
|
+
* what the forget deletes. A child that has not finished is asked of the adapter
|
|
215
|
+
* that ran it. When no adapter this harness knows of can be that one, and the host
|
|
216
|
+
* named none in `subprocesses`, the forget is refused.
|
|
217
|
+
*
|
|
218
|
+
* @throws NoeticConfigError `FORGET_CHILD_UNREACHABLE`
|
|
219
|
+
*/
|
|
220
|
+
async function stopChildren(host, covered, named) {
|
|
221
|
+
const unfinished = covered.children.filter((child) => child.link?.settled !== true);
|
|
222
|
+
const runners = new Map(unfinished.map((child) => [
|
|
223
|
+
child.childId,
|
|
224
|
+
runnerOf(host, child),
|
|
225
|
+
]));
|
|
226
|
+
const unreachable = unfinished.filter((child) => runners.get(child.childId) === undefined);
|
|
227
|
+
if (unreachable.length > 0 && named.length === 0) {
|
|
228
|
+
throw childUnreachable(unreachable);
|
|
229
|
+
}
|
|
230
|
+
const adapters = new Set([
|
|
231
|
+
host.subprocess,
|
|
232
|
+
...adaptersUsedBy(host.harness),
|
|
233
|
+
...named,
|
|
234
|
+
]);
|
|
235
|
+
for (const runner of runners.values()) {
|
|
236
|
+
if (runner) {
|
|
237
|
+
adapters.add(runner);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
for (const adapter of adapters) {
|
|
241
|
+
if (!runsInProcess(adapter)) {
|
|
242
|
+
await stopLive(adapter, covered.executions);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
function childUnreachable(children) {
|
|
247
|
+
const named = children
|
|
248
|
+
.map((child) => `"${child.childId}" (step "${child.link?.stepId ?? 'unknown'}")`)
|
|
249
|
+
.join(', ');
|
|
250
|
+
return new NoeticConfigError({
|
|
251
|
+
code: 'FORGET_CHILD_UNREACHABLE',
|
|
252
|
+
message: `Cannot tell whether ${named} still runs: the subprocess adapter that ran it is not known to this harness.`,
|
|
253
|
+
hint: 'Pass that adapter in forget(scope, { subprocesses: [adapter] }) so a child still running is stopped before what it kept is deleted.',
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
/** Delete everything stored for the executions, checking the lease between them. */
|
|
257
|
+
async function forgetExecutionState(host, executionIds, under) {
|
|
258
|
+
const storage = host.storage;
|
|
259
|
+
for (const executionId of executionIds) {
|
|
260
|
+
under.lease?.assert();
|
|
261
|
+
await host.releaseConnections(executionId);
|
|
262
|
+
await host.clearCheckpoint(executionId);
|
|
263
|
+
if (!storage) {
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
const keys = parseExecutionKeys(await storage.list(`${EXECUTION_PREFIX}${executionId}:`))
|
|
267
|
+
.filter((parsed) => parsed.executionId === executionId &&
|
|
268
|
+
!(under.keepTrail && parsed.part === ExecutionPart.Trail))
|
|
269
|
+
.map((parsed) => parsed.key);
|
|
270
|
+
await deleteAll(storage, keys);
|
|
271
|
+
}
|
|
272
|
+
// Pool leases a crashed run left: no harness holds them to release.
|
|
273
|
+
if (storage) {
|
|
274
|
+
under.lease?.assert();
|
|
275
|
+
await deleteAll(storage, await poolLeasesOf(storage, new Set(executionIds)));
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Delete the state each of `layerIds` keeps at the thread's scope key. A key under
|
|
280
|
+
* `layers/<id>/a/` may be thread `a`'s or, as `layers/<id>/a/b/`, thread `a/b`'s: keys
|
|
281
|
+
* under another stored thread's scope key are left to that thread.
|
|
282
|
+
*/
|
|
283
|
+
async function forgetLayerState(host, threadId, layerIds) {
|
|
284
|
+
const storage = host.storage;
|
|
285
|
+
if (!storage || layerIds.size === 0) {
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
const nested = (await listStoredThreads(host, {
|
|
289
|
+
prefix: `${threadId}/`,
|
|
290
|
+
})).map((other) => `${other}/`);
|
|
291
|
+
for (const layerId of layerIds) {
|
|
292
|
+
const scope = `${LAYERS_PREFIX}${layerId}/${threadId}/`;
|
|
293
|
+
const keys = (await storage.list(scope)).filter((key) => {
|
|
294
|
+
const rest = key.slice(scope.length - threadId.length - 1);
|
|
295
|
+
return !nested.some((other) => rest.startsWith(other));
|
|
296
|
+
});
|
|
297
|
+
await deleteAll(storage, keys);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/** The thread's stored record, or undefined when it has none or it does not read. */
|
|
301
|
+
async function recordOf(host, threadId) {
|
|
302
|
+
return host.sessionStore?.load(threadId);
|
|
303
|
+
}
|
|
304
|
+
/** Refuse a thread with a turn running, or about to run, in this harness. */
|
|
305
|
+
function refuseBusy(host, threadId, record) {
|
|
306
|
+
const live = executionsOf(record).find((id) => host.executionBusy(id));
|
|
307
|
+
if (host.threadBusy(threadId) || live !== undefined) {
|
|
308
|
+
throw busy(threadId, `thread "${threadId}" has a turn running in this harness`);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Take the thread's lease, waiting up to `waitMs` for another harness's, and keep it
|
|
313
|
+
* renewed until the forget is done. Taking it raises its term, so a harness that
|
|
314
|
+
* stalled mid-turn loses its next write.
|
|
315
|
+
*/
|
|
316
|
+
async function holdThread(host, threadId, under) {
|
|
317
|
+
if (!host.leaseOptions) {
|
|
318
|
+
return undefined;
|
|
319
|
+
}
|
|
320
|
+
const lease = await TurnLease.take({
|
|
321
|
+
...host.leaseOptions,
|
|
322
|
+
waitMs: under.waitMs,
|
|
323
|
+
}, threadId, {
|
|
324
|
+
above: under.record?.term,
|
|
325
|
+
});
|
|
326
|
+
// A lost lease is found by `assert` and `verify` before the next delete.
|
|
327
|
+
lease.keep(() => undefined);
|
|
328
|
+
return lease;
|
|
329
|
+
}
|
|
330
|
+
/** Every layer id whose state may be kept for the thread. */
|
|
331
|
+
function layerIdsFor(host, records) {
|
|
332
|
+
const ids = new Set(host.layerIds());
|
|
333
|
+
for (const record of records) {
|
|
334
|
+
for (const id of record?.layers ?? []) {
|
|
335
|
+
ids.add(id);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return ids;
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* @internal
|
|
342
|
+
* Forget a thread: settle its spend, then delete its executions, layer state,
|
|
343
|
+
* display output, record and lease, in that order, holding the lease throughout.
|
|
344
|
+
* The caller keeps new turns of the thread from starting in this harness meanwhile.
|
|
345
|
+
*/
|
|
346
|
+
export async function forgetThread(host, threadId, options = {}) {
|
|
347
|
+
const before = await recordOf(host, threadId);
|
|
348
|
+
refuseBusy(host, threadId, before);
|
|
349
|
+
const lease = await holdThread(host, threadId, {
|
|
350
|
+
record: before,
|
|
351
|
+
waitMs: options.waitMs ?? 0,
|
|
352
|
+
});
|
|
353
|
+
try {
|
|
354
|
+
const report = await forgetHeldThread(host, threadId, {
|
|
355
|
+
options,
|
|
356
|
+
before,
|
|
357
|
+
lease,
|
|
358
|
+
});
|
|
359
|
+
return report;
|
|
360
|
+
}
|
|
361
|
+
catch (error) {
|
|
362
|
+
await lease?.release();
|
|
363
|
+
throw error;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
async function forgetHeldThread(host, threadId, held) {
|
|
367
|
+
const { options, before, lease } = held;
|
|
368
|
+
const covered = await withChildren(host, executionsOf(before));
|
|
369
|
+
await stopChildren(host, covered, options.subprocesses ?? []);
|
|
370
|
+
const executions = covered.executions;
|
|
371
|
+
const spend = await host.closeSpend((record) => record.threadId === threadId ||
|
|
372
|
+
(record.executionId !== undefined && executions.has(record.executionId)), options.patienceMs);
|
|
373
|
+
await lease?.verify();
|
|
374
|
+
// A turn may have begun before the lease was taken: read the record again under it.
|
|
375
|
+
const after = await recordOf(host, threadId);
|
|
376
|
+
refuseBusy(host, threadId, after);
|
|
377
|
+
const again = await withChildren(host, executionsOf(after));
|
|
378
|
+
const added = [
|
|
379
|
+
...again.executions,
|
|
380
|
+
].filter((executionId) => !executions.has(executionId));
|
|
381
|
+
if (added.length > 0) {
|
|
382
|
+
await stopChildren(host, again, options.subprocesses ?? []);
|
|
383
|
+
spend.push(...(await host.closeSpend((record) => record.executionId !== undefined && added.includes(record.executionId), options.patienceMs)));
|
|
384
|
+
}
|
|
385
|
+
const executionIds = [
|
|
386
|
+
...executions,
|
|
387
|
+
...added,
|
|
388
|
+
];
|
|
389
|
+
host.dropThread(threadId);
|
|
390
|
+
await forgetExecutionState(host, executionIds, {
|
|
391
|
+
keepTrail: options.keepTrail === true,
|
|
392
|
+
lease,
|
|
393
|
+
});
|
|
394
|
+
await forgetLayerState(host, threadId, layerIdsFor(host, [
|
|
395
|
+
before,
|
|
396
|
+
after,
|
|
397
|
+
]));
|
|
398
|
+
await host.settleOutput(threadId);
|
|
399
|
+
await host.outputStorage.delete(outputKey(threadId));
|
|
400
|
+
await lease?.verify();
|
|
401
|
+
if (host.storage) {
|
|
402
|
+
await host.storage.delete(sessionKey(threadId));
|
|
403
|
+
}
|
|
404
|
+
// The lease goes last, while still held: a forget cut off before this leaves the thread listed.
|
|
405
|
+
await lease?.stop();
|
|
406
|
+
await lease?.verify();
|
|
407
|
+
await host.storage?.delete(leaseKey(threadId));
|
|
408
|
+
return {
|
|
409
|
+
threadId,
|
|
410
|
+
executionIds,
|
|
411
|
+
spend,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* @internal
|
|
416
|
+
* Forget one execution: settle its spend, then delete everything under
|
|
417
|
+
* `execution:<id>:`. A thread's record is left alone.
|
|
418
|
+
*/
|
|
419
|
+
export async function forgetExecution(host, executionId, options = {}) {
|
|
420
|
+
const covered = await withChildren(host, [
|
|
421
|
+
executionId,
|
|
422
|
+
]);
|
|
423
|
+
const executions = covered.executions;
|
|
424
|
+
const live = [
|
|
425
|
+
...executions,
|
|
426
|
+
].find((id) => host.executionBusy(id));
|
|
427
|
+
if (live !== undefined) {
|
|
428
|
+
throw busy(live, `execution "${live}" has a run in flight in this harness`);
|
|
429
|
+
}
|
|
430
|
+
await stopChildren(host, covered, options.subprocesses ?? []);
|
|
431
|
+
const spend = await host.closeSpend((record) => record.executionId !== undefined && executions.has(record.executionId), options.patienceMs);
|
|
432
|
+
const executionIds = [
|
|
433
|
+
...executions,
|
|
434
|
+
];
|
|
435
|
+
await forgetExecutionState(host, executionIds, {
|
|
436
|
+
keepTrail: options.keepTrail === true,
|
|
437
|
+
});
|
|
438
|
+
return {
|
|
439
|
+
executionIds,
|
|
440
|
+
spend,
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
//#endregion
|
|
444
|
+
//#region Listing
|
|
445
|
+
/** @internal Every thread with a record, a lease, or display output stored. */
|
|
446
|
+
export async function listStoredThreads(host, options = {}) {
|
|
447
|
+
const prefix = options.prefix ?? '';
|
|
448
|
+
const found = new Set(await idsUnder(host.outputStorage, OUTPUT_PREFIX, prefix));
|
|
449
|
+
const storage = host.storage;
|
|
450
|
+
if (storage) {
|
|
451
|
+
for (const keyPrefix of [
|
|
452
|
+
SESSION_PREFIX,
|
|
453
|
+
LEASE_PREFIX,
|
|
454
|
+
]) {
|
|
455
|
+
for (const id of await idsUnder(storage, keyPrefix, prefix)) {
|
|
456
|
+
found.add(id);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
return [
|
|
461
|
+
...found,
|
|
462
|
+
].sort();
|
|
463
|
+
}
|
|
464
|
+
/** @internal Every execution with anything stored, and what is stored for it. */
|
|
465
|
+
export async function listStoredExecutions(host, options = {}) {
|
|
466
|
+
const prefix = options.prefix ?? '';
|
|
467
|
+
const parts = new Map();
|
|
468
|
+
const add = (executionId, part) => {
|
|
469
|
+
if (!executionId.startsWith(prefix)) {
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
const known = parts.get(executionId) ?? new Set();
|
|
473
|
+
known.add(part);
|
|
474
|
+
parts.set(executionId, known);
|
|
475
|
+
};
|
|
476
|
+
const keys = (await host.storage?.list(`${EXECUTION_PREFIX}${prefix}`)) ?? [];
|
|
477
|
+
for (const parsed of parseExecutionKeys(keys)) {
|
|
478
|
+
add(parsed.executionId, parsed.part);
|
|
479
|
+
}
|
|
480
|
+
// A checkpoint store of the host's own may keep snapshots outside `storage`.
|
|
481
|
+
for (const { executionId } of (await host.checkpointStore?.list()) ?? []) {
|
|
482
|
+
add(executionId, ExecutionPart.Snapshot);
|
|
483
|
+
}
|
|
484
|
+
return [
|
|
485
|
+
...parts,
|
|
486
|
+
]
|
|
487
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
488
|
+
.map(([executionId, stored]) => ({
|
|
489
|
+
executionId,
|
|
490
|
+
parts: [
|
|
491
|
+
...stored,
|
|
492
|
+
],
|
|
493
|
+
resumable: stored.has(ExecutionPart.Snapshot) || stored.has(ExecutionPart.Ledger),
|
|
494
|
+
}));
|
|
495
|
+
}
|
|
496
|
+
//#endregion
|
|
@@ -2,7 +2,7 @@ import type { ArtifactStore, ConnectionEntries, ConnectionTrigger, SecretResolve
|
|
|
2
2
|
import type { Verifier } from '@noetic-tools/types/verify';
|
|
3
3
|
import type { LayerStateStore } from './deps/context.js';
|
|
4
4
|
import type { CheckpointStore, StepLedgerRetention } from './deps/runtime.js';
|
|
5
|
-
import type { AgentHooks, CallModelRequest, ContextCacheConfig, ContextData, ContextLayer, CustomItem, CustomItemsBrand, DecideRequest, DecideResponse, DeliveryMode, FsAdapter, ItemSchemaConfig, LLMResponse, LlmProviderConfig, ProjectionPolicy, ShellAdapter, Steps, StorageAdapter, SubprocessAdapter, Tool, ToolApprover, TraceExporter, ZodType } from './deps/types.js';
|
|
5
|
+
import type { AgentHooks, CallModelRequest, ContextCacheConfig, ContextData, ContextLayer, CustomItem, CustomItemsBrand, DecideRequest, DecideResponse, DeliveryMode, FsAdapter, HeldCallHandler, HeldSteerPolicy, ItemSchemaConfig, LLMResponse, LlmProviderConfig, ProjectionPolicy, ShellAdapter, Steps, StorageAdapter, SubprocessAdapter, Tool, ToolApprover, TraceExporter, ZodType } from './deps/types.js';
|
|
6
6
|
/**
|
|
7
7
|
* Storage-scoped environment configuration for `AgentHarness`.
|
|
8
8
|
*
|
|
@@ -210,6 +210,20 @@ export interface AgentHarnessOpts<TParams extends Record<string, unknown> = Reco
|
|
|
210
210
|
* unapproved and the harness warns once per tool name.
|
|
211
211
|
*/
|
|
212
212
|
approveToolCall?: ToolApprover;
|
|
213
|
+
/**
|
|
214
|
+
* Puts a held tool call in front of a person (spec 08 § Held tool calls): called
|
|
215
|
+
* once per question per process with the call and a signal that aborts when the
|
|
216
|
+
* call is settled any other way. Return the answer, taken as a decision item passed
|
|
217
|
+
* to `execute()` is, or `undefined` to leave the call held. The approver still
|
|
218
|
+
* decides what is held; this is what the host does with what it held.
|
|
219
|
+
*/
|
|
220
|
+
onHeld?: HeldCallHandler;
|
|
221
|
+
/**
|
|
222
|
+
* What a steer does at the `held` steer point before any layer has a say: `apply`
|
|
223
|
+
* (the default) skips the held calls for it; `defer` keeps it queued behind them,
|
|
224
|
+
* so a question a person was shown stays open.
|
|
225
|
+
*/
|
|
226
|
+
steerWhileHeld?: HeldSteerPolicy;
|
|
213
227
|
/**
|
|
214
228
|
* The live things the agent works with — browsers, devices, apps, chat workspaces,
|
|
215
229
|
* sources — keyed by name, or as a list of named entries (`[mcp({ name, … })]`)
|
|
@@ -26,6 +26,12 @@
|
|
|
26
26
|
*/
|
|
27
27
|
import type { Item, ItemSchemaRegistry, RoundUsage } from '@noetic-tools/types';
|
|
28
28
|
import type { ToolCallResult } from '../runtime/tool-call.js';
|
|
29
|
+
/** Ledger kind of a model-loop round's record. */
|
|
30
|
+
export declare const ROUND_KIND = "callModel:round";
|
|
31
|
+
/** Ledger kind of one tool call's record within a round. */
|
|
32
|
+
export declare const CALL_KIND = "callModel:call";
|
|
33
|
+
/** What follows a round's key in the key of a call recorded beneath it. */
|
|
34
|
+
export declare const CALL_SEGMENT = "/call:";
|
|
29
35
|
/** A function call as the call ledger identifies it. */
|
|
30
36
|
interface CalledFunction {
|
|
31
37
|
callId: string;
|
|
@@ -30,8 +30,12 @@ import { isFunctionCall } from '../interpreter/typeguards.js';
|
|
|
30
30
|
import { hashStepInput } from '../runtime/durable/step-ledger.js';
|
|
31
31
|
import { ContextImpl } from './deps/runtime.js';
|
|
32
32
|
//#region Types
|
|
33
|
-
|
|
34
|
-
const
|
|
33
|
+
/** Ledger kind of a model-loop round's record. */
|
|
34
|
+
export const ROUND_KIND = 'callModel:round';
|
|
35
|
+
/** Ledger kind of one tool call's record within a round. */
|
|
36
|
+
export const CALL_KIND = 'callModel:call';
|
|
37
|
+
/** What follows a round's key in the key of a call recorded beneath it. */
|
|
38
|
+
export const CALL_SEGMENT = '/call:';
|
|
35
39
|
/** What a recorded tool call left: the result the round went on with. */
|
|
36
40
|
const CallOutputSchema = z.object({
|
|
37
41
|
output: z.string(),
|
|
@@ -193,7 +197,7 @@ export class RoundLedger {
|
|
|
193
197
|
calls(round) {
|
|
194
198
|
const ledger = this.ctx.ledger;
|
|
195
199
|
const stepId = this.dispatch.stepId;
|
|
196
|
-
const keyOf = (call) => `${this.key(round)}
|
|
200
|
+
const keyOf = (call) => `${this.key(round)}${CALL_SEGMENT}${call.callId}`;
|
|
197
201
|
// A call is the same call only with the same name and arguments, asked for by
|
|
198
202
|
// the same step input: a provider that numbers its calls from one each time
|
|
199
203
|
// would otherwise hand a call the result of another conversation's.
|
|
@@ -7,7 +7,7 @@ import { SteerPoint, validateSchema } from '@noetic-tools/types';
|
|
|
7
7
|
import { itemsToInput, toolModelOutputToProvider } from '../adapters/openrouter.js';
|
|
8
8
|
import { isFunctionCall } from '../interpreter/typeguards.js';
|
|
9
9
|
import { drainsOf } from '../runtime/drain.js';
|
|
10
|
-
import { heldCallsOf, heldScopeOf, mayWriteHolds, waitOnHeldCalls } from '../runtime/held-calls.js';
|
|
10
|
+
import { heldCallsOf, heldScopeOf, mayWriteHolds, noticeHeld, waitOnHeldCalls, } from '../runtime/held-calls.js';
|
|
11
11
|
import { createToolResultItem, executeToolCall } from '../runtime/tool-call.js';
|
|
12
12
|
import { emitToolUi } from '../runtime/tool-ui.js';
|
|
13
13
|
import { findTool } from './model-request.js';
|
|
@@ -64,6 +64,8 @@ async function executeToolRound(scope, params) {
|
|
|
64
64
|
});
|
|
65
65
|
}
|
|
66
66
|
const heldCalls = [];
|
|
67
|
+
/** What each held call was last announced as held for. */
|
|
68
|
+
const announcedAs = new Map();
|
|
67
69
|
for (const [index, fc] of functionCalls.entries()) {
|
|
68
70
|
await drainsOf(request.ctx)?.hold(request.ctx);
|
|
69
71
|
if (request.signal?.aborted) {
|
|
@@ -100,6 +102,7 @@ async function executeToolRound(scope, params) {
|
|
|
100
102
|
});
|
|
101
103
|
if (call.held) {
|
|
102
104
|
heldCalls.push(fc);
|
|
105
|
+
announcedAs.set(fc.callId, call.held);
|
|
103
106
|
continue;
|
|
104
107
|
}
|
|
105
108
|
spans.recordToolSpan(modelSpan, fc.name, toolForCall?.needsApproval ?? false, call.approval);
|
|
@@ -142,10 +145,11 @@ async function executeToolRound(scope, params) {
|
|
|
142
145
|
conversationInput,
|
|
143
146
|
emitIfAllowed: params.emitIfAllowed,
|
|
144
147
|
calls: params.calls,
|
|
145
|
-
announced:
|
|
148
|
+
announced: announcedAs.get(fc.callId),
|
|
146
149
|
});
|
|
147
150
|
if (call.held) {
|
|
148
151
|
heldCalls.push(fc);
|
|
152
|
+
announcedAs.set(fc.callId, call.held);
|
|
149
153
|
continue;
|
|
150
154
|
}
|
|
151
155
|
spans.recordToolSpan(modelSpan, fc.name, toolForCall?.needsApproval ?? false, call.approval);
|
|
@@ -208,13 +212,23 @@ async function executeFunctionCall(scope, params) {
|
|
|
208
212
|
}));
|
|
209
213
|
// Held: it has no result yet. Nothing goes into the conversation for it.
|
|
210
214
|
if (toolResult.held) {
|
|
211
|
-
if (
|
|
215
|
+
if (params.announced !== toolResult.held.reason) {
|
|
212
216
|
params.emitIfAllowed('tool_call_held', {
|
|
213
217
|
...toolResult.held,
|
|
214
218
|
});
|
|
219
|
+
if (request.ctx) {
|
|
220
|
+
noticeHeld({
|
|
221
|
+
harness: scope.harness,
|
|
222
|
+
ctx: request.ctx,
|
|
223
|
+
held: toolResult.held,
|
|
224
|
+
emit: (settled) => params.emitIfAllowed('tool_call_settled', {
|
|
225
|
+
...settled,
|
|
226
|
+
}),
|
|
227
|
+
});
|
|
228
|
+
}
|
|
215
229
|
}
|
|
216
230
|
return {
|
|
217
|
-
held:
|
|
231
|
+
held: toolResult.held.reason,
|
|
218
232
|
};
|
|
219
233
|
}
|
|
220
234
|
// A replayed call appends the item it appended before, under the same id.
|
|
@@ -380,7 +394,7 @@ async function dropHolds(scope, request, calls) {
|
|
|
380
394
|
const executionId = heldScopeOf(request.ctx);
|
|
381
395
|
for (const call of calls) {
|
|
382
396
|
if (await holds.load(executionId, call.callId)) {
|
|
383
|
-
await holds.close(executionId, call.callId);
|
|
397
|
+
await holds.close(executionId, call.callId, 'skipped');
|
|
384
398
|
}
|
|
385
399
|
}
|
|
386
400
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tool calls an execution's step ledger holds (spec 23a § Tool calls in a round).
|
|
3
|
+
*
|
|
4
|
+
* A resumed run replays what its ledger recorded: completed steps with the items they
|
|
5
|
+
* appended, the rounds of an unfinished model loop with theirs, and the calls a cut-off
|
|
6
|
+
* round finished. A host that keeps its own record of tool traffic reads this list to
|
|
7
|
+
* know which calls the resume brings back on its own, so it never adds them twice.
|
|
8
|
+
*/
|
|
9
|
+
import type { RecordedToolCall } from '@noetic-tools/types';
|
|
10
|
+
import type { StepLedgerWindow } from '../runtime/durable/step-ledger.js';
|
|
11
|
+
/**
|
|
12
|
+
* The tool calls a recovered ledger window holds, in the order they were recorded.
|
|
13
|
+
* A call is `settled` when its result is on record too, in the same entry or as a
|
|
14
|
+
* call record beneath its round.
|
|
15
|
+
*/
|
|
16
|
+
export declare function recordedToolCalls(window: StepLedgerWindow): RecordedToolCall[];
|