@noetic-tools/core 5.22.0-next.1 → 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.
Files changed (60) hide show
  1. package/dist/adapters/in-memory-subprocess-adapter.js +4 -2
  2. package/dist/adapters/openrouter.d.ts +6 -1
  3. package/dist/adapters/openrouter.js +10 -0
  4. package/dist/builders/custom-item.d.ts +1 -1
  5. package/dist/builders/custom-item.js +14 -3
  6. package/dist/builders/decide-builders.d.ts +7 -0
  7. package/dist/builders/tool-builder.d.ts +5 -1
  8. package/dist/builders/tool-builder.js +2 -0
  9. package/dist/builders/workflow-control-nodes.js +1 -0
  10. package/dist/connections/pool.d.ts +18 -0
  11. package/dist/connections/pool.js +54 -9
  12. package/dist/connections/registry.js +11 -0
  13. package/dist/harness/agent-harness.d.ts +130 -3
  14. package/dist/harness/agent-harness.js +337 -22
  15. package/dist/harness/decide-call.d.ts +15 -0
  16. package/dist/harness/decide-call.js +57 -7
  17. package/dist/harness/deps/types.d.ts +1 -1
  18. package/dist/harness/forget.d.ts +57 -0
  19. package/dist/harness/forget.js +496 -0
  20. package/dist/harness/harness-options.d.ts +24 -1
  21. package/dist/harness/llm-client.d.ts +2 -0
  22. package/dist/harness/llm-client.js +9 -5
  23. package/dist/harness/model-rounds.d.ts +6 -0
  24. package/dist/harness/model-rounds.js +7 -3
  25. package/dist/harness/model-tool-round.js +67 -8
  26. package/dist/harness/recorded-tool-calls.d.ts +16 -0
  27. package/dist/harness/recorded-tool-calls.js +106 -0
  28. package/dist/harness/spend.d.ts +13 -1
  29. package/dist/harness/spend.js +82 -1
  30. package/dist/harness/steer-inbox.js +9 -5
  31. package/dist/harness/thread-record.d.ts +12 -1
  32. package/dist/harness/thread-record.js +63 -19
  33. package/dist/index.d.ts +9 -6
  34. package/dist/index.js +4 -3
  35. package/dist/interpreter/acp-tools.js +21 -4
  36. package/dist/interpreter/execute-action.js +7 -1
  37. package/dist/interpreter/execute-decide.js +5 -0
  38. package/dist/interpreter/execute.js +55 -3
  39. package/dist/interpreter/step-dispatcher.js +17 -1
  40. package/dist/interpreter/step-kind-dispatch.js +9 -1
  41. package/dist/portable/runtime.d.ts +4 -0
  42. package/dist/portable/runtime.js +2 -0
  43. package/dist/runtime/durable/child-links.d.ts +61 -0
  44. package/dist/runtime/durable/child-links.js +127 -0
  45. package/dist/runtime/durable/session-store.d.ts +6 -0
  46. package/dist/runtime/durable/session-store.js +16 -2
  47. package/dist/runtime/durable/turn-lease.d.ts +10 -0
  48. package/dist/runtime/durable/turn-lease.js +10 -2
  49. package/dist/runtime/event-broadcaster.d.ts +9 -1
  50. package/dist/runtime/event-broadcaster.js +16 -1
  51. package/dist/runtime/held-calls.d.ts +65 -6
  52. package/dist/runtime/held-calls.js +257 -5
  53. package/dist/runtime/output-store.d.ts +90 -0
  54. package/dist/runtime/output-store.js +243 -0
  55. package/dist/runtime/session-streams.d.ts +28 -7
  56. package/dist/runtime/session-streams.js +112 -67
  57. package/dist/runtime/tool-approval.d.ts +1 -3
  58. package/dist/runtime/tool-approval.js +1 -1
  59. package/package.json +2 -2
  60. package/schema/noetic-workflow.schema.json +27 -0
@@ -1,4 +1,4 @@
1
1
  export type { ContextCacheConfig, ContextCacheStore, ContextData, ContextLayer, ExecutionContext, ProjectionPolicy, StorageAdapter, } from '@noetic-tools/context';
2
- export type { AcpKeepAlive, AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, Channel, ChannelHandle, Context, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomItemsBrand, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DeliveryMode, DetachedHandle, DrainReport, ExecuteInput, ExecuteOptions, ExecutionScope, ExecutionStatus, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, ItemSchemaExtensions, LLMResponse, LlmProviderConfig, OnSteerParams, PendingSpend, RecallLayerOutput, RecallOptions, ReconcileSpendOptions, SessionScope, SessionUsage, ShellAdapter, Span, SpendSettlement, SteeringDecision, SteerVerdict, Step, StepLike, Steps, StepsInput, StepsOutput, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, UsageCharge, ValidStepChain, WriteOffSpendOptions, } from '@noetic-tools/types';
2
+ export type { AcpKeepAlive, AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, Channel, ChannelHandle, Context, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomItemsBrand, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DeliveryMode, DetachedHandle, DrainReport, ExecuteInput, ExecuteOptions, ExecutionScope, ExecutionStatus, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, HeldCallHandler, HeldSteerPolicy, Item, ItemSchemaConfig, ItemSchemaExtensions, LLMResponse, LlmProviderConfig, OnSteerParams, PendingSpend, RecallLayerOutput, RecallOptions, ReconcileSpendOptions, SessionScope, SessionUsage, ShellAdapter, Span, SpendSettlement, SteeringDecision, SteerVerdict, Step, StepLike, Steps, StepsInput, StepsOutput, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, UsageCharge, ValidStepChain, WriteOffSpendOptions, } from '@noetic-tools/types';
3
3
  export { SteeringAction } from '@noetic-tools/types';
4
4
  export type { ZodType } from 'zod';
@@ -0,0 +1,57 @@
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 type { ForgetOptions, ForgetReport, ListStoredOptions, SpendSettlement, StorageAdapter, StoredExecution, SubprocessAdapter } from '@noetic-tools/types';
7
+ import type { CheckpointStore } from '../runtime/durable/checkpoint-store.js';
8
+ import type { SessionStore } from '../runtime/durable/session-store.js';
9
+ import type { SpendRecord } from '../runtime/durable/spend-log.js';
10
+ import type { TurnLeaseOptions } from '../runtime/durable/turn-lease.js';
11
+ /** @internal What forgetting needs from its harness. */
12
+ export interface ForgetHost {
13
+ /** The harness's durable storage. Undefined when it has none. */
14
+ readonly storage?: StorageAdapter;
15
+ /** Where display output is kept: `storage`, or memory without it. */
16
+ readonly outputStorage: StorageAdapter;
17
+ readonly checkpointStore?: CheckpointStore;
18
+ readonly sessionStore?: SessionStore;
19
+ readonly leaseOptions?: TurnLeaseOptions;
20
+ /** True when this harness has a turn of the thread running. */
21
+ threadBusy(threadId: string): boolean;
22
+ /** True when this harness has a run in flight on the execution. */
23
+ executionBusy(executionId: string): boolean;
24
+ /** Settle the pending dispatches `owns` picks; empty without durable storage. */
25
+ closeSpend(owns: (record: SpendRecord) => boolean, patienceMs?: number): Promise<SpendSettlement[]>;
26
+ /** `clearCheckpoint`: the snapshot, ledger, held calls and pending entries. */
27
+ clearCheckpoint(executionId: string): Promise<void>;
28
+ /** Wait for the thread's queued display output to land, then drop it from memory. */
29
+ settleOutput(threadId: string): Promise<void>;
30
+ /** Drop what this harness holds in memory for the thread: its session and park watch. */
31
+ dropThread(threadId: string): void;
32
+ /** Ids of the context layers this harness keeps durable state for. */
33
+ layerIds(): ReadonlyArray<string>;
34
+ /** Release the pool leases this harness still holds for the run, freeing their connections. */
35
+ releaseConnections(executionId: string): Promise<void>;
36
+ /** The harness's `environment.subprocess`. */
37
+ readonly subprocess: SubprocessAdapter;
38
+ /** The harness itself: what it dispatched out of process is kept against it. */
39
+ readonly harness: object;
40
+ }
41
+ /**
42
+ * @internal
43
+ * Forget a thread: settle its spend, then delete its executions, layer state,
44
+ * display output, record and lease, in that order, holding the lease throughout.
45
+ * The caller keeps new turns of the thread from starting in this harness meanwhile.
46
+ */
47
+ export declare function forgetThread(host: ForgetHost, threadId: string, options?: ForgetOptions): Promise<ForgetReport>;
48
+ /**
49
+ * @internal
50
+ * Forget one execution: settle its spend, then delete everything under
51
+ * `execution:<id>:`. A thread's record is left alone.
52
+ */
53
+ export declare function forgetExecution(host: ForgetHost, executionId: string, options?: ForgetOptions): Promise<ForgetReport>;
54
+ /** @internal Every thread with a record, a lease, or display output stored. */
55
+ export declare function listStoredThreads(host: ForgetHost, options?: ListStoredOptions): Promise<string[]>;
56
+ /** @internal Every execution with anything stored, and what is stored for it. */
57
+ export declare function listStoredExecutions(host: ForgetHost, options?: ListStoredOptions): Promise<StoredExecution[]>;
@@ -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
  *
@@ -123,6 +123,15 @@ export interface AgentEnvironmentConfig {
123
123
  /** `AgentHarness` constructor options. */
124
124
  export interface AgentHarnessOpts<TParams extends Record<string, unknown> = Record<string, unknown>, TItem extends CustomItem = CustomItem> {
125
125
  name: string;
126
+ /**
127
+ * Keep each thread's streamed output for display (spec 08 § Display output):
128
+ * `getSessionOutput()` then returns every item the thread streamed, unfinished
129
+ * ones included, from this harness or a later one over the same storage. A root
130
+ * context from `createContext()` also joins its thread, so `run()` on it streams
131
+ * like a turn. Display output is kept apart from checkpoints and is never
132
+ * resumed from. Default false.
133
+ */
134
+ interactive?: boolean;
126
135
  /**
127
136
  * Root step tree executed for every turn submitted via `execute()`. The custom items
128
137
  * it declares (a `workflow()` step's brand) type `getItemStream`, `getFullStream`,
@@ -201,6 +210,20 @@ export interface AgentHarnessOpts<TParams extends Record<string, unknown> = Reco
201
210
  * unapproved and the harness warns once per tool name.
202
211
  */
203
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;
204
227
  /**
205
228
  * The live things the agent works with — browsers, devices, apps, chat workspaces,
206
229
  * sources — keyed by name, or as a list of named entries (`[mcp({ name, … })]`)
@@ -55,6 +55,8 @@ export declare class LlmGateway {
55
55
  * prices, and generation lookups.
56
56
  */
57
57
  readonly sdkClient?: OpenRouterSdk;
58
+ /** Where native decisions go when the provider's base URL is not OpenRouter's. */
59
+ private readonly decisionsServerUrl?;
58
60
  /** Model id → whether it answers natively as a decision model. */
59
61
  private readonly decisionModels;
60
62
  constructor(options: LlmGatewayOptions);
@@ -1,5 +1,5 @@
1
1
  import { frameworkCast } from '@noetic-tools/types';
2
- import { callDecide } from './decide-call.js';
2
+ import { callDecide, decisionsServerUrl } from './decide-call.js';
3
3
  import { HTTPClient, OpenRouter, OpenRouterSdk } from './deps/adapters.js';
4
4
  import { someStep } from './deps/interpreter.js';
5
5
  import { AgentHarnessModelCaller, noLlmProviderError } from './model-call.js';
@@ -134,8 +134,7 @@ function generationHook(spend) {
134
134
  }
135
135
  });
136
136
  }
137
- function createSdkClient(config, http) {
138
- const resolved = resolveLlmClient(config, readLlmEnv());
137
+ function createSdkClient(resolved, http) {
139
138
  if (!resolved) {
140
139
  return undefined;
141
140
  }
@@ -164,6 +163,8 @@ export class LlmGateway {
164
163
  * prices, and generation lookups.
165
164
  */
166
165
  sdkClient;
166
+ /** Where native decisions go when the provider's base URL is not OpenRouter's. */
167
+ decisionsServerUrl;
167
168
  /** Model id → whether it answers natively as a decision model. */
168
169
  decisionModels = new Map();
169
170
  constructor(options) {
@@ -172,9 +173,11 @@ export class LlmGateway {
172
173
  this.client = options.callModelOverride
173
174
  ? undefined
174
175
  : createClient(options.providerConfig, options.contextCache, http);
175
- this.sdkClient = options.callModelOverride
176
+ const resolved = options.callModelOverride
176
177
  ? undefined
177
- : createSdkClient(options.providerConfig, http);
178
+ : resolveLlmClient(options.providerConfig, readLlmEnv());
179
+ this.sdkClient = createSdkClient(resolved, http);
180
+ this.decisionsServerUrl = decisionsServerUrl(resolved?.serverURL);
178
181
  }
179
182
  callModel(request, host) {
180
183
  return new AgentHarnessModelCaller({
@@ -194,6 +197,7 @@ export class LlmGateway {
194
197
  }
195
198
  return callDecide(request, {
196
199
  client: this.sdkClient,
200
+ serverUrl: this.decisionsServerUrl,
197
201
  callModel,
198
202
  nativeModels: this.decisionModels,
199
203
  spend: this.#options.spend,
@@ -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;