@a-dray/aglib 0.6.6 → 0.7.0
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/README.md +2 -1
- package/dist/harness/adapters/claude-agent-sdk/index.d.ts +55 -0
- package/dist/harness/adapters/claude-agent-sdk/index.js +267 -0
- package/dist/harness/adapters/claude-agent-sdk/index.js.map +1 -0
- package/dist/harness/adapters/codex/index.d.ts +80 -0
- package/dist/harness/adapters/codex/index.js +373 -0
- package/dist/harness/adapters/codex/index.js.map +1 -0
- package/dist/harness/adapters/native/compaction.d.ts +8 -2
- package/dist/harness/adapters/native/compaction.js +77 -33
- package/dist/harness/adapters/native/compaction.js.map +1 -1
- package/dist/harness/adapters/vendor.d.ts +98 -0
- package/dist/harness/adapters/vendor.js +217 -0
- package/dist/harness/adapters/vendor.js.map +1 -0
- package/dist/model/adapters/openai-compatible/index.js +7 -3
- package/dist/model/adapters/openai-compatible/index.js.map +1 -1
- package/dist/model/adapters/openai-responses/index.d.ts +2 -0
- package/dist/model/adapters/openai-responses/index.js +5 -4
- package/dist/model/adapters/openai-responses/index.js.map +1 -1
- package/dist/run.js +62 -13
- package/dist/run.js.map +1 -1
- package/dist/store/adapters/sqlite.js +42 -6
- package/dist/store/adapters/sqlite.js.map +1 -1
- package/dist/store/conformance.d.ts +1 -1
- package/dist/store/conformance.js +19 -0
- package/dist/store/conformance.js.map +1 -1
- package/dist/store/store.d.ts +26 -12
- package/dist/store/store.js.map +1 -1
- package/package.json +16 -3
package/dist/run.js
CHANGED
|
@@ -43,8 +43,36 @@ export function runAgent(options) {
|
|
|
43
43
|
let result;
|
|
44
44
|
let unwatch;
|
|
45
45
|
let clearInputWait;
|
|
46
|
+
let renewal;
|
|
47
|
+
let lost;
|
|
46
48
|
try {
|
|
47
49
|
const { agent, store } = options;
|
|
50
|
+
// A claimed run keeps its claim while its model or a tool is quiet, and
|
|
51
|
+
// stops the moment the claim is gone: whoever holds it now owns the
|
|
52
|
+
// session, and nothing this run does next would be its to do.
|
|
53
|
+
const renew = async () => {
|
|
54
|
+
if (!claim || !store || lost)
|
|
55
|
+
return lost;
|
|
56
|
+
const renewed = await store.renew({ sessionId, claimId: claim.claimId });
|
|
57
|
+
if (!renewed.ok) {
|
|
58
|
+
lost = renewed.error;
|
|
59
|
+
controller.abort();
|
|
60
|
+
}
|
|
61
|
+
return lost;
|
|
62
|
+
};
|
|
63
|
+
if (claim && store) {
|
|
64
|
+
if (await renew())
|
|
65
|
+
return { status: "failed", error: lost, seq: claim.seq, usage };
|
|
66
|
+
let renewing = false;
|
|
67
|
+
renewal = setInterval(() => {
|
|
68
|
+
if (renewing)
|
|
69
|
+
return;
|
|
70
|
+
renewing = true;
|
|
71
|
+
void renew()
|
|
72
|
+
.catch((error) => { lost = { code: "unavailable", message: String(error), retryable: false }; controller.abort(); })
|
|
73
|
+
.finally(() => { renewing = false; });
|
|
74
|
+
}, claim.renewAfterMs);
|
|
75
|
+
}
|
|
48
76
|
const restored = store ? await open(store, sessionId, agent, options.key) : undefined;
|
|
49
77
|
if (restored && !restored.ok) {
|
|
50
78
|
return {
|
|
@@ -130,6 +158,7 @@ export function runAgent(options) {
|
|
|
130
158
|
if (store) {
|
|
131
159
|
const written = await store.append({
|
|
132
160
|
sessionId, expectedSeq: log.seq, entries,
|
|
161
|
+
...(claim ? { claimId: claim.claimId } : {}),
|
|
133
162
|
...(deliveries.length ? { enqueue: deliveries } : {}),
|
|
134
163
|
...(take ? { takePending: take } : {}),
|
|
135
164
|
});
|
|
@@ -232,7 +261,17 @@ export function runAgent(options) {
|
|
|
232
261
|
const executor = agent.tools?.length
|
|
233
262
|
? createExecutor({
|
|
234
263
|
tools: agent.tools,
|
|
235
|
-
|
|
264
|
+
// A tool's effect is the thing a lost claim cannot take back, so a
|
|
265
|
+
// claimed run checks it still owns the session before admitting one
|
|
266
|
+
// — and again after the policy, which may itself have waited.
|
|
267
|
+
...(claim ? { decide: async (call) => {
|
|
268
|
+
const before = await renew();
|
|
269
|
+
if (before)
|
|
270
|
+
return { action: "reject", message: before.message };
|
|
271
|
+
const decision = agent.decide ? await agent.decide(call) : { action: "execute" };
|
|
272
|
+
const after = await renew();
|
|
273
|
+
return after ? { action: "reject", message: after.message } : decision;
|
|
274
|
+
} } : agent.decide ? { decide: agent.decide } : {}),
|
|
236
275
|
sessionId, runId,
|
|
237
276
|
report: (callId, data) => updates.push({ type: "tool.progress", callId, data }),
|
|
238
277
|
})
|
|
@@ -267,24 +306,30 @@ export function runAgent(options) {
|
|
|
267
306
|
// it, so one session never holds two open runs. Only on a claim: the
|
|
268
307
|
// store established there that nothing else is running, where a bare
|
|
269
308
|
// `sessionId` establishes nothing and the run may still be live.
|
|
270
|
-
|
|
271
|
-
await commit([{
|
|
272
|
-
type: "run.finished", runId: interrupted, outcome: "cancelled",
|
|
273
|
-
error: {
|
|
274
|
-
code: "superseded",
|
|
275
|
-
message: "This activation was interrupted, and a later one began over it.",
|
|
276
|
-
retryable: false,
|
|
277
|
-
},
|
|
278
|
-
}]);
|
|
279
|
-
}
|
|
309
|
+
//
|
|
280
310
|
// Nothing opens a resumption. A `run.started` recording input nobody sent
|
|
281
311
|
// would be a second beginning for one conversation; the loop reads the
|
|
282
312
|
// history it was handed instead, sees the call that already ran, and
|
|
283
313
|
// carries on rather than asking for it again.
|
|
284
|
-
|
|
314
|
+
//
|
|
315
|
+
// One commit for both: closing the predecessor in a write of its own
|
|
316
|
+
// released the claim between the two, and another worker could take the
|
|
317
|
+
// session in that gap.
|
|
318
|
+
const opening = arrivals.map((arrival) => ({
|
|
285
319
|
type: "run.started", runId, input: arrival.input,
|
|
286
320
|
...(arrival.from ? { from: arrival.from } : {}),
|
|
287
|
-
}))
|
|
321
|
+
}));
|
|
322
|
+
if (opening.length && interrupted && claim) {
|
|
323
|
+
opening.unshift({
|
|
324
|
+
type: "run.finished", runId: interrupted, outcome: "cancelled",
|
|
325
|
+
error: {
|
|
326
|
+
code: "superseded",
|
|
327
|
+
message: "This activation was interrupted, and a later one began over it.",
|
|
328
|
+
retryable: false,
|
|
329
|
+
},
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
await commit(opening);
|
|
288
333
|
// Every ceiling is checked where work is recorded, and a resumption
|
|
289
334
|
// records nothing before its first turn — so a deadline that had already
|
|
290
335
|
// passed was never seen. Checked once here too, before the harness is
|
|
@@ -365,6 +410,8 @@ export function runAgent(options) {
|
|
|
365
410
|
const settled = stopped && outcome.status === "cancelled"
|
|
366
411
|
? { status: "failed", error: stopped }
|
|
367
412
|
: outcome;
|
|
413
|
+
if (renewal)
|
|
414
|
+
clearInterval(renewal);
|
|
368
415
|
await commit([{
|
|
369
416
|
type: "run.finished", runId,
|
|
370
417
|
outcome: settled.status === "completed" ? "completed" : settled.status === "cancelled" ? "cancelled" : "failed",
|
|
@@ -397,6 +444,8 @@ export function runAgent(options) {
|
|
|
397
444
|
}
|
|
398
445
|
}
|
|
399
446
|
}
|
|
447
|
+
if (renewal)
|
|
448
|
+
clearInterval(renewal);
|
|
400
449
|
unwatch?.();
|
|
401
450
|
clearInputWait?.();
|
|
402
451
|
updates.close();
|
package/dist/run.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.js","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD;;;;;;;GAOG;AACH,MAAM,UAAU,QAAQ,CAAC,OAAwB;IAC/C,6EAA6E;IAC7E,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,IAAI,EAAE,CAAC;IACxC,IAAI,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAA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,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;YAC1C,CAAC,CAAC;YACF,OAAO;gBACL,KAAK,CAAC,IAAI;oBACR,SAAS,CAAC;wBACR,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;wBACtC,IAAI,KAAK,KAAK,SAAS;4BAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;wBACvD,IAAI,MAAM;4BAAE,OAAO,IAAI,EAAE,CAAC;wBAC1B,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,GAAG,QAAQ,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;oBACrE,CAAC;gBACH,CAAC;gBACD,KAAK,CAAC,MAAM,KAAiC,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;aAC9D,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { Agent, AgentRun, Arrival, RunAgentOptions, RunResult } from \"./agent.js\";\nimport type { Failure } from \"./result.js\";\nimport type { HarnessContext, HarnessResult, Update } from \"./harness/harness.js\";\nimport type { Delivery, Store, StoreConflict, StoreError } from \"./store/store.js\";\nimport type { Content } from \"./content.js\";\nimport type { Entry, Stored, Usage } from \"./session/entry.js\";\nimport { err } from \"./result.js\";\nimport { createLog } from \"./session/log.js\";\nimport { toMessages } from \"./session/messages.js\";\nimport { createExecutor } from \"./tools/execute.js\";\n\n/**\n * Start an agent on a session.\n *\n * Without a store the log lives in memory and the session is ephemeral; with\n * one, every commit is durable before the next turn is built. The agent\n * definition is identical either way — durability is a composition choice, not\n * a different program.\n */\nexport function runAgent(options: RunAgentOptions): AgentRun {\n // A claim names its own session; a caller sending into a new one names none.\n const hooks = options.agent.hooks ?? [];\n if (new Set(hooks.map(hook => hook.name)).size !== hooks.length || hooks.some(hook => !hook.name)) {\n throw new Error(\"Lifecycle hook names must be non-empty and unique.\");\n }\n const claim = options.claim;\n const sessionId = claim?.sessionId ?? options.sessionId ?? crypto.randomUUID();\n const controller = new AbortController();\n // Composed rather than forwarded. `addEventListener(\"abort\", …)` never fires\n // on a signal that has already aborted, so a caller who gave up before\n // calling got a full run anyway; and a listener added per run to a signal\n // that outlives it is a leak the run cannot clean up.\n const signal = options.signal\n ? AbortSignal.any([options.signal, controller.signal])\n : controller.signal;\n\n const updates = createChannel<Update>();\n const result = execute();\n\n return {\n result,\n cancel: () => controller.abort(),\n [Symbol.asyncIterator]: () => updates.iterator(),\n };\n\n async function execute(): Promise<RunResult> {\n // What this activation consumed. Summed from the model usage entries it\n // commits rather than reported by the harness, so one answer serves a loop\n // we own and a loop we do not — and so a run that failed still says what it\n // burned on the way there.\n const usage: Usage = {};\n let hookContext: HarnessContext | undefined;\n let result: RunResult | undefined;\n let unwatch: (() => void) | undefined;\n let clearInputWait: (() => void) | undefined;\n\n try {\n const { agent, store } = options;\n const restored = store ? await open(store, sessionId, agent, options.key) : undefined;\n if (restored && !restored.ok) {\n return {\n status: \"failed\", error: restored.error,\n seq: positionOf(restored.error, 0), usage,\n };\n }\n // The store's own position, not the last entry's. They agree only while\n // nothing has ever been folded away, and the store is the one that knows.\n const log = createLog(restored?.value.entries ?? [], restored?.value.seq ?? 0);\n const stopping = (error: Failure): RunResult => (result = { status: \"failed\", error, seq: log.seq, usage });\n\n // A claim was read at a position. If the session has moved since, this\n // worker lost, and the deliveries it was carrying are still where it\n // found them.\n if (claim && claim.seq !== log.seq) {\n return stopping({ code: \"conflict\", message: `Session is at ${log.seq}, not ${claim.seq}`, retryable: true });\n }\n\n // A ceiling on money needs something that can count it. Refused here\n // rather than silently ignored, because a limit that is declared and not\n // enforced is the most expensive kind of nothing.\n\n // The activation still open on this log, if one is. It decides three\n // things below: whether there is anything to resume, which run a\n // resumption continues, and which run a fresh activation supersedes.\n const interrupted = openRunId(log.entries);\n\n // What this run is adding, then what was waiting. A claim's deliveries\n // are named so the log records who each came from; anything the worker\n // supplies itself leads, because the only thing that ever does is\n // orientation for a harness with nowhere else to put it.\n const arrivals: readonly Arrival[] = [\n ...arrivalsOf(options.input),\n ...(claim?.pending ?? []).map((delivery): Arrival => ({\n input: delivery.input,\n ...(delivery.from ? { from: delivery.from } : {}),\n })),\n ];\n\n // A resumption continues the run it was handed, under that run's id. A\n // fresh id would leave the log holding a `run.started` nothing closes and\n // a `run.finished` nothing opened — a pair that only the store's\n // type-based rule saves, and that anything grouping entries by run reads\n // as broken. A resumption without an interrupted run is refused below.\n const runId = arrivals.length || !interrupted ? crypto.randomUUID() : interrupted;\n\n // The ceiling has one owner, and it is here rather than in a harness.\n // Counting committed entries is the only way to bound a harness that owns\n // its own loop — which is most of them — so a limit declared on the agent\n // holds for every one instead of only for ours.\n const limits = agent.limits;\n let stopped: Failure | undefined;\n let turns = 0;\n let toolCalls = 0;\n const generations = new Set<string>();\n\n function exceeded(): Failure | undefined {\n if (!limits) return undefined;\n if (limits.maxTurns !== undefined && turns >= limits.maxTurns) {\n return { code: \"turn-limit\", message: `Stopped after ${turns} turns.`, retryable: false };\n }\n if (limits.maxToolCalls !== undefined && toolCalls >= limits.maxToolCalls) {\n return { code: \"tool-call-limit\", message: `Stopped after ${toolCalls} tool calls.`, retryable: false };\n }\n // Checked where work is recorded rather than on a timer: a deadline\n // stops the next piece of work, it does not interrupt one mid-flight.\n if (limits.deadline !== undefined && Date.now() >= Date.parse(limits.deadline)) {\n return { code: \"deadline\", message: `Stopped at the deadline of ${limits.deadline}.`, retryable: false };\n }\n return undefined;\n }\n\n // How many deliveries the next write takes off this session's own queue:\n // what the claim was carrying, and afterwards whatever `drain` folded in.\n // Cleared by the write that lands, because the input is gone once the\n // entries carrying it are durable, and not before.\n let take = claim?.pending.length ?? 0;\n\n async function commit(entries: readonly Entry[], deliveries: readonly Delivery[] = []): Promise<void> {\n if (!entries.length && !deliveries.length) return;\n // Counted before the write, not after: the tokens were consumed whether\n // or not this entry wins the compare-and-swap, and a run that reports\n // nothing after paying for a generation is the opposite of what\n // `RunResult.usage` promises.\n for (const entry of entries) {\n if ((entry.type === \"assistant\" || entry.type === \"model.finished\") && entry.usage) accumulate(usage, entry.usage);\n }\n\n if (store) {\n const written = await store.append({\n sessionId, expectedSeq: log.seq, entries,\n ...(deliveries.length ? { enqueue: deliveries } : {}),\n ...(take ? { takePending: take } : {}),\n });\n if (!written.ok) throw new CommitFailed(written.error, positionOf(written.error, log.seq));\n take = 0;\n }\n for (const stored of log.append(entries)) updates.push({ type: \"entry\", entry: stored });\n\n if (!stopped) {\n for (const entry of entries) {\n if (entry.type === \"assistant\") {\n const id = entry.generation?.id;\n // A provider may commit a completed asynchronous call before\n // the generation itself ends. It is recovery state, not another\n // turn and not yet the boundary at which a turn ceiling applies.\n if (!entry.generation || entry.generation.endedAt) {\n if (!id || !generations.has(id)) turns += 1;\n if (id) generations.add(id);\n }\n }\n // `tool.finished`, not `tool.started`: the start is committed before\n // the batch executes, so counting it there cancelled the very batch\n // that reached the ceiling — `maxToolCalls: 1` ran no tools at all,\n // and said it had stopped after one.\n if (entry.type === \"tool.finished\") toolCalls += 1;\n }\n stopped = exceeded();\n if (stopped) controller.abort();\n }\n }\n\n let inputWake = false;\n let wakePromise: Promise<void> | undefined;\n let resolveWake: (() => void) | undefined;\n const wake = () => {\n inputWake = true;\n resolveWake?.();\n resolveWake = undefined;\n wakePromise = undefined;\n };\n if (store?.watch) {\n unwatch = store.watch((change) => {\n if (change.sessionId !== sessionId || !change.runnable) return;\n wake();\n });\n }\n signal.addEventListener(\"abort\", wake);\n clearInputWait = () => signal.removeEventListener(\"abort\", wake);\n\n async function waitForInput(): Promise<void> {\n if (!store || signal.aborted) return;\n if (inputWake) { inputWake = false; return; }\n if (!store.watch) {\n await new Promise<void>((resolve) => setTimeout(resolve, 100));\n return;\n }\n wakePromise ??= new Promise<void>((resolve) => { resolveWake = resolve; });\n await wakePromise;\n inputWake = false;\n }\n\n // Input that arrived while this activation was running, taken from the\n // front of the queue and committed as part of it. `takePending` removes\n // exactly what was committed, in the same write, so losing the position\n // loses the turn and never the messages.\n async function drain(): Promise<number> {\n if (!store) return 0;\n // Nothing is folded into an activation that is over. Draining here\n // committed the waiting deliveries and took them off the queue, and the\n // loop then ended — leaving a peer's message answered by nobody and\n // invisible to `next` (nothing pending) and to `interrupted` (no open run),\n // which is the trap this whole path exists to close.\n if (signal.aborted) return 0;\n const current = await store.read({ sessionId, afterSeq: log.seq });\n if (!current.ok || !current.value.pending.length) return 0;\n // Only `turn` asks to join this activation. The queue is ordered and\n // consumption is a prefix, so a later delivery cannot jump over one\n // explicitly left for the next activation.\n const boundary = current.value.pending.findIndex((delivery) => delivery.priority !== \"turn\");\n const waiting = current.value.pending.slice(0, boundary < 0 ? current.value.pending.length : boundary);\n if (!waiting.length) return 0;\n take = waiting.length;\n await commit(waiting.map((delivery): Entry => ({\n type: \"run.started\", runId, input: delivery.input,\n ...(delivery.from ? { from: delivery.from } : {}),\n })));\n return waiting.length;\n }\n\n const executor = agent.tools?.length\n ? createExecutor({\n tools: agent.tools,\n ...(agent.decide ? { decide: agent.decide } : {}),\n sessionId, runId,\n report: (callId, data) => updates.push({ type: \"tool.progress\", callId, data }),\n })\n : undefined;\n\n if (!arrivals.length) {\n // An open run is what a resumption continues. Without one there is\n // nothing half-done here: a closed log would otherwise take a second\n // `run.finished` with no beginning to match it.\n if (!interrupted) {\n return stopping({\n code: \"nothing-to-resume\",\n message: \"An activation with no input continues an interrupted run, and this session has none open.\",\n retryable: false,\n });\n }\n if (agent.harness.recovery !== \"history\") {\n // Asked to continue a log this harness cannot read. The interrupted\n // run is ended rather than left open, because nothing else will\n // continue it either — the harness is a property of the session — and\n // a run that stays open is handed back by `interrupted` every window,\n // for ever. A worker that provisions anything before it runs pays for\n // that each time round.\n const failure: Failure = {\n code: \"no-recovery\",\n message: `The ${agent.harness.id} harness cannot restart from history, so this activation cannot be continued.`,\n retryable: false,\n };\n stopped = failure;\n }\n }\n\n // An interrupted predecessor is ended before a new activation begins over\n // it, so one session never holds two open runs. Only on a claim: the\n // store established there that nothing else is running, where a bare\n // `sessionId` establishes nothing and the run may still be live.\n if (arrivals.length && interrupted && claim) {\n await commit([{\n type: \"run.finished\", runId: interrupted, outcome: \"cancelled\",\n error: {\n code: \"superseded\",\n message: \"This activation was interrupted, and a later one began over it.\",\n retryable: false,\n },\n }]);\n }\n\n // Nothing opens a resumption. A `run.started` recording input nobody sent\n // would be a second beginning for one conversation; the loop reads the\n // history it was handed instead, sees the call that already ran, and\n // carries on rather than asking for it again.\n await commit(arrivals.map((arrival): Entry => ({\n type: \"run.started\", runId, input: arrival.input,\n ...(arrival.from ? { from: arrival.from } : {}),\n })));\n\n // Every ceiling is checked where work is recorded, and a resumption\n // records nothing before its first turn — so a deadline that had already\n // passed was never seen. Checked once here too, before the harness is\n // handed anything.\n stopped ??= exceeded();\n\n function makeContext(): HarnessContext {\n const supplied = options.context;\n const current = supplied ? {\n ...(supplied.run ? { run: supplied.run } : {}),\n get turn() {\n const value = supplied.turn;\n return typeof value === \"function\" ? value() : value;\n },\n } : undefined;\n return {\n sessionId, runId,\n instructions: agent.instructions,\n history: () => toMessages({\n instructions: agent.instructions,\n entries: log.entries,\n ...(agent.attribution ? { attribution: true } : {}),\n ...(current ? { context: current } : {}),\n }),\n entries: () => log.entries,\n ...(current ? { context: current } : {}),\n ...(executor ? { tools: executor } : {}),\n commit,\n ...(store ? { drain, waitForInput } : {}),\n emit: (update) => updates.push(update),\n signal, hooks,\n };\n }\n\n async function stoppingHooks(outcome: HarnessResult) {\n const inputs: Entry[] = [];\n const outgoing: Delivery[] = [];\n for (const hook of hooks) {\n const response = await hook.beforeStop?.(hookContext!, outcome);\n if (response && \"input\" in response && outcome.status === \"completed\" && !signal.aborted && !stopped &&\n !log.entries.some(entry => entry.type === \"hook.input\" && entry.runId === runId && entry.hook === hook.name)) {\n inputs.push({ type: \"hook.input\", runId, hook: hook.name, input: response.input });\n }\n if (response && \"deliveries\" in response) outgoing.push(...response.deliveries);\n }\n return { inputs, deliveries: outgoing };\n }\n\n hookContext = makeContext();\n let outcome: HarnessResult;\n let outgoing: readonly Delivery[] = [];\n try {\n for (const hook of hooks) await hook.beforeRun?.(hookContext);\n for (;;) {\n outcome = stopped ? { status: \"failed\", error: stopped }\n : signal.aborted ? { status: \"cancelled\" }\n : await agent.harness.run(hookContext);\n if (stopped) outcome = { status: \"failed\", error: stopped };\n else if (signal.aborted) outcome = { status: \"cancelled\" };\n const ending = await stoppingHooks(outcome);\n if (!ending.inputs.length) { outgoing = ending.deliveries; break; }\n await commit(ending.inputs);\n }\n } catch (error) {\n if (error instanceof CommitFailed) throw error;\n outcome = { status: \"failed\", error: {\n code: \"hook-or-harness\", message: error instanceof Error ? error.message : String(error), retryable: false,\n } };\n }\n\n // A harness stopped by the ceiling reports a cancellation, because that is\n // all it saw. The run knows why it was cancelled and says so instead.\n const settled = stopped && outcome.status === \"cancelled\"\n ? { status: \"failed\" as const, error: stopped }\n : outcome;\n\n await commit(\n [{\n type: \"run.finished\", runId,\n outcome: settled.status === \"completed\" ? \"completed\" : settled.status === \"cancelled\" ? \"cancelled\" : \"failed\",\n ...(settled.status === \"failed\" ? { error: settled.error } : {}),\n }],\n outgoing,\n );\n\n if (settled.status === \"completed\") {\n return result = { status: \"completed\", output: settled.output, seq: log.seq, usage };\n }\n if (settled.status === \"cancelled\") return result = { status: \"cancelled\", seq: log.seq, usage };\n return stopping(settled.error);\n } catch (error) {\n if (error instanceof CommitFailed) {\n return result = { status: \"failed\", error: error.failure, seq: error.seq, usage };\n }\n throw error;\n } finally {\n if (hookContext) {\n const final = result ?? { status: \"failed\" as const, error: {\n code: \"run-error\", message: \"The run could not finish.\", retryable: false,\n }, seq: hookContext.entries().at(-1)?.seq ?? 0, usage };\n for (const hook of hooks) {\n try { await hook.afterRun?.(hookContext, final); }\n catch (error) {\n updates.push({ type: \"hook.error\", hook: hook.name, message: error instanceof Error ? error.message : String(error) });\n }\n }\n }\n unwatch?.();\n clearInputWait?.();\n updates.close();\n }\n }\n}\n\nclass CommitFailed extends Error {\n constructor(readonly failure: Failure, readonly seq: number) {\n super(failure.message);\n }\n}\n\n/**\n * Where the session actually is after a refused write. A conflict knows; every\n * other failure leaves the caller with the position it already had. Reporting\n * zero told a caller at forty that it was at the beginning.\n *\n * The `typeof` is not defensive noise: a store may report a conflict, and only\n * a `StoreConflict` carries the position. Casting on the code alone produced a\n * `RunResult.seq` of `undefined` under a type that says `number`.\n */\nfunction positionOf(error: StoreError, fallback: number): number {\n const actual = (error as StoreConflict).actualSeq;\n return error.code === \"conflict\" && typeof actual === \"number\" ? actual : fallback;\n}\n\nconst isArrival = (value: unknown): value is Arrival =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && \"input\" in value;\n\n/**\n * One arrival, or several.\n *\n * The elements decide it, because the outer shape cannot: an arrival names its\n * `input`, a content part names its `type`, and nothing is both. Reading every\n * array as a batch is what turned one image-and-text message into one entry per\n * part, each holding a part where whole content belongs.\n */\nfunction arrivalsOf(input: RunAgentOptions[\"input\"]): readonly Arrival[] {\n if (input === undefined) return [];\n // Nothing sent is nothing sent. Falling through committed a `run.started`\n // whose input was an empty array of content parts.\n if (Array.isArray(input) && input.length === 0) return [];\n if (Array.isArray(input) && input.length > 0 && input.every(isArrival)) return input;\n if (isArrival(input)) return [input];\n return [{ input: input as Content }];\n}\n\n/**\n * The activation still open on this log, if one is.\n *\n * `run.started` opens and `run.finished` closes, which is the same rule the\n * store maintains its claim from — read here from the entries rather than asked\n * of the store, because the log is the only thing that knows.\n */\nfunction openRunId(entries: readonly Stored[]): string | undefined {\n let open: string | undefined;\n for (const entry of entries) {\n if (entry.type === \"run.started\") open = entry.runId;\n if (entry.type === \"run.finished\") open = undefined;\n }\n return open;\n}\n\n/** Token counts add; unknown stays unknown rather than becoming a zero. */\nfunction accumulate(total: Usage, turn: Usage): void {\n for (const key of [\"inputTokens\", \"outputTokens\", \"cacheReadTokens\", \"cacheWriteTokens\", \"costUsd\"] as const) {\n if (turn[key] !== undefined) total[key] = (total[key] ?? 0) + turn[key]!;\n }\n}\n\nasync function open(store: Store, sessionId: string, agent: Agent, key?: string) {\n const existing = await store.read({ sessionId });\n if (existing.ok) {\n // `version` is documented as the boundary past which an agent is no longer\n // compatible with an existing session. Nothing was comparing it, so the\n // boundary held for exactly as long as nobody crossed it.\n const stored = existing.value.agent;\n if (stored.id !== agent.id || stored.version !== agent.version) {\n return err<StoreError>({\n code: \"conflict\",\n message: `Session ${sessionId} belongs to ${stored.id}@${stored.version}, not ${agent.id}@${agent.version}`,\n retryable: false,\n });\n }\n return existing;\n }\n if (existing.error.code !== \"not-found\") return existing;\n const created = await store.create({\n sessionId, agent: { id: agent.id, version: agent.version }, ...(key ? { key } : {}),\n });\n if (!created.ok) return created;\n return store.read({ sessionId });\n}\n\n/**\n * A bounded fan-out queue for ephemeral updates.\n *\n * One buffer of recent updates, which every listener starts from and which\n * never grows past its limit. That single rule gives three things:\n *\n * **A run nobody drains costs a fixed amount.** A headless worker used to\n * accumulate every delta of an entire activation, because the queue only ever\n * grew. Dropping the oldest is safe precisely because updates are not recovery\n * state and the committed log is.\n *\n * **Arriving late loses nothing that matters.** The first entry commits before\n * `runAgent` returns, so a caller that iterates immediately would otherwise\n * never see its own run start. A UI reconnecting mid-run gets recent history\n * for the same reason, without asking the store for it.\n *\n * **Everyone sees everything.** Each listener drains its own copy, so an\n * application can watch a run for telemetry and for a UI at once instead of the\n * two stealing events from each other.\n */\nfunction createChannel<T>(limit = 1_024) {\n interface Listener { buffer: T[]; wake?: () => void }\n const listeners = new Set<Listener>();\n const replay: T[] = [];\n let closed = false;\n\n const bounded = (buffer: T[], value: T) => {\n if (buffer.length >= limit) buffer.shift();\n buffer.push(value);\n };\n\n return {\n push(value: T) {\n bounded(replay, value);\n for (const listener of listeners) {\n bounded(listener.buffer, value);\n listener.wake?.();\n }\n },\n close() {\n closed = true;\n for (const listener of listeners) listener.wake?.();\n },\n iterator(): AsyncIterator<T> {\n const listener: Listener = { buffer: [...replay] };\n listeners.add(listener);\n const done = (): IteratorResult<T> => {\n listeners.delete(listener);\n return { value: undefined, done: true };\n };\n return {\n async next(): Promise<IteratorResult<T>> {\n for (;;) {\n const value = listener.buffer.shift();\n if (value !== undefined) return { value, done: false };\n if (closed) return done();\n await new Promise<void>((resolve) => { listener.wake = resolve; });\n }\n },\n async return(): Promise<IteratorResult<T>> { return done(); },\n };\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"run.js","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD;;;;;;;GAOG;AACH,MAAM,UAAU,QAAQ,CAAC,OAAwB;IAC/C,6EAA6E;IAC7E,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,IAAI,EAAE,CAAC;IACxC,IAAI,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,KAAK,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAClG,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IACxE,CAAC;IACD,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;IAC5B,MAAM,SAAS,GAAG,KAAK,EAAE,SAAS,IAAI,OAAO,CAAC,SAAS,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;IAC/E,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;IACzC,6EAA6E;IAC7E,uEAAuE;IACvE,0EAA0E;IAC1E,sDAAsD;IACtD,MAA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AAO,CAAC,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;gBAChC,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC;YACpB,CAAC;QACH,CAAC;QACD,KAAK;YACH,MAAM,GAAG,IAAI,CAAC;YACd,KAAK,MAAM,QAAQ,IAAI,SAAS;gBAAE,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC;QACtD,CAAC;QACD,QAAQ;YACN,MAAM,QAAQ,GAAa,EAAE,MAAM,EAAE,CAAC,GAAG,MAAM,CAAC,EAAE,CAAC;YACnD,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACxB,MAAM,IAAI,GAAG,GAAsB,EAAE;gBACnC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;gBAC3B,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;YAC1C,CAAC,CAAC;YACF,OAAO;gBACL,KAAK,CAAC,IAAI;oBACR,SAAS,CAAC;wBACR,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;wBACtC,IAAI,KAAK,KAAK,SAAS;4BAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;wBACvD,IAAI,MAAM;4BAAE,OAAO,IAAI,EAAE,CAAC;wBAC1B,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,GAAG,QAAQ,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;oBACrE,CAAC;gBACH,CAAC;gBACD,KAAK,CAAC,MAAM,KAAiC,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;aAC9D,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { Agent, AgentRun, Arrival, RunAgentOptions, RunResult } from \"./agent.js\";\nimport type { Failure } from \"./result.js\";\nimport type { HarnessContext, HarnessResult, Update } from \"./harness/harness.js\";\nimport type { Delivery, Store, StoreConflict, StoreError } from \"./store/store.js\";\nimport type { Content } from \"./content.js\";\nimport type { Entry, Stored, Usage } from \"./session/entry.js\";\nimport { err } from \"./result.js\";\nimport { createLog } from \"./session/log.js\";\nimport { toMessages } from \"./session/messages.js\";\nimport { createExecutor } from \"./tools/execute.js\";\n\n/**\n * Start an agent on a session.\n *\n * Without a store the log lives in memory and the session is ephemeral; with\n * one, every commit is durable before the next turn is built. The agent\n * definition is identical either way — durability is a composition choice, not\n * a different program.\n */\nexport function runAgent(options: RunAgentOptions): AgentRun {\n // A claim names its own session; a caller sending into a new one names none.\n const hooks = options.agent.hooks ?? [];\n if (new Set(hooks.map(hook => hook.name)).size !== hooks.length || hooks.some(hook => !hook.name)) {\n throw new Error(\"Lifecycle hook names must be non-empty and unique.\");\n }\n const claim = options.claim;\n const sessionId = claim?.sessionId ?? options.sessionId ?? crypto.randomUUID();\n const controller = new AbortController();\n // Composed rather than forwarded. `addEventListener(\"abort\", …)` never fires\n // on a signal that has already aborted, so a caller who gave up before\n // calling got a full run anyway; and a listener added per run to a signal\n // that outlives it is a leak the run cannot clean up.\n const signal = options.signal\n ? AbortSignal.any([options.signal, controller.signal])\n : controller.signal;\n\n const updates = createChannel<Update>();\n const result = execute();\n\n return {\n result,\n cancel: () => controller.abort(),\n [Symbol.asyncIterator]: () => updates.iterator(),\n };\n\n async function execute(): Promise<RunResult> {\n // What this activation consumed. Summed from the model usage entries it\n // commits rather than reported by the harness, so one answer serves a loop\n // we own and a loop we do not — and so a run that failed still says what it\n // burned on the way there.\n const usage: Usage = {};\n let hookContext: HarnessContext | undefined;\n let result: RunResult | undefined;\n let unwatch: (() => void) | undefined;\n let clearInputWait: (() => void) | undefined;\n let renewal: ReturnType<typeof setInterval> | undefined;\n let lost: Failure | undefined;\n\n try {\n const { agent, store } = options;\n // A claimed run keeps its claim while its model or a tool is quiet, and\n // stops the moment the claim is gone: whoever holds it now owns the\n // session, and nothing this run does next would be its to do.\n const renew = async (): Promise<Failure | undefined> => {\n if (!claim || !store || lost) return lost;\n const renewed = await store.renew({ sessionId, claimId: claim.claimId });\n if (!renewed.ok) { lost = renewed.error; controller.abort(); }\n return lost;\n };\n if (claim && store) {\n if (await renew()) return { status: \"failed\", error: lost!, seq: claim.seq, usage };\n let renewing = false;\n renewal = setInterval(() => {\n if (renewing) return;\n renewing = true;\n void renew()\n .catch((error: unknown) => { lost = { code: \"unavailable\", message: String(error), retryable: false }; controller.abort(); })\n .finally(() => { renewing = false; });\n }, claim.renewAfterMs);\n }\n const restored = store ? await open(store, sessionId, agent, options.key) : undefined;\n if (restored && !restored.ok) {\n return {\n status: \"failed\", error: restored.error,\n seq: positionOf(restored.error, 0), usage,\n };\n }\n // The store's own position, not the last entry's. They agree only while\n // nothing has ever been folded away, and the store is the one that knows.\n const log = createLog(restored?.value.entries ?? [], restored?.value.seq ?? 0);\n const stopping = (error: Failure): RunResult => (result = { status: \"failed\", error, seq: log.seq, usage });\n\n // A claim was read at a position. If the session has moved since, this\n // worker lost, and the deliveries it was carrying are still where it\n // found them.\n if (claim && claim.seq !== log.seq) {\n return stopping({ code: \"conflict\", message: `Session is at ${log.seq}, not ${claim.seq}`, retryable: true });\n }\n\n // A ceiling on money needs something that can count it. Refused here\n // rather than silently ignored, because a limit that is declared and not\n // enforced is the most expensive kind of nothing.\n\n // The activation still open on this log, if one is. It decides three\n // things below: whether there is anything to resume, which run a\n // resumption continues, and which run a fresh activation supersedes.\n const interrupted = openRunId(log.entries);\n\n // What this run is adding, then what was waiting. A claim's deliveries\n // are named so the log records who each came from; anything the worker\n // supplies itself leads, because the only thing that ever does is\n // orientation for a harness with nowhere else to put it.\n const arrivals: readonly Arrival[] = [\n ...arrivalsOf(options.input),\n ...(claim?.pending ?? []).map((delivery): Arrival => ({\n input: delivery.input,\n ...(delivery.from ? { from: delivery.from } : {}),\n })),\n ];\n\n // A resumption continues the run it was handed, under that run's id. A\n // fresh id would leave the log holding a `run.started` nothing closes and\n // a `run.finished` nothing opened — a pair that only the store's\n // type-based rule saves, and that anything grouping entries by run reads\n // as broken. A resumption without an interrupted run is refused below.\n const runId = arrivals.length || !interrupted ? crypto.randomUUID() : interrupted;\n\n // The ceiling has one owner, and it is here rather than in a harness.\n // Counting committed entries is the only way to bound a harness that owns\n // its own loop — which is most of them — so a limit declared on the agent\n // holds for every one instead of only for ours.\n const limits = agent.limits;\n let stopped: Failure | undefined;\n let turns = 0;\n let toolCalls = 0;\n const generations = new Set<string>();\n\n function exceeded(): Failure | undefined {\n if (!limits) return undefined;\n if (limits.maxTurns !== undefined && turns >= limits.maxTurns) {\n return { code: \"turn-limit\", message: `Stopped after ${turns} turns.`, retryable: false };\n }\n if (limits.maxToolCalls !== undefined && toolCalls >= limits.maxToolCalls) {\n return { code: \"tool-call-limit\", message: `Stopped after ${toolCalls} tool calls.`, retryable: false };\n }\n // Checked where work is recorded rather than on a timer: a deadline\n // stops the next piece of work, it does not interrupt one mid-flight.\n if (limits.deadline !== undefined && Date.now() >= Date.parse(limits.deadline)) {\n return { code: \"deadline\", message: `Stopped at the deadline of ${limits.deadline}.`, retryable: false };\n }\n return undefined;\n }\n\n // How many deliveries the next write takes off this session's own queue:\n // what the claim was carrying, and afterwards whatever `drain` folded in.\n // Cleared by the write that lands, because the input is gone once the\n // entries carrying it are durable, and not before.\n let take = claim?.pending.length ?? 0;\n\n async function commit(entries: readonly Entry[], deliveries: readonly Delivery[] = []): Promise<void> {\n if (!entries.length && !deliveries.length) return;\n // Counted before the write, not after: the tokens were consumed whether\n // or not this entry wins the compare-and-swap, and a run that reports\n // nothing after paying for a generation is the opposite of what\n // `RunResult.usage` promises.\n for (const entry of entries) {\n if ((entry.type === \"assistant\" || entry.type === \"model.finished\") && entry.usage) accumulate(usage, entry.usage);\n }\n\n if (store) {\n const written = await store.append({\n sessionId, expectedSeq: log.seq, entries,\n ...(claim ? { claimId: claim.claimId } : {}),\n ...(deliveries.length ? { enqueue: deliveries } : {}),\n ...(take ? { takePending: take } : {}),\n });\n if (!written.ok) throw new CommitFailed(written.error, positionOf(written.error, log.seq));\n take = 0;\n }\n for (const stored of log.append(entries)) updates.push({ type: \"entry\", entry: stored });\n\n if (!stopped) {\n for (const entry of entries) {\n if (entry.type === \"assistant\") {\n const id = entry.generation?.id;\n // A provider may commit a completed asynchronous call before\n // the generation itself ends. It is recovery state, not another\n // turn and not yet the boundary at which a turn ceiling applies.\n if (!entry.generation || entry.generation.endedAt) {\n if (!id || !generations.has(id)) turns += 1;\n if (id) generations.add(id);\n }\n }\n // `tool.finished`, not `tool.started`: the start is committed before\n // the batch executes, so counting it there cancelled the very batch\n // that reached the ceiling — `maxToolCalls: 1` ran no tools at all,\n // and said it had stopped after one.\n if (entry.type === \"tool.finished\") toolCalls += 1;\n }\n stopped = exceeded();\n if (stopped) controller.abort();\n }\n }\n\n let inputWake = false;\n let wakePromise: Promise<void> | undefined;\n let resolveWake: (() => void) | undefined;\n const wake = () => {\n inputWake = true;\n resolveWake?.();\n resolveWake = undefined;\n wakePromise = undefined;\n };\n if (store?.watch) {\n unwatch = store.watch((change) => {\n if (change.sessionId !== sessionId || !change.runnable) return;\n wake();\n });\n }\n signal.addEventListener(\"abort\", wake);\n clearInputWait = () => signal.removeEventListener(\"abort\", wake);\n\n async function waitForInput(): Promise<void> {\n if (!store || signal.aborted) return;\n if (inputWake) { inputWake = false; return; }\n if (!store.watch) {\n await new Promise<void>((resolve) => setTimeout(resolve, 100));\n return;\n }\n wakePromise ??= new Promise<void>((resolve) => { resolveWake = resolve; });\n await wakePromise;\n inputWake = false;\n }\n\n // Input that arrived while this activation was running, taken from the\n // front of the queue and committed as part of it. `takePending` removes\n // exactly what was committed, in the same write, so losing the position\n // loses the turn and never the messages.\n async function drain(): Promise<number> {\n if (!store) return 0;\n // Nothing is folded into an activation that is over. Draining here\n // committed the waiting deliveries and took them off the queue, and the\n // loop then ended — leaving a peer's message answered by nobody and\n // invisible to `next` (nothing pending) and to `interrupted` (no open run),\n // which is the trap this whole path exists to close.\n if (signal.aborted) return 0;\n const current = await store.read({ sessionId, afterSeq: log.seq });\n if (!current.ok || !current.value.pending.length) return 0;\n // Only `turn` asks to join this activation. The queue is ordered and\n // consumption is a prefix, so a later delivery cannot jump over one\n // explicitly left for the next activation.\n const boundary = current.value.pending.findIndex((delivery) => delivery.priority !== \"turn\");\n const waiting = current.value.pending.slice(0, boundary < 0 ? current.value.pending.length : boundary);\n if (!waiting.length) return 0;\n take = waiting.length;\n await commit(waiting.map((delivery): Entry => ({\n type: \"run.started\", runId, input: delivery.input,\n ...(delivery.from ? { from: delivery.from } : {}),\n })));\n return waiting.length;\n }\n\n const executor = agent.tools?.length\n ? createExecutor({\n tools: agent.tools,\n // A tool's effect is the thing a lost claim cannot take back, so a\n // claimed run checks it still owns the session before admitting one\n // — and again after the policy, which may itself have waited.\n ...(claim ? { decide: async (call: Parameters<NonNullable<typeof agent.decide>>[0]) => {\n const before = await renew();\n if (before) return { action: \"reject\" as const, message: before.message };\n const decision = agent.decide ? await agent.decide(call) : { action: \"execute\" as const };\n const after = await renew();\n return after ? { action: \"reject\" as const, message: after.message } : decision;\n } } : agent.decide ? { decide: agent.decide } : {}),\n sessionId, runId,\n report: (callId, data) => updates.push({ type: \"tool.progress\", callId, data }),\n })\n : undefined;\n\n if (!arrivals.length) {\n // An open run is what a resumption continues. Without one there is\n // nothing half-done here: a closed log would otherwise take a second\n // `run.finished` with no beginning to match it.\n if (!interrupted) {\n return stopping({\n code: \"nothing-to-resume\",\n message: \"An activation with no input continues an interrupted run, and this session has none open.\",\n retryable: false,\n });\n }\n if (agent.harness.recovery !== \"history\") {\n // Asked to continue a log this harness cannot read. The interrupted\n // run is ended rather than left open, because nothing else will\n // continue it either — the harness is a property of the session — and\n // a run that stays open is handed back by `interrupted` every window,\n // for ever. A worker that provisions anything before it runs pays for\n // that each time round.\n const failure: Failure = {\n code: \"no-recovery\",\n message: `The ${agent.harness.id} harness cannot restart from history, so this activation cannot be continued.`,\n retryable: false,\n };\n stopped = failure;\n }\n }\n\n // An interrupted predecessor is ended before a new activation begins over\n // it, so one session never holds two open runs. Only on a claim: the\n // store established there that nothing else is running, where a bare\n // `sessionId` establishes nothing and the run may still be live.\n //\n // Nothing opens a resumption. A `run.started` recording input nobody sent\n // would be a second beginning for one conversation; the loop reads the\n // history it was handed instead, sees the call that already ran, and\n // carries on rather than asking for it again.\n //\n // One commit for both: closing the predecessor in a write of its own\n // released the claim between the two, and another worker could take the\n // session in that gap.\n const opening: Entry[] = arrivals.map((arrival): Entry => ({\n type: \"run.started\", runId, input: arrival.input,\n ...(arrival.from ? { from: arrival.from } : {}),\n }));\n if (opening.length && interrupted && claim) {\n opening.unshift({\n type: \"run.finished\", runId: interrupted, outcome: \"cancelled\",\n error: {\n code: \"superseded\",\n message: \"This activation was interrupted, and a later one began over it.\",\n retryable: false,\n },\n });\n }\n await commit(opening);\n\n // Every ceiling is checked where work is recorded, and a resumption\n // records nothing before its first turn — so a deadline that had already\n // passed was never seen. Checked once here too, before the harness is\n // handed anything.\n stopped ??= exceeded();\n\n function makeContext(): HarnessContext {\n const supplied = options.context;\n const current = supplied ? {\n ...(supplied.run ? { run: supplied.run } : {}),\n get turn() {\n const value = supplied.turn;\n return typeof value === \"function\" ? value() : value;\n },\n } : undefined;\n return {\n sessionId, runId,\n instructions: agent.instructions,\n history: () => toMessages({\n instructions: agent.instructions,\n entries: log.entries,\n ...(agent.attribution ? { attribution: true } : {}),\n ...(current ? { context: current } : {}),\n }),\n entries: () => log.entries,\n ...(current ? { context: current } : {}),\n ...(executor ? { tools: executor } : {}),\n commit,\n ...(store ? { drain, waitForInput } : {}),\n emit: (update) => updates.push(update),\n signal, hooks,\n };\n }\n\n async function stoppingHooks(outcome: HarnessResult) {\n const inputs: Entry[] = [];\n const outgoing: Delivery[] = [];\n for (const hook of hooks) {\n const response = await hook.beforeStop?.(hookContext!, outcome);\n if (response && \"input\" in response && outcome.status === \"completed\" && !signal.aborted && !stopped &&\n !log.entries.some(entry => entry.type === \"hook.input\" && entry.runId === runId && entry.hook === hook.name)) {\n inputs.push({ type: \"hook.input\", runId, hook: hook.name, input: response.input });\n }\n if (response && \"deliveries\" in response) outgoing.push(...response.deliveries);\n }\n return { inputs, deliveries: outgoing };\n }\n\n hookContext = makeContext();\n let outcome: HarnessResult;\n let outgoing: readonly Delivery[] = [];\n try {\n for (const hook of hooks) await hook.beforeRun?.(hookContext);\n for (;;) {\n outcome = stopped ? { status: \"failed\", error: stopped }\n : signal.aborted ? { status: \"cancelled\" }\n : await agent.harness.run(hookContext);\n if (stopped) outcome = { status: \"failed\", error: stopped };\n else if (signal.aborted) outcome = { status: \"cancelled\" };\n const ending = await stoppingHooks(outcome);\n if (!ending.inputs.length) { outgoing = ending.deliveries; break; }\n await commit(ending.inputs);\n }\n } catch (error) {\n if (error instanceof CommitFailed) throw error;\n outcome = { status: \"failed\", error: {\n code: \"hook-or-harness\", message: error instanceof Error ? error.message : String(error), retryable: false,\n } };\n }\n\n // A harness stopped by the ceiling reports a cancellation, because that is\n // all it saw. The run knows why it was cancelled and says so instead.\n const settled = stopped && outcome.status === \"cancelled\"\n ? { status: \"failed\" as const, error: stopped }\n : outcome;\n if (renewal) clearInterval(renewal);\n\n await commit(\n [{\n type: \"run.finished\", runId,\n outcome: settled.status === \"completed\" ? \"completed\" : settled.status === \"cancelled\" ? \"cancelled\" : \"failed\",\n ...(settled.status === \"failed\" ? { error: settled.error } : {}),\n }],\n outgoing,\n );\n\n if (settled.status === \"completed\") {\n return result = { status: \"completed\", output: settled.output, seq: log.seq, usage };\n }\n if (settled.status === \"cancelled\") return result = { status: \"cancelled\", seq: log.seq, usage };\n return stopping(settled.error);\n } catch (error) {\n if (error instanceof CommitFailed) {\n return result = { status: \"failed\", error: error.failure, seq: error.seq, usage };\n }\n throw error;\n } finally {\n if (hookContext) {\n const final = result ?? { status: \"failed\" as const, error: {\n code: \"run-error\", message: \"The run could not finish.\", retryable: false,\n }, seq: hookContext.entries().at(-1)?.seq ?? 0, usage };\n for (const hook of hooks) {\n try { await hook.afterRun?.(hookContext, final); }\n catch (error) {\n updates.push({ type: \"hook.error\", hook: hook.name, message: error instanceof Error ? error.message : String(error) });\n }\n }\n }\n if (renewal) clearInterval(renewal);\n unwatch?.();\n clearInputWait?.();\n updates.close();\n }\n }\n}\n\nclass CommitFailed extends Error {\n constructor(readonly failure: Failure, readonly seq: number) {\n super(failure.message);\n }\n}\n\n/**\n * Where the session actually is after a refused write. A conflict knows; every\n * other failure leaves the caller with the position it already had. Reporting\n * zero told a caller at forty that it was at the beginning.\n *\n * The `typeof` is not defensive noise: a store may report a conflict, and only\n * a `StoreConflict` carries the position. Casting on the code alone produced a\n * `RunResult.seq` of `undefined` under a type that says `number`.\n */\nfunction positionOf(error: StoreError, fallback: number): number {\n const actual = (error as StoreConflict).actualSeq;\n return error.code === \"conflict\" && typeof actual === \"number\" ? actual : fallback;\n}\n\nconst isArrival = (value: unknown): value is Arrival =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && \"input\" in value;\n\n/**\n * One arrival, or several.\n *\n * The elements decide it, because the outer shape cannot: an arrival names its\n * `input`, a content part names its `type`, and nothing is both. Reading every\n * array as a batch is what turned one image-and-text message into one entry per\n * part, each holding a part where whole content belongs.\n */\nfunction arrivalsOf(input: RunAgentOptions[\"input\"]): readonly Arrival[] {\n if (input === undefined) return [];\n // Nothing sent is nothing sent. Falling through committed a `run.started`\n // whose input was an empty array of content parts.\n if (Array.isArray(input) && input.length === 0) return [];\n if (Array.isArray(input) && input.length > 0 && input.every(isArrival)) return input;\n if (isArrival(input)) return [input];\n return [{ input: input as Content }];\n}\n\n/**\n * The activation still open on this log, if one is.\n *\n * `run.started` opens and `run.finished` closes, which is the same rule the\n * store maintains its claim from — read here from the entries rather than asked\n * of the store, because the log is the only thing that knows.\n */\nfunction openRunId(entries: readonly Stored[]): string | undefined {\n let open: string | undefined;\n for (const entry of entries) {\n if (entry.type === \"run.started\") open = entry.runId;\n if (entry.type === \"run.finished\") open = undefined;\n }\n return open;\n}\n\n/** Token counts add; unknown stays unknown rather than becoming a zero. */\nfunction accumulate(total: Usage, turn: Usage): void {\n for (const key of [\"inputTokens\", \"outputTokens\", \"cacheReadTokens\", \"cacheWriteTokens\", \"costUsd\"] as const) {\n if (turn[key] !== undefined) total[key] = (total[key] ?? 0) + turn[key]!;\n }\n}\n\nasync function open(store: Store, sessionId: string, agent: Agent, key?: string) {\n const existing = await store.read({ sessionId });\n if (existing.ok) {\n // `version` is documented as the boundary past which an agent is no longer\n // compatible with an existing session. Nothing was comparing it, so the\n // boundary held for exactly as long as nobody crossed it.\n const stored = existing.value.agent;\n if (stored.id !== agent.id || stored.version !== agent.version) {\n return err<StoreError>({\n code: \"conflict\",\n message: `Session ${sessionId} belongs to ${stored.id}@${stored.version}, not ${agent.id}@${agent.version}`,\n retryable: false,\n });\n }\n return existing;\n }\n if (existing.error.code !== \"not-found\") return existing;\n const created = await store.create({\n sessionId, agent: { id: agent.id, version: agent.version }, ...(key ? { key } : {}),\n });\n if (!created.ok) return created;\n return store.read({ sessionId });\n}\n\n/**\n * A bounded fan-out queue for ephemeral updates.\n *\n * One buffer of recent updates, which every listener starts from and which\n * never grows past its limit. That single rule gives three things:\n *\n * **A run nobody drains costs a fixed amount.** A headless worker used to\n * accumulate every delta of an entire activation, because the queue only ever\n * grew. Dropping the oldest is safe precisely because updates are not recovery\n * state and the committed log is.\n *\n * **Arriving late loses nothing that matters.** The first entry commits before\n * `runAgent` returns, so a caller that iterates immediately would otherwise\n * never see its own run start. A UI reconnecting mid-run gets recent history\n * for the same reason, without asking the store for it.\n *\n * **Everyone sees everything.** Each listener drains its own copy, so an\n * application can watch a run for telemetry and for a UI at once instead of the\n * two stealing events from each other.\n */\nfunction createChannel<T>(limit = 1_024) {\n interface Listener { buffer: T[]; wake?: () => void }\n const listeners = new Set<Listener>();\n const replay: T[] = [];\n let closed = false;\n\n const bounded = (buffer: T[], value: T) => {\n if (buffer.length >= limit) buffer.shift();\n buffer.push(value);\n };\n\n return {\n push(value: T) {\n bounded(replay, value);\n for (const listener of listeners) {\n bounded(listener.buffer, value);\n listener.wake?.();\n }\n },\n close() {\n closed = true;\n for (const listener of listeners) listener.wake?.();\n },\n iterator(): AsyncIterator<T> {\n const listener: Listener = { buffer: [...replay] };\n listeners.add(listener);\n const done = (): IteratorResult<T> => {\n listeners.delete(listener);\n return { value: undefined, done: true };\n };\n return {\n async next(): Promise<IteratorResult<T>> {\n for (;;) {\n const value = listener.buffer.shift();\n if (value !== undefined) return { value, done: false };\n if (closed) return done();\n await new Promise<void>((resolve) => { listener.wake = resolve; });\n }\n },\n async return(): Promise<IteratorResult<T>> { return done(); },\n };\n },\n };\n}\n"]}
|
|
@@ -9,6 +9,7 @@ const tables = `
|
|
|
9
9
|
pending TEXT NOT NULL DEFAULT '[]',
|
|
10
10
|
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
11
11
|
running_since TEXT,
|
|
12
|
+
claim_id TEXT,
|
|
12
13
|
updated_at TEXT NOT NULL
|
|
13
14
|
);
|
|
14
15
|
CREATE TABLE IF NOT EXISTS entries (
|
|
@@ -37,6 +38,7 @@ const tables = `
|
|
|
37
38
|
*/
|
|
38
39
|
const added = [
|
|
39
40
|
{ table: "sessions", column: "running_since", type: "TEXT" },
|
|
41
|
+
{ table: "sessions", column: "claim_id", type: "TEXT" },
|
|
40
42
|
];
|
|
41
43
|
const indexes = `
|
|
42
44
|
CREATE INDEX IF NOT EXISTS sessions_by_key ON sessions (key, updated_at DESC, id DESC);
|
|
@@ -72,6 +74,9 @@ const DEFAULT_DELIVERY_MEMORY_MS = 7 * 24 * 60 * 60 * 1000;
|
|
|
72
74
|
export function createSqliteStore(input) {
|
|
73
75
|
const database = input.database;
|
|
74
76
|
const claimMs = input.claimMs ?? DEFAULT_CLAIM_MS;
|
|
77
|
+
/** A third of the window: two renewals can be missed before a live owner looks dead. */
|
|
78
|
+
const renewAfterMs = Math.max(1, Math.floor(claimMs / 3));
|
|
79
|
+
const owns = (row, claimId) => row.claim_id === claimId && !!row.running_since && Date.parse(row.running_since) + claimMs > Date.now();
|
|
75
80
|
const deliveryMemoryMs = input.deliveryMemoryMs ?? DEFAULT_DELIVERY_MEMORY_MS;
|
|
76
81
|
// Tables, then the columns an older build's tables lack, then the indexes —
|
|
77
82
|
// which is the only order that works, because an index may be over a column
|
|
@@ -163,7 +168,7 @@ export function createSqliteStore(input) {
|
|
|
163
168
|
* the queue is consumed here rather than in `next`, a loser leaves the
|
|
164
169
|
* messages it was carrying untouched.
|
|
165
170
|
*/
|
|
166
|
-
async append({ sessionId, expectedSeq, entries, enqueue, metadata, takePending }) {
|
|
171
|
+
async append({ sessionId, expectedSeq, claimId, entries, enqueue, metadata, takePending }) {
|
|
167
172
|
const at = new Date().toISOString();
|
|
168
173
|
try {
|
|
169
174
|
// Inside the try: on a busy database this is where the failure lands,
|
|
@@ -174,6 +179,12 @@ export function createSqliteStore(input) {
|
|
|
174
179
|
database.exec("ROLLBACK");
|
|
175
180
|
return err(notFound(sessionId));
|
|
176
181
|
}
|
|
182
|
+
// Ownership before position: a writer whose claim lapsed and passed on
|
|
183
|
+
// can still be at the right sequence, if nothing committed in between.
|
|
184
|
+
if (claimId !== undefined && !owns(session, claimId)) {
|
|
185
|
+
database.exec("ROLLBACK");
|
|
186
|
+
return err({ code: "conflict", message: "Session ownership expired or changed", retryable: false });
|
|
187
|
+
}
|
|
177
188
|
if (session.last_seq !== expectedSeq) {
|
|
178
189
|
database.exec("ROLLBACK");
|
|
179
190
|
return err({
|
|
@@ -188,8 +199,6 @@ export function createSqliteStore(input) {
|
|
|
188
199
|
// ends it. `next` reads this to keep a second one from beginning, and
|
|
189
200
|
// the log is the only thing that knows — so it is derived from the log
|
|
190
201
|
// rather than asserted by a caller.
|
|
191
|
-
const opens = entries.some((entry) => entry.type === "run.started");
|
|
192
|
-
const closes = entries.some((entry) => entry.type === "run.finished");
|
|
193
202
|
// Only a write that records work renews the claim. Renewing on any
|
|
194
203
|
// append at all meant a message *to* a session renewed the claim of the
|
|
195
204
|
// worker that was supposed to read it — so a dead worker's session
|
|
@@ -203,7 +212,11 @@ export function createSqliteStore(input) {
|
|
|
203
212
|
// longer than the claim window was handed to a second worker while it
|
|
204
213
|
// was still going — and a compare-and-swap cannot un-run a tool call.
|
|
205
214
|
// A worker that dies still releases, because a dead worker stops writing.
|
|
206
|
-
|
|
215
|
+
// The last lifecycle entry decides, so one write that closes an
|
|
216
|
+
// interrupted run and opens its successor leaves the session open.
|
|
217
|
+
const lifecycle = entries.findLast((entry) => entry.type === "run.started" || entry.type === "run.finished");
|
|
218
|
+
const runningSince = lifecycle?.type === "run.finished" ? null
|
|
219
|
+
: lifecycle?.type === "run.started" || (worked && session.running_since) ? at : session.running_since;
|
|
207
220
|
const merged = metadata
|
|
208
221
|
? JSON.stringify({ ...JSON.parse(session.metadata), ...metadata })
|
|
209
222
|
: session.metadata;
|
|
@@ -256,6 +269,8 @@ export function createSqliteStore(input) {
|
|
|
256
269
|
run(`UPDATE sessions SET pending = ?, updated_at = ? WHERE id = ?`, [JSON.stringify([...queueOf(target), delivery]), at, delivery.sessionId]);
|
|
257
270
|
delivered.add(delivery.sessionId);
|
|
258
271
|
}
|
|
272
|
+
if (!runningSince)
|
|
273
|
+
run(`UPDATE sessions SET claim_id = NULL WHERE id = ?`, [sessionId]);
|
|
259
274
|
database.exec("COMMIT");
|
|
260
275
|
// After the commit, never before: a watcher that looked on an earlier
|
|
261
276
|
// wake would find nothing and never be told again.
|
|
@@ -293,6 +308,23 @@ export function createSqliteStore(input) {
|
|
|
293
308
|
return err(failed(error));
|
|
294
309
|
}
|
|
295
310
|
},
|
|
311
|
+
async renew({ sessionId, claimId }) {
|
|
312
|
+
try {
|
|
313
|
+
database.exec("BEGIN IMMEDIATE");
|
|
314
|
+
const row = one(`SELECT * FROM sessions WHERE id = ?`, [sessionId]);
|
|
315
|
+
if (!row || !owns(row, claimId)) {
|
|
316
|
+
database.exec("ROLLBACK");
|
|
317
|
+
return err({ code: "conflict", message: "Session ownership expired or changed", retryable: false });
|
|
318
|
+
}
|
|
319
|
+
run(`UPDATE sessions SET running_since = ? WHERE id = ?`, [new Date().toISOString(), sessionId]);
|
|
320
|
+
database.exec("COMMIT");
|
|
321
|
+
return ok(undefined);
|
|
322
|
+
}
|
|
323
|
+
catch (error) {
|
|
324
|
+
database.exec("ROLLBACK");
|
|
325
|
+
return err(failed(error));
|
|
326
|
+
}
|
|
327
|
+
},
|
|
296
328
|
/**
|
|
297
329
|
* Claim a session that has input and no activation already running.
|
|
298
330
|
*
|
|
@@ -316,9 +348,11 @@ export function createSqliteStore(input) {
|
|
|
316
348
|
database.exec("COMMIT");
|
|
317
349
|
return ok(undefined);
|
|
318
350
|
}
|
|
319
|
-
|
|
351
|
+
const claimId = crypto.randomUUID();
|
|
352
|
+
run(`UPDATE sessions SET running_since = ?, claim_id = ? WHERE id = ?`, [new Date(now).toISOString(), claimId, row.id]);
|
|
320
353
|
database.exec("COMMIT");
|
|
321
354
|
return ok({
|
|
355
|
+
claimId, renewAfterMs,
|
|
322
356
|
sessionId: row.id,
|
|
323
357
|
seq: row.last_seq,
|
|
324
358
|
pending: queueOf(row),
|
|
@@ -354,9 +388,11 @@ export function createSqliteStore(input) {
|
|
|
354
388
|
database.exec("COMMIT");
|
|
355
389
|
return ok(undefined);
|
|
356
390
|
}
|
|
357
|
-
|
|
391
|
+
const claimId = crypto.randomUUID();
|
|
392
|
+
run(`UPDATE sessions SET running_since = ?, claim_id = ? WHERE id = ?`, [new Date(now).toISOString(), claimId, row.id]);
|
|
358
393
|
database.exec("COMMIT");
|
|
359
394
|
return ok({
|
|
395
|
+
claimId, renewAfterMs,
|
|
360
396
|
sessionId: row.id,
|
|
361
397
|
seq: row.last_seq,
|
|
362
398
|
pending: [],
|