@noetic-tools/core 5.22.0-next.2 → 5.22.0-next.4
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 +110 -4
- package/dist/harness/agent-harness.js +394 -40
- 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 +40 -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/park-watchers.d.ts +3 -2
- 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 +23 -1
- package/dist/harness/thread-record.js +98 -21
- package/dist/harness/turn-cuts.d.ts +50 -0
- package/dist/harness/turn-cuts.js +108 -0
- package/dist/index.d.ts +6 -7
- 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 +11 -0
- package/dist/runtime/durable/session-store.js +28 -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/session-runner.d.ts +9 -1
- package/dist/runtime/session-runner.js +34 -0
- package/dist/runtime/tool-approval.d.ts +1 -3
- package/dist/runtime/tool-approval.js +1 -1
- package/package.json +2 -2
|
@@ -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, StoredTurn, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, TurnCut, TurnCutReason, 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, ExecuteOptions, FsAdapter, HeldCallHandler, HeldSteerPolicy, ItemSchemaConfig, LLMResponse, LlmProviderConfig, ProjectionPolicy, ShellAdapter, Steps, StorageAdapter, StoredTurn, SubprocessAdapter, Tool, ToolApprover, TraceExporter, ZodType } from './deps/types.js';
|
|
6
6
|
/**
|
|
7
7
|
* Storage-scoped environment configuration for `AgentHarness`.
|
|
8
8
|
*
|
|
@@ -99,6 +99,23 @@ export interface TurnLeaseConfig {
|
|
|
99
99
|
waitMs?: number;
|
|
100
100
|
/** The clock leases are timed by. Default `Date.now`. */
|
|
101
101
|
now?: () => number;
|
|
102
|
+
/**
|
|
103
|
+
* How a turn cut by `lease_lost` or `ledger_write_failed` is run again (spec 23
|
|
104
|
+
* § Cut turns). Every field has a default.
|
|
105
|
+
*/
|
|
106
|
+
cut?: TurnCutConfig;
|
|
107
|
+
}
|
|
108
|
+
/** @public Settings for cut turns (spec 23 § Cut turns). */
|
|
109
|
+
export interface TurnCutConfig {
|
|
110
|
+
/**
|
|
111
|
+
* How many times a turn may be cut and run again. The cut after that fails the
|
|
112
|
+
* turn. Default `DEFAULT_CUT_ATTEMPTS` (3); `0` fails every turn that would be cut.
|
|
113
|
+
*/
|
|
114
|
+
attempts?: number;
|
|
115
|
+
/** How long after its first cut a turn is due again, in ms; doubled for each cut after. Default 1 000. */
|
|
116
|
+
delayMs?: number;
|
|
117
|
+
/** The longest a cut turn waits before it is due again, in ms. Default 60 000. */
|
|
118
|
+
maxDelayMs?: number;
|
|
102
119
|
}
|
|
103
120
|
/**
|
|
104
121
|
* Execution-environment configuration for `AgentHarness`: the storage,
|
|
@@ -210,6 +227,28 @@ export interface AgentHarnessOpts<TParams extends Record<string, unknown> = Reco
|
|
|
210
227
|
* unapproved and the harness warns once per tool name.
|
|
211
228
|
*/
|
|
212
229
|
approveToolCall?: ToolApprover;
|
|
230
|
+
/**
|
|
231
|
+
* Puts a held tool call in front of a person (spec 08 § Held tool calls): called
|
|
232
|
+
* once per question per process with the call and a signal that aborts when the
|
|
233
|
+
* call is settled any other way. Return the answer, taken as a decision item passed
|
|
234
|
+
* to `execute()` is, or `undefined` to leave the call held. The approver still
|
|
235
|
+
* decides what is held; this is what the host does with what it held.
|
|
236
|
+
*/
|
|
237
|
+
onHeld?: HeldCallHandler;
|
|
238
|
+
/**
|
|
239
|
+
* What a steer does at the `held` steer point before any layer has a say: `apply`
|
|
240
|
+
* (the default) skips the held calls for it; `defer` keeps it queued behind them,
|
|
241
|
+
* so a question a person was shown stays open.
|
|
242
|
+
*/
|
|
243
|
+
steerWhileHeld?: HeldSteerPolicy;
|
|
244
|
+
/**
|
|
245
|
+
* The `execute()` options a stored turn runs with when `wake()` is given none
|
|
246
|
+
* (spec 23 § Parked turns). A stored turn keeps no options of its own, since they
|
|
247
|
+
* hold live objects: tools, layers, connections and their credentials. A host that
|
|
248
|
+
* passes per-turn options to `execute()` rebuilds them here, so a turn woken by an
|
|
249
|
+
* alarm in a fresh process runs as it began.
|
|
250
|
+
*/
|
|
251
|
+
turnOptions?: (turn: StoredTurn) => ExecuteOptions | Promise<ExecuteOptions>;
|
|
213
252
|
/**
|
|
214
253
|
* The live things the agent works with — browsers, devices, apps, chat workspaces,
|
|
215
254
|
* 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.
|