@ny4n/durable 0.0.0-stage → 1.0.1
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/LICENSE +21 -0
- package/README.md +711 -2
- package/dist/documents.d.ts +66 -0
- package/dist/documents.d.ts.map +1 -0
- package/dist/documents.js +98 -0
- package/dist/documents.js.map +1 -0
- package/dist/entries.d.ts +31 -0
- package/dist/entries.d.ts.map +1 -0
- package/dist/entries.js +31 -0
- package/dist/entries.js.map +1 -0
- package/dist/env/decode.d.ts +16 -0
- package/dist/env/decode.d.ts.map +1 -0
- package/dist/env/decode.js +28 -0
- package/dist/env/decode.js.map +1 -0
- package/dist/env/index.d.ts +263 -0
- package/dist/env/index.d.ts.map +1 -0
- package/dist/env/index.js +49 -0
- package/dist/env/index.js.map +1 -0
- package/dist/env/line-scan.d.ts +13 -0
- package/dist/env/line-scan.d.ts.map +1 -0
- package/dist/env/line-scan.js +147 -0
- package/dist/env/line-scan.js.map +1 -0
- package/dist/env/node-watch.d.ts +29 -0
- package/dist/env/node-watch.d.ts.map +1 -0
- package/dist/env/node-watch.js +485 -0
- package/dist/env/node-watch.js.map +1 -0
- package/dist/env/node.d.ts +56 -0
- package/dist/env/node.d.ts.map +1 -0
- package/dist/env/node.js +1166 -0
- package/dist/env/node.js.map +1 -0
- package/dist/errors.d.ts +32 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +53 -0
- package/dist/errors.js.map +1 -0
- package/dist/harness/agent.d.ts +33 -0
- package/dist/harness/agent.d.ts.map +1 -0
- package/dist/harness/agent.js +235 -0
- package/dist/harness/agent.js.map +1 -0
- package/dist/harness/assistant.d.ts +15 -0
- package/dist/harness/assistant.d.ts.map +1 -0
- package/dist/harness/assistant.js +23 -0
- package/dist/harness/assistant.js.map +1 -0
- package/dist/harness/compaction.d.ts +56 -0
- package/dist/harness/compaction.d.ts.map +1 -0
- package/dist/harness/compaction.js +384 -0
- package/dist/harness/compaction.js.map +1 -0
- package/dist/harness/context.d.ts +63 -0
- package/dist/harness/context.d.ts.map +1 -0
- package/dist/harness/context.js +221 -0
- package/dist/harness/context.js.map +1 -0
- package/dist/harness/define.d.ts +18 -0
- package/dist/harness/define.d.ts.map +1 -0
- package/dist/harness/define.js +25 -0
- package/dist/harness/define.js.map +1 -0
- package/dist/harness/events.d.ts +180 -0
- package/dist/harness/events.d.ts.map +1 -0
- package/dist/harness/events.js +370 -0
- package/dist/harness/events.js.map +1 -0
- package/dist/harness/generation.d.ts +54 -0
- package/dist/harness/generation.d.ts.map +1 -0
- package/dist/harness/generation.js +514 -0
- package/dist/harness/generation.js.map +1 -0
- package/dist/harness/harness.d.ts +17 -0
- package/dist/harness/harness.d.ts.map +1 -0
- package/dist/harness/harness.js +332 -0
- package/dist/harness/harness.js.map +1 -0
- package/dist/harness/inbox.d.ts +59 -0
- package/dist/harness/inbox.d.ts.map +1 -0
- package/dist/harness/inbox.js +97 -0
- package/dist/harness/inbox.js.map +1 -0
- package/dist/harness/json.d.ts +10 -0
- package/dist/harness/json.d.ts.map +1 -0
- package/dist/harness/json.js +33 -0
- package/dist/harness/json.js.map +1 -0
- package/dist/harness/live.d.ts +142 -0
- package/dist/harness/live.d.ts.map +1 -0
- package/dist/harness/live.js +149 -0
- package/dist/harness/live.js.map +1 -0
- package/dist/harness/output.d.ts +69 -0
- package/dist/harness/output.d.ts.map +1 -0
- package/dist/harness/output.js +318 -0
- package/dist/harness/output.js.map +1 -0
- package/dist/harness/prompt.d.ts +27 -0
- package/dist/harness/prompt.d.ts.map +1 -0
- package/dist/harness/prompt.js +131 -0
- package/dist/harness/prompt.js.map +1 -0
- package/dist/harness/provider.d.ts +14 -0
- package/dist/harness/provider.d.ts.map +1 -0
- package/dist/harness/provider.js +30 -0
- package/dist/harness/provider.js.map +1 -0
- package/dist/harness/registry.d.ts +6 -0
- package/dist/harness/registry.d.ts.map +1 -0
- package/dist/harness/registry.js +101 -0
- package/dist/harness/registry.js.map +1 -0
- package/dist/harness/run.d.ts +17 -0
- package/dist/harness/run.d.ts.map +1 -0
- package/dist/harness/run.js +26 -0
- package/dist/harness/run.js.map +1 -0
- package/dist/harness/scheduler.d.ts +106 -0
- package/dist/harness/scheduler.d.ts.map +1 -0
- package/dist/harness/scheduler.js +1743 -0
- package/dist/harness/scheduler.js.map +1 -0
- package/dist/harness/submissions.d.ts +29 -0
- package/dist/harness/submissions.d.ts.map +1 -0
- package/dist/harness/submissions.js +175 -0
- package/dist/harness/submissions.js.map +1 -0
- package/dist/harness/task-graph.d.ts +49 -0
- package/dist/harness/task-graph.d.ts.map +1 -0
- package/dist/harness/task-graph.js +168 -0
- package/dist/harness/task-graph.js.map +1 -0
- package/dist/harness/tool.d.ts +76 -0
- package/dist/harness/tool.d.ts.map +1 -0
- package/dist/harness/tool.js +736 -0
- package/dist/harness/tool.js.map +1 -0
- package/dist/harness/types.d.ts +713 -0
- package/dist/harness/types.d.ts.map +1 -0
- package/dist/harness/types.js +2 -0
- package/dist/harness/types.js.map +1 -0
- package/dist/harness/usage.d.ts +18 -0
- package/dist/harness/usage.d.ts.map +1 -0
- package/dist/harness/usage.js +57 -0
- package/dist/harness/usage.js.map +1 -0
- package/dist/harness/util.d.ts +19 -0
- package/dist/harness/util.d.ts.map +1 -0
- package/dist/harness/util.js +58 -0
- package/dist/harness/util.js.map +1 -0
- package/dist/harness/view.d.ts +47 -0
- package/dist/harness/view.d.ts.map +1 -0
- package/dist/harness/view.js +206 -0
- package/dist/harness/view.js.map +1 -0
- package/dist/ids.d.ts +6 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +9 -0
- package/dist/ids.js.map +1 -0
- package/dist/images/cloudflare.d.ts +4 -0
- package/dist/images/cloudflare.d.ts.map +1 -0
- package/dist/images/cloudflare.js +9 -0
- package/dist/images/cloudflare.js.map +1 -0
- package/dist/images/exif.d.ts +3 -0
- package/dist/images/exif.d.ts.map +1 -0
- package/dist/images/exif.js +71 -0
- package/dist/images/exif.js.map +1 -0
- package/dist/images/index.d.ts +18 -0
- package/dist/images/index.d.ts.map +1 -0
- package/dist/images/index.js +125 -0
- package/dist/images/index.js.map +1 -0
- package/dist/images/node-worker.d.ts +17 -0
- package/dist/images/node-worker.d.ts.map +1 -0
- package/dist/images/node-worker.js +16 -0
- package/dist/images/node-worker.js.map +1 -0
- package/dist/images/node.d.ts +21 -0
- package/dist/images/node.d.ts.map +1 -0
- package/dist/images/node.js +121 -0
- package/dist/images/node.js.map +1 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +20 -0
- package/dist/index.js.map +1 -0
- package/dist/session/forks.d.ts +10 -0
- package/dist/session/forks.d.ts.map +1 -0
- package/dist/session/forks.js +42 -0
- package/dist/session/forks.js.map +1 -0
- package/dist/session/observation.d.ts +42 -0
- package/dist/session/observation.d.ts.map +1 -0
- package/dist/session/observation.js +281 -0
- package/dist/session/observation.js.map +1 -0
- package/dist/session/session.d.ts +133 -0
- package/dist/session/session.d.ts.map +1 -0
- package/dist/session/session.js +811 -0
- package/dist/session/session.js.map +1 -0
- package/dist/session/transaction.d.ts +119 -0
- package/dist/session/transaction.d.ts.map +1 -0
- package/dist/session/transaction.js +795 -0
- package/dist/session/transaction.js.map +1 -0
- package/dist/storage/jsonl/index.d.ts +2 -0
- package/dist/storage/jsonl/index.d.ts.map +1 -0
- package/dist/storage/jsonl/index.js +2 -0
- package/dist/storage/jsonl/index.js.map +1 -0
- package/dist/storage/jsonl/node.d.ts +6 -0
- package/dist/storage/jsonl/node.d.ts.map +1 -0
- package/dist/storage/jsonl/node.js +8 -0
- package/dist/storage/jsonl/node.js.map +1 -0
- package/dist/storage/jsonl/storage.d.ts +143 -0
- package/dist/storage/jsonl/storage.d.ts.map +1 -0
- package/dist/storage/jsonl/storage.js +682 -0
- package/dist/storage/jsonl/storage.js.map +1 -0
- package/dist/storage/memory.d.ts +62 -0
- package/dist/storage/memory.d.ts.map +1 -0
- package/dist/storage/memory.js +733 -0
- package/dist/storage/memory.js.map +1 -0
- package/dist/storage/scan.d.ts +18 -0
- package/dist/storage/scan.d.ts.map +1 -0
- package/dist/storage/scan.js +29 -0
- package/dist/storage/scan.js.map +1 -0
- package/dist/storage/sqlite/cloudflare.d.ts +46 -0
- package/dist/storage/sqlite/cloudflare.d.ts.map +1 -0
- package/dist/storage/sqlite/cloudflare.js +106 -0
- package/dist/storage/sqlite/cloudflare.js.map +1 -0
- package/dist/storage/sqlite/database.d.ts +37 -0
- package/dist/storage/sqlite/database.d.ts.map +1 -0
- package/dist/storage/sqlite/database.js +2 -0
- package/dist/storage/sqlite/database.js.map +1 -0
- package/dist/storage/sqlite/index.d.ts +4 -0
- package/dist/storage/sqlite/index.d.ts.map +1 -0
- package/dist/storage/sqlite/index.js +3 -0
- package/dist/storage/sqlite/index.js.map +1 -0
- package/dist/storage/sqlite/migrations.d.ts +11 -0
- package/dist/storage/sqlite/migrations.d.ts.map +1 -0
- package/dist/storage/sqlite/migrations.js +111 -0
- package/dist/storage/sqlite/migrations.js.map +1 -0
- package/dist/storage/sqlite/node.d.ts +41 -0
- package/dist/storage/sqlite/node.d.ts.map +1 -0
- package/dist/storage/sqlite/node.js +179 -0
- package/dist/storage/sqlite/node.js.map +1 -0
- package/dist/storage/sqlite/storage.d.ts +65 -0
- package/dist/storage/sqlite/storage.d.ts.map +1 -0
- package/dist/storage/sqlite/storage.js +670 -0
- package/dist/storage/sqlite/storage.js.map +1 -0
- package/dist/tasks.d.ts +6 -0
- package/dist/tasks.d.ts.map +1 -0
- package/dist/tasks.js +5 -0
- package/dist/tasks.js.map +1 -0
- package/dist/testing/assertions.d.ts +5 -0
- package/dist/testing/assertions.d.ts.map +1 -0
- package/dist/testing/assertions.js +25 -0
- package/dist/testing/assertions.js.map +1 -0
- package/dist/testing/env-conformance.d.ts +7 -0
- package/dist/testing/env-conformance.d.ts.map +1 -0
- package/dist/testing/env-conformance.js +431 -0
- package/dist/testing/env-conformance.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +6 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/runner.d.ts +12 -0
- package/dist/testing/runner.d.ts.map +1 -0
- package/dist/testing/runner.js +23 -0
- package/dist/testing/runner.js.map +1 -0
- package/dist/testing/storage-benchmark.d.ts +41 -0
- package/dist/testing/storage-benchmark.d.ts.map +1 -0
- package/dist/testing/storage-benchmark.js +350 -0
- package/dist/testing/storage-benchmark.js.map +1 -0
- package/dist/testing/storage-conformance.d.ts +4 -0
- package/dist/testing/storage-conformance.d.ts.map +1 -0
- package/dist/testing/storage-conformance.js +1213 -0
- package/dist/testing/storage-conformance.js.map +1 -0
- package/dist/testing/types.d.ts +37 -0
- package/dist/testing/types.d.ts.map +1 -0
- package/dist/testing/types.js +2 -0
- package/dist/testing/types.js.map +1 -0
- package/dist/tools/bash.d.ts +55 -0
- package/dist/tools/bash.d.ts.map +1 -0
- package/dist/tools/bash.js +138 -0
- package/dist/tools/bash.js.map +1 -0
- package/dist/tools/edit-diff.d.ts +89 -0
- package/dist/tools/edit-diff.d.ts.map +1 -0
- package/dist/tools/edit-diff.js +386 -0
- package/dist/tools/edit-diff.js.map +1 -0
- package/dist/tools/edit.d.ts +18 -0
- package/dist/tools/edit.d.ts.map +1 -0
- package/dist/tools/edit.js +117 -0
- package/dist/tools/edit.js.map +1 -0
- package/dist/tools/env.d.ts +5 -0
- package/dist/tools/env.d.ts.map +1 -0
- package/dist/tools/env.js +7 -0
- package/dist/tools/env.js.map +1 -0
- package/dist/tools/file-mutation-queue.d.ts +9 -0
- package/dist/tools/file-mutation-queue.d.ts.map +1 -0
- package/dist/tools/file-mutation-queue.js +52 -0
- package/dist/tools/file-mutation-queue.js.map +1 -0
- package/dist/tools/image-processor.d.ts +47 -0
- package/dist/tools/image-processor.d.ts.map +1 -0
- package/dist/tools/image-processor.js +30 -0
- package/dist/tools/image-processor.js.map +1 -0
- package/dist/tools/image.d.ts +20 -0
- package/dist/tools/image.d.ts.map +1 -0
- package/dist/tools/image.js +178 -0
- package/dist/tools/image.js.map +1 -0
- package/dist/tools/index.d.ts +46 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +23 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/path-utils.d.ts +5 -0
- package/dist/tools/path-utils.d.ts.map +1 -0
- package/dist/tools/path-utils.js +26 -0
- package/dist/tools/path-utils.js.map +1 -0
- package/dist/tools/read.d.ts +25 -0
- package/dist/tools/read.d.ts.map +1 -0
- package/dist/tools/read.js +235 -0
- package/dist/tools/read.js.map +1 -0
- package/dist/tools/write.d.ts +10 -0
- package/dist/tools/write.d.ts.map +1 -0
- package/dist/tools/write.js +31 -0
- package/dist/tools/write.js.map +1 -0
- package/dist/truncate.d.ts +64 -0
- package/dist/truncate.d.ts.map +1 -0
- package/dist/truncate.js +154 -0
- package/dist/truncate.js.map +1 -0
- package/dist/types.d.ts +932 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +140 -5
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
import { isContextOverflow } from "@ny4n/ai/utils/overflow";
|
|
2
|
+
import { isRetryableAssistantError, retryDelayMs } from "@ny4n/ai/utils/retry";
|
|
3
|
+
import { getCurrentTools } from "@ny4n/ai/utils/transcript";
|
|
4
|
+
import { copyJson } from "@ny4n/chord";
|
|
5
|
+
import { AssistantEntry, ResetEntry, SystemEntry, UserEntry } from "../entries.js";
|
|
6
|
+
import { defineTask } from "../tasks.js";
|
|
7
|
+
import { addTools } from "./agent.js";
|
|
8
|
+
import { appendAssistant, convertPartial } from "./assistant.js";
|
|
9
|
+
import { createCompaction, estimateContext, selectCut } from "./compaction.js";
|
|
10
|
+
import { applyBoundary, prepareBoundary } from "./inbox.js";
|
|
11
|
+
import { assignJson } from "./json.js";
|
|
12
|
+
import { endRun, LiveDoc } from "./live.js";
|
|
13
|
+
import { planSystemEntries, renderSections, replaySections } from "./prompt.js";
|
|
14
|
+
import { ensureProviderSessionId } from "./provider.js";
|
|
15
|
+
import { createGeneration, generationTaskReference, handOver, startRun } from "./run.js";
|
|
16
|
+
import { appendToolResult, harnessError, ToolTask } from "./tool.js";
|
|
17
|
+
const DEFAULT_POLL_AFTER_MS = 5000;
|
|
18
|
+
/**
|
|
19
|
+
* Built-in generation task: prepares the positional system prompt and tool loadout, requests or polls the model,
|
|
20
|
+
* retries, and classifies the response. The run's inputs live in `nyan.live.run`.
|
|
21
|
+
*/
|
|
22
|
+
export const GenerationTask = defineTask({
|
|
23
|
+
name: generationTaskReference.definition.name,
|
|
24
|
+
version: generationTaskReference.definition.version,
|
|
25
|
+
initial: generationTaskReference.definition.initial,
|
|
26
|
+
phases: {
|
|
27
|
+
/**
|
|
28
|
+
* Render the system prompt and tool loadout and append the positional `nyan.system` entries they need, then move to
|
|
29
|
+
* `request`. The agent and settings resolved here are fixed for this request. Only the Harness writes to a busy
|
|
30
|
+
* conversation, so the transcript read here is still the tail at the commit.
|
|
31
|
+
*/
|
|
32
|
+
prepare: async (task, runtime, context) => {
|
|
33
|
+
const { conversationId } = runtime;
|
|
34
|
+
const agent = await runtime.agent(context);
|
|
35
|
+
const settings = runtime.settings;
|
|
36
|
+
const { model, thinkingLevel } = agent;
|
|
37
|
+
const resolved = model === undefined ? undefined : runtime.models.getModel(model.provider, model.modelId);
|
|
38
|
+
if (model === undefined || resolved === undefined)
|
|
39
|
+
return failNoModel(runtime, model, context);
|
|
40
|
+
const { attempt, compacted, overflow } = task.state.checkpoint;
|
|
41
|
+
if (compacted !== undefined && overflow !== undefined) {
|
|
42
|
+
const [outcome] = await runtime.outcomes([compacted], context);
|
|
43
|
+
if (outcome?.status !== "completed" || outcome.result.entryId === undefined) {
|
|
44
|
+
return failModelError(runtime, overflow, context);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const view = await runtime.context(conversationId, context);
|
|
48
|
+
const shown = replaySections(view.messages);
|
|
49
|
+
const report = (error) => runtime.report(error);
|
|
50
|
+
let env;
|
|
51
|
+
try {
|
|
52
|
+
env = await runtime.env(context);
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (context.abortSignal?.aborted)
|
|
56
|
+
throw error;
|
|
57
|
+
report(error);
|
|
58
|
+
}
|
|
59
|
+
const input = { conversationId, agent, env, shown: Object.fromEntries(shown), read: runtime };
|
|
60
|
+
const desired = await renderSections(agent.sections, input, shown, report, context);
|
|
61
|
+
const entries = planSystemEntries(view, desired, agent.tools, runtime.now());
|
|
62
|
+
const threshold = compacted === undefined
|
|
63
|
+
? thresholdCompaction(view, entries, resolved.contextWindow, settings.compaction)
|
|
64
|
+
: undefined;
|
|
65
|
+
if (threshold === "blocking") {
|
|
66
|
+
// Compact first and prepare again; the transcript is unchanged until the compaction appends.
|
|
67
|
+
await runtime.commit(async (tx) => {
|
|
68
|
+
const child = await createCompaction(tx, conversationId, { reason: "threshold" }, runtime.taskId);
|
|
69
|
+
const checkpoint = { phase: "prepare", attempt, compacted: child };
|
|
70
|
+
return { status: "waiting", checkpoint, on: [child], policy: "allSettled" };
|
|
71
|
+
}, context);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
await runtime.commit(async (tx) => {
|
|
75
|
+
let cutoff = (await tx.scanEntries({ conversationId }, 1)).items[0]?.id;
|
|
76
|
+
for (const entry of entries)
|
|
77
|
+
cutoff = (await tx.appendEntry(SystemEntry, conversationId, entry)).id;
|
|
78
|
+
if (cutoff === undefined)
|
|
79
|
+
throw new Error(`Conversation ${conversationId} has no entries to send`);
|
|
80
|
+
// Checked in this commit, so a compaction admitted during preparation counts.
|
|
81
|
+
if (threshold === "background" && (await tx.doc(LiveDoc, conversationId)).compactions === undefined) {
|
|
82
|
+
await createCompaction(tx, conversationId, { reason: "threshold" });
|
|
83
|
+
}
|
|
84
|
+
const request = {
|
|
85
|
+
attempt,
|
|
86
|
+
...(compacted === undefined ? {} : { compacted }),
|
|
87
|
+
model,
|
|
88
|
+
thinkingLevel,
|
|
89
|
+
streamOptions: settings.stream,
|
|
90
|
+
cutoff,
|
|
91
|
+
};
|
|
92
|
+
return { status: "running", checkpoint: { phase: "request", ...request } };
|
|
93
|
+
}, context);
|
|
94
|
+
},
|
|
95
|
+
request: async (task, runtime, context) => {
|
|
96
|
+
const { attempt, compacted, model: ref, thinkingLevel, streamOptions, cutoff } = task.state.checkpoint;
|
|
97
|
+
const conversationId = runtime.conversationId;
|
|
98
|
+
await runtime.commit(async (tx) => {
|
|
99
|
+
const live = await tx.doc(LiveDoc, conversationId);
|
|
100
|
+
await convertPartial(tx, live, conversationId);
|
|
101
|
+
live.generation = { attempt };
|
|
102
|
+
return undefined;
|
|
103
|
+
}, context);
|
|
104
|
+
const model = runtime.models.getModel(ref.provider, ref.modelId);
|
|
105
|
+
if (model === undefined)
|
|
106
|
+
return failNoModel(runtime, ref, context);
|
|
107
|
+
const view = await runtime.context(conversationId, context, { at: cutoff });
|
|
108
|
+
let messages = view.messages;
|
|
109
|
+
await runtime.hooks.each("beforeRequest", async (hook) => {
|
|
110
|
+
const replaced = await hook({ messages }, runtime, context);
|
|
111
|
+
if (replaced !== undefined)
|
|
112
|
+
messages = replaced.messages;
|
|
113
|
+
});
|
|
114
|
+
const options = {
|
|
115
|
+
...streamOptions,
|
|
116
|
+
signal: runtime.signal,
|
|
117
|
+
sessionId: await ensureProviderSessionId(runtime, context),
|
|
118
|
+
...(thinkingLevel === "off" ? {} : { reasoning: thinkingLevel }),
|
|
119
|
+
};
|
|
120
|
+
const message = await streamResponse(runtime, model, messages, options, attempt, context);
|
|
121
|
+
const request = { attempt, compacted, model: ref, cutoff, messages: view.messages };
|
|
122
|
+
await classify(runtime, request, message, context);
|
|
123
|
+
},
|
|
124
|
+
retry: async (task, runtime, context) => {
|
|
125
|
+
const { attempt, compacted, until } = task.state.checkpoint;
|
|
126
|
+
await runtime.sleep(until, context);
|
|
127
|
+
await runtime.commit(async (tx) => {
|
|
128
|
+
(await tx.doc(LiveDoc, runtime.conversationId)).generation = { attempt: attempt + 1 };
|
|
129
|
+
const checkpoint = {
|
|
130
|
+
phase: "prepare",
|
|
131
|
+
attempt: attempt + 1,
|
|
132
|
+
...(compacted === undefined ? {} : { compacted }),
|
|
133
|
+
};
|
|
134
|
+
return { status: "running", checkpoint };
|
|
135
|
+
}, context);
|
|
136
|
+
},
|
|
137
|
+
poll: async (task, runtime, context) => {
|
|
138
|
+
const { attempt, compacted, model: ref, cutoff, handle, pollAt } = task.state.checkpoint;
|
|
139
|
+
const model = runtime.models.getModel(ref.provider, ref.modelId);
|
|
140
|
+
if (model === undefined)
|
|
141
|
+
return failNoModel(runtime, ref, context);
|
|
142
|
+
await runtime.sleep(pollAt, context);
|
|
143
|
+
const message = await runtime.models.fetchDeferred(model, handle, { signal: runtime.signal });
|
|
144
|
+
const request = { attempt, compacted, model: ref, cutoff, pollAt };
|
|
145
|
+
await classify(runtime, request, message, context);
|
|
146
|
+
},
|
|
147
|
+
tools: async (task, runtime, context) => {
|
|
148
|
+
const { assistant, tools, pending } = task.state.checkpoint;
|
|
149
|
+
const [next, ...rest] = pending;
|
|
150
|
+
if (next === undefined)
|
|
151
|
+
return finishToolRound(runtime, assistant, tools, context);
|
|
152
|
+
// Sequential round: start the next call and wait for it.
|
|
153
|
+
await runtime.commit(async (tx) => {
|
|
154
|
+
const live = await tx.doc(LiveDoc, runtime.conversationId);
|
|
155
|
+
const taskId = await createToolTask(tx, runtime, assistant, next);
|
|
156
|
+
const slot = live.tools?.find((slot) => slot.callId === next && slot.taskId === undefined);
|
|
157
|
+
if (slot !== undefined)
|
|
158
|
+
slot.taskId = taskId;
|
|
159
|
+
const checkpoint = {
|
|
160
|
+
phase: "tools",
|
|
161
|
+
assistant,
|
|
162
|
+
tools: [...tools, taskId],
|
|
163
|
+
pending: rest,
|
|
164
|
+
};
|
|
165
|
+
return { status: "waiting", checkpoint, on: [taskId], policy: "allSettled" };
|
|
166
|
+
}, context);
|
|
167
|
+
},
|
|
168
|
+
},
|
|
169
|
+
abort: async (task, runtime, context) => {
|
|
170
|
+
const checkpoint = task.state.checkpoint;
|
|
171
|
+
if (checkpoint.phase === "poll") {
|
|
172
|
+
const model = runtime.models.getModel(checkpoint.model.provider, checkpoint.model.modelId);
|
|
173
|
+
if (model !== undefined) {
|
|
174
|
+
try {
|
|
175
|
+
await runtime.models.cancelDeferred(model, checkpoint.handle, { signal: runtime.signal });
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
runtime.report(error);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
const conversationId = runtime.conversationId;
|
|
183
|
+
// Runs after the round's tool tasks are terminal; calls never started get `aborted` results (spec §8.5).
|
|
184
|
+
const unstarted = checkpoint.phase === "tools"
|
|
185
|
+
? await readCalls(runtime, checkpoint.assistant, checkpoint.pending, context)
|
|
186
|
+
: [];
|
|
187
|
+
await runtime.commit(async (tx) => {
|
|
188
|
+
const live = await tx.doc(LiveDoc, conversationId);
|
|
189
|
+
await convertPartial(tx, live, conversationId);
|
|
190
|
+
for (const call of unstarted) {
|
|
191
|
+
const result = harnessError("aborted", `Tool ${call.name} was aborted`);
|
|
192
|
+
await appendToolResult(tx, conversationId, call, result, { timestamp: runtime.now() });
|
|
193
|
+
}
|
|
194
|
+
endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "aborted" });
|
|
195
|
+
return { status: "terminal", outcome: { status: "aborted" } };
|
|
196
|
+
}, context);
|
|
197
|
+
},
|
|
198
|
+
});
|
|
199
|
+
/** The calls `callIds` of the assistant entry, in the given order. */
|
|
200
|
+
async function readCalls(runtime, assistant, callIds, context) {
|
|
201
|
+
const message = (await runtime.entry(AssistantEntry, assistant, context))?.model?.[0];
|
|
202
|
+
const calls = message?.role === "assistant" ? message.content.filter((content) => content.type === "toolCall") : [];
|
|
203
|
+
return callIds.flatMap((id) => calls.filter((call) => call.id === id).slice(0, 1));
|
|
204
|
+
}
|
|
205
|
+
/** A tool task for call `callId`, owned by the generation. */
|
|
206
|
+
function createToolTask(tx, runtime, assistant, callId) {
|
|
207
|
+
return tx.createTask(ToolTask, { kind: "model", assistant, callId }, { ownership: { kind: "task", taskId: runtime.taskId } });
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Which threshold compaction preparation starts before its request (spec §8.3): `blocking` above
|
|
211
|
+
* `contextWindow - reserveTokens`, `background` above the background threshold, and only when range selection finds a
|
|
212
|
+
* cut. The caller starts a background one only while no compaction is listed.
|
|
213
|
+
*/
|
|
214
|
+
function thresholdCompaction(view, planned, contextWindow, policy) {
|
|
215
|
+
if (!policy.enabled || contextWindow <= 0)
|
|
216
|
+
return undefined;
|
|
217
|
+
const tokens = estimateContext(view, planned.flatMap((entry) => entry.model ?? []));
|
|
218
|
+
const blocking = contextWindow - policy.reserveTokens;
|
|
219
|
+
const background = blocking - policy.backgroundTokens;
|
|
220
|
+
const over = tokens > blocking ? "blocking" : policy.backgroundTokens > 0 && tokens > background ? "background" : undefined;
|
|
221
|
+
if (over === undefined || selectCut(view, policy.keepRecentTokens) === undefined)
|
|
222
|
+
return undefined;
|
|
223
|
+
return over;
|
|
224
|
+
}
|
|
225
|
+
/** Settle the run's inputs `unanswered` with `model_error` and fail with `text`. */
|
|
226
|
+
async function failModelError(runtime, text, context) {
|
|
227
|
+
await runtime.commit(async (tx) => {
|
|
228
|
+
const live = await tx.doc(LiveDoc, runtime.conversationId);
|
|
229
|
+
endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "model_error", detail: text });
|
|
230
|
+
return {
|
|
231
|
+
status: "terminal",
|
|
232
|
+
outcome: { status: "failed", error: { message: text, detail: { reason: "model_error" } } },
|
|
233
|
+
};
|
|
234
|
+
}, context);
|
|
235
|
+
}
|
|
236
|
+
/** Settle the run's inputs `unanswered` with `no_model` and fail. */
|
|
237
|
+
async function failNoModel(runtime, ref, context) {
|
|
238
|
+
const message = ref === undefined ? "No model is configured" : `Model ${ref.provider}/${ref.modelId} is not available`;
|
|
239
|
+
await runtime.commit(async (tx) => {
|
|
240
|
+
const live = await tx.doc(LiveDoc, runtime.conversationId);
|
|
241
|
+
endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "no_model" });
|
|
242
|
+
return { status: "terminal", outcome: { status: "failed", error: { message, detail: { reason: "no_model" } } } };
|
|
243
|
+
}, context);
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Stream one request and return the terminal message. Partials commit as trailing writes at most every
|
|
247
|
+
* `progress.partialIntervalMs` (default 100 ms) with one commit in flight; `finally` stops the throttle and awaits that
|
|
248
|
+
* commit, so no stale partial lands after the outcome.
|
|
249
|
+
*/
|
|
250
|
+
async function streamResponse(runtime, model, messages, options, attempt, context) {
|
|
251
|
+
const interval = runtime.settings.progress.partialIntervalMs;
|
|
252
|
+
let pending;
|
|
253
|
+
let timer;
|
|
254
|
+
let inFlight;
|
|
255
|
+
let stopped = false;
|
|
256
|
+
const flush = () => {
|
|
257
|
+
timer = undefined;
|
|
258
|
+
const partial = pending;
|
|
259
|
+
pending = undefined;
|
|
260
|
+
if (partial === undefined || stopped)
|
|
261
|
+
return;
|
|
262
|
+
inFlight = (async () => {
|
|
263
|
+
// Copy synchronously: the provider keeps mutating its partial.
|
|
264
|
+
const message = copyJson(partial, { omitUndefinedProperties: true });
|
|
265
|
+
await runtime.commit(async (tx) => {
|
|
266
|
+
const live = await tx.doc(LiveDoc, runtime.conversationId);
|
|
267
|
+
live.generation ??= { attempt };
|
|
268
|
+
assignJson(live.generation, "message", message);
|
|
269
|
+
return undefined;
|
|
270
|
+
}, context);
|
|
271
|
+
})()
|
|
272
|
+
.catch((error) => {
|
|
273
|
+
// Rejections after an abort mark or close are expected; the committed state stays consistent.
|
|
274
|
+
if (!runtime.signal.aborted)
|
|
275
|
+
runtime.report(error);
|
|
276
|
+
})
|
|
277
|
+
.finally(() => {
|
|
278
|
+
inFlight = undefined;
|
|
279
|
+
if (pending !== undefined && !stopped)
|
|
280
|
+
timer = setTimeout(flush, interval);
|
|
281
|
+
});
|
|
282
|
+
};
|
|
283
|
+
try {
|
|
284
|
+
const events = runtime.models.streamSimple(model, { messages: [...messages] }, options);
|
|
285
|
+
for await (const event of events) {
|
|
286
|
+
// A partial without content, such as nyan-ai's opening `start` event, shows nothing; a deferred response
|
|
287
|
+
// never gets past it, so it never leaves a partial.
|
|
288
|
+
if (event.type === "done" || event.type === "error" || event.partial.content.length === 0)
|
|
289
|
+
continue;
|
|
290
|
+
pending = event.partial;
|
|
291
|
+
if (timer === undefined && inFlight === undefined)
|
|
292
|
+
timer = setTimeout(flush, interval);
|
|
293
|
+
}
|
|
294
|
+
return await events.result();
|
|
295
|
+
}
|
|
296
|
+
finally {
|
|
297
|
+
stopped = true;
|
|
298
|
+
clearTimeout(timer);
|
|
299
|
+
await inFlight;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
/** Classify a terminal provider message in one commit that also clears the partial. */
|
|
303
|
+
async function classify(runtime, request, message, context) {
|
|
304
|
+
// An abort mark or close: the abort invocation or the reopened run handles the committed state.
|
|
305
|
+
runtime.signal.throwIfAborted();
|
|
306
|
+
const conversationId = runtime.conversationId;
|
|
307
|
+
const { attempt, compacted, model: ref, cutoff } = request;
|
|
308
|
+
if (message.stopReason === "deferred" && message.deferred !== undefined) {
|
|
309
|
+
const handle = message.deferred;
|
|
310
|
+
const pollAt = Math.max(runtime.now() + (handle.pollAfterMs ?? DEFAULT_POLL_AFTER_MS), request.pollAt === undefined ? Number.NEGATIVE_INFINITY : request.pollAt + 1);
|
|
311
|
+
await runtime.commit(async (tx) => {
|
|
312
|
+
(await tx.doc(LiveDoc, conversationId)).generation = { attempt, deferred: { pollAt } };
|
|
313
|
+
const checkpoint = {
|
|
314
|
+
phase: "poll",
|
|
315
|
+
attempt,
|
|
316
|
+
...(compacted === undefined ? {} : { compacted }),
|
|
317
|
+
model: ref,
|
|
318
|
+
cutoff,
|
|
319
|
+
handle,
|
|
320
|
+
pollAt,
|
|
321
|
+
};
|
|
322
|
+
return { status: "running", checkpoint };
|
|
323
|
+
}, context);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
await runtime.hooks.each("afterResponse", (hook) => hook(message, runtime, context));
|
|
327
|
+
const calls = message.content.filter((content) => content.type === "toolCall");
|
|
328
|
+
if (message.stopReason === "toolUse" && calls.length > 0) {
|
|
329
|
+
return startToolRound(runtime, request, message, calls, context);
|
|
330
|
+
}
|
|
331
|
+
if (message.stopReason === "stop" || message.stopReason === "length" || message.stopReason === "toolUse") {
|
|
332
|
+
return answer(runtime, message, context);
|
|
333
|
+
}
|
|
334
|
+
// The retry and compaction policies govern the next attempt, so they are read now rather than pinned at preparation.
|
|
335
|
+
const settings = runtime.settings;
|
|
336
|
+
const overflow = message.stopReason === "error" && isContextOverflow(message);
|
|
337
|
+
if (overflow && compacted === undefined && settings.compaction.enabled) {
|
|
338
|
+
const policy = settings.compaction;
|
|
339
|
+
const view = await runtime.context(conversationId, context, { at: cutoff });
|
|
340
|
+
if (selectCut(view, policy.keepRecentTokens) !== undefined) {
|
|
341
|
+
const text = message.errorMessage ?? "Context overflow";
|
|
342
|
+
await runtime.commit(async (tx) => {
|
|
343
|
+
const live = await tx.doc(LiveDoc, conversationId);
|
|
344
|
+
await appendAssistant(tx, conversationId, message);
|
|
345
|
+
delete live.generation;
|
|
346
|
+
const child = await createCompaction(tx, conversationId, { reason: "overflow" }, runtime.taskId);
|
|
347
|
+
const checkpoint = { phase: "prepare", attempt, compacted: child, overflow: text };
|
|
348
|
+
return { status: "waiting", checkpoint, on: [child], policy: "allSettled" };
|
|
349
|
+
}, context);
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
const policy = settings.retry;
|
|
354
|
+
// An overflow is never retried: only a compaction can make the next request fit.
|
|
355
|
+
const retry = message.stopReason === "error" &&
|
|
356
|
+
!overflow &&
|
|
357
|
+
isRetryableAssistantError(message) &&
|
|
358
|
+
policy.enabled &&
|
|
359
|
+
attempt <= policy.maxRetries;
|
|
360
|
+
const until = retry ? runtime.now() + retryDelayMs(policy, attempt) : 0;
|
|
361
|
+
await runtime.commit(async (tx) => {
|
|
362
|
+
const live = await tx.doc(LiveDoc, conversationId);
|
|
363
|
+
await appendAssistant(tx, conversationId, message);
|
|
364
|
+
if (retry) {
|
|
365
|
+
live.generation = { attempt, retry: { at: until, error: message.errorMessage ?? "" } };
|
|
366
|
+
const checkpoint = {
|
|
367
|
+
phase: "retry",
|
|
368
|
+
attempt,
|
|
369
|
+
...(compacted === undefined ? {} : { compacted }),
|
|
370
|
+
until,
|
|
371
|
+
};
|
|
372
|
+
return { status: "running", checkpoint };
|
|
373
|
+
}
|
|
374
|
+
const text = message.errorMessage ?? `Model response ended with stop reason ${message.stopReason}`;
|
|
375
|
+
endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "model_error", detail: text });
|
|
376
|
+
return {
|
|
377
|
+
status: "terminal",
|
|
378
|
+
outcome: { status: "failed", error: { message: text, detail: { reason: "model_error" } } },
|
|
379
|
+
};
|
|
380
|
+
}, context);
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* A final answer; the final boundary places queued items (spec §6). The first `onYield` continuation appends a user
|
|
384
|
+
* message and hands the run to a successor generation, but only when the boundary selected no user item and no reset.
|
|
385
|
+
* Otherwise the run's inputs settle `done`, and selected user items start the next run.
|
|
386
|
+
*/
|
|
387
|
+
async function answer(runtime, message, context) {
|
|
388
|
+
let continuation;
|
|
389
|
+
await runtime.hooks.each("onYield", async (hook) => {
|
|
390
|
+
if (continuation !== undefined)
|
|
391
|
+
return;
|
|
392
|
+
continuation = (await hook(message, runtime, context))?.continue;
|
|
393
|
+
});
|
|
394
|
+
const conversationId = runtime.conversationId;
|
|
395
|
+
await runtime.commit(async (tx) => {
|
|
396
|
+
// Queue modes are read on the Session line, when the boundary is decided.
|
|
397
|
+
const boundary = await prepareBoundary(tx, conversationId, runtime.settings);
|
|
398
|
+
const live = await tx.doc(LiveDoc, conversationId);
|
|
399
|
+
const entry = await appendAssistant(tx, conversationId, message);
|
|
400
|
+
const result = { status: "terminal", outcome: { status: "completed", result: { entryId: entry.id } } };
|
|
401
|
+
const { users, reset } = await applyBoundary(tx, boundary, "final", runtime.now());
|
|
402
|
+
if (continuation !== undefined && users.length === 0 && !reset) {
|
|
403
|
+
const user = { role: "user", content: continuation, timestamp: runtime.now() };
|
|
404
|
+
await tx.appendEntry(UserEntry, conversationId, { model: [user] });
|
|
405
|
+
handOver(live, runtime.taskId, await createGeneration(tx, conversationId));
|
|
406
|
+
delete live.generation;
|
|
407
|
+
return result;
|
|
408
|
+
}
|
|
409
|
+
endRun(tx, live, runtime.taskId, { status: "done", answer: entry.id });
|
|
410
|
+
if (users.length > 0)
|
|
411
|
+
await startRun(tx, conversationId, live, users);
|
|
412
|
+
return result;
|
|
413
|
+
}, context);
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Append the tool-calling answer and start its tool round in one commit (spec §8.3). A call to a tool the request did
|
|
417
|
+
* not offer gets its `tool_unavailable` result here; every other call gets a tool task owned by the generation, only the
|
|
418
|
+
* first one now when the round is sequential. The generation then waits for them in its `tools` phase, keeping the run.
|
|
419
|
+
*/
|
|
420
|
+
async function startToolRound(runtime, request, message, calls, context) {
|
|
421
|
+
const conversationId = runtime.conversationId;
|
|
422
|
+
const messages = request.messages ?? (await runtime.context(conversationId, context, { at: request.cutoff })).messages;
|
|
423
|
+
const offered = new Set(getCurrentTools(messages).map((tool) => tool.name));
|
|
424
|
+
// Read as the round starts; a tool is resolved as its tool task resolves it.
|
|
425
|
+
const tools = (await runtime.agent(context)).tools;
|
|
426
|
+
const sequential = runtime.settings.toolExecution === "sequential" ||
|
|
427
|
+
calls.some((call) => offered.has(call.name) && tools.find((tool) => tool.name === call.name)?.executionMode === "sequential");
|
|
428
|
+
await runtime.commit(async (tx) => {
|
|
429
|
+
const live = await tx.doc(LiveDoc, conversationId);
|
|
430
|
+
const entry = await appendAssistant(tx, conversationId, message);
|
|
431
|
+
const slots = [];
|
|
432
|
+
const tools = [];
|
|
433
|
+
const pending = [];
|
|
434
|
+
for (const call of calls) {
|
|
435
|
+
if (!offered.has(call.name)) {
|
|
436
|
+
const unavailable = harnessError("tool_unavailable", `Tool ${call.name} is not available`);
|
|
437
|
+
const result = await appendToolResult(tx, conversationId, call, unavailable, { timestamp: runtime.now() });
|
|
438
|
+
slots.push({ callId: call.id, name: call.name, status: "done", entry: result.id });
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
441
|
+
if (sequential && tools.length > 0) {
|
|
442
|
+
pending.push(call.id);
|
|
443
|
+
slots.push({ callId: call.id, name: call.name, status: "pending" });
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
const taskId = await createToolTask(tx, runtime, entry.id, call.id);
|
|
447
|
+
tools.push(taskId);
|
|
448
|
+
slots.push({ callId: call.id, name: call.name, taskId, status: "pending" });
|
|
449
|
+
}
|
|
450
|
+
delete live.generation;
|
|
451
|
+
live.tools = slots;
|
|
452
|
+
const checkpoint = { phase: "tools", assistant: entry.id, tools, pending };
|
|
453
|
+
return { status: "waiting", checkpoint, on: tools, policy: "allSettled" };
|
|
454
|
+
}, context);
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* The round's tools are terminal: apply their controls and either end the run at the final boundary (`terminate`,
|
|
458
|
+
* `handoff`, or a queued reset) or hand it to the next generation at the `postTools` boundary (spec §8.5).
|
|
459
|
+
*/
|
|
460
|
+
async function finishToolRound(runtime, assistant, tools, context) {
|
|
461
|
+
const conversationId = runtime.conversationId;
|
|
462
|
+
const controls = new Map();
|
|
463
|
+
const outcomes = await runtime.outcomes(tools, context);
|
|
464
|
+
tools.forEach((id, index) => {
|
|
465
|
+
const outcome = outcomes[index];
|
|
466
|
+
// Version 1 results have no kind; every result a generation's round reads is a model-issued call's.
|
|
467
|
+
controls.set(id, outcome.status === "completed" && outcome.result.kind !== "nested" ? outcome.result.control : undefined);
|
|
468
|
+
});
|
|
469
|
+
const slots = (await runtime.snapshot(LiveDoc, conversationId, context))?.tools ?? [];
|
|
470
|
+
const results = slots.flatMap((slot) => (slot.entry === undefined ? [] : [slot.entry]));
|
|
471
|
+
await runtime.hooks.each("afterTools", (hook) => hook(assistant, results, runtime, context));
|
|
472
|
+
// Every call of the round, including those answered without a task, must ask to terminate.
|
|
473
|
+
const terminate = slots.length > 0 &&
|
|
474
|
+
slots.every((slot) => slot.taskId !== undefined && controls.get(slot.taskId)?.terminate === true);
|
|
475
|
+
const added = [...controls.values()].flatMap((control) => control?.addTools ?? []);
|
|
476
|
+
// The last handoff in call order wins.
|
|
477
|
+
const handoff = [...controls.values()].findLast((control) => control?.handoff !== undefined)?.handoff;
|
|
478
|
+
await runtime.commit(async (tx) => {
|
|
479
|
+
const boundary = await prepareBoundary(tx, conversationId, runtime.settings);
|
|
480
|
+
if (added.length > 0)
|
|
481
|
+
await addTools(tx, conversationId, added);
|
|
482
|
+
const live = await tx.doc(LiveDoc, conversationId);
|
|
483
|
+
const now = runtime.now();
|
|
484
|
+
if (terminate || handoff !== undefined) {
|
|
485
|
+
if (handoff !== undefined) {
|
|
486
|
+
const message = { role: "user", content: handoff, timestamp: now };
|
|
487
|
+
const entry = await tx.appendEntry(ResetEntry, conversationId, { head: "self", model: [message] });
|
|
488
|
+
boundary.head = entry.id;
|
|
489
|
+
}
|
|
490
|
+
const { users } = await applyBoundary(tx, boundary, "final", now);
|
|
491
|
+
endRun(tx, live, runtime.taskId, { status: "done", answer: assistant });
|
|
492
|
+
if (users.length > 0)
|
|
493
|
+
await startRun(tx, conversationId, live, users);
|
|
494
|
+
}
|
|
495
|
+
else {
|
|
496
|
+
const { users, reset } = await applyBoundary(tx, boundary, "postTools", now);
|
|
497
|
+
if (reset) {
|
|
498
|
+
// The queued reset cut the run's context before an answer.
|
|
499
|
+
endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "reset" });
|
|
500
|
+
if (users.length > 0)
|
|
501
|
+
await startRun(tx, conversationId, live, users);
|
|
502
|
+
}
|
|
503
|
+
else {
|
|
504
|
+
delete live.tools;
|
|
505
|
+
delete live.nestedTools;
|
|
506
|
+
if (live.run?.taskId === runtime.taskId)
|
|
507
|
+
live.run.inputs.push(...users);
|
|
508
|
+
handOver(live, runtime.taskId, await createGeneration(tx, conversationId));
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
return { status: "terminal", outcome: { status: "completed", result: { entryId: assistant } } };
|
|
512
|
+
}, context);
|
|
513
|
+
}
|
|
514
|
+
//# sourceMappingURL=generation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generation.js","sourceRoot":"","sources":["../../src/harness/generation.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAgB,QAAQ,EAA8B,MAAM,aAAa,CAAC;AACjF,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAEnF,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAiB,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,cAAc,EAAE,MAA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AE,EAAE,EAAE,CAAC;IACjG,CAAC,EAAE,OAAO,CAAC,CAAC;AACb,CAAC","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tDeferredHandle,\n\tMessage,\n\tModel,\n\tModelThinkingLevel,\n\tSimpleStreamOptions,\n\tToolCall,\n} from \"@ny4n/ai/contracts\";\nimport { isContextOverflow } from \"@ny4n/ai/utils/overflow\";\nimport { isRetryableAssistantError, retryDelayMs } from \"@ny4n/ai/utils/retry\";\nimport { getCurrentTools } from \"@ny4n/ai/utils/transcript\";\nimport { type Context, copyJson, type Draft, type JsonValue } from \"@ny4n/chord\";\nimport { AssistantEntry, ResetEntry, SystemEntry, UserEntry } from \"../entries.ts\";\nimport type { ExecutionEnv } from \"../env/index.ts\";\nimport { defineTask } from \"../tasks.ts\";\nimport type { EntryId, NextTaskState, TaskId, TaskRuntime, Tx } from \"../types.ts\";\nimport { addTools } from \"./agent.ts\";\nimport { appendAssistant, convertPartial } from \"./assistant.ts\";\nimport { createCompaction, estimateContext, selectCut } from \"./compaction.ts\";\nimport { applyBoundary, prepareBoundary } from \"./inbox.ts\";\nimport { assignJson } from \"./json.ts\";\nimport { endRun, LiveDoc, type ToolSlot } from \"./live.ts\";\nimport { planSystemEntries, renderSections, replaySections } from \"./prompt.ts\";\nimport { ensureProviderSessionId } from \"./provider.ts\";\nimport { createGeneration, generationTaskReference, handOver, startRun } from \"./run.ts\";\nimport { appendToolResult, harnessError, ToolTask, type ToolTaskResult } from \"./tool.ts\";\nimport type {\n\tCompactionPolicy,\n\tCompactionResult,\n\tContextView,\n\tConversationStreamOptions,\n\tGenerationHooks,\n\tModelRef,\n\tPromptInput,\n\tToolControl,\n\tUserInput,\n} from \"./types.ts\";\n\nexport type GenerationInput = Record<string, never>;\n\nexport type GenerationCheckpoint =\n\t| {\n\t\t\tphase: \"prepare\";\n\t\t\tattempt: number;\n\t\t\t/** The blocking compaction this generation waited for; it starts no other compaction (spec §8.3). */\n\t\t\tcompacted?: TaskId<CompactionResult>;\n\t\t\t/** Error text of the overflow that started `compacted`; checked once when `prepare` resumes. */\n\t\t\toverflow?: string;\n\t }\n\t| {\n\t\t\tphase: \"request\";\n\t\t\tattempt: number;\n\t\t\tcompacted?: TaskId<CompactionResult>;\n\t\t\tmodel: ModelRef;\n\t\t\tthinkingLevel: ModelThinkingLevel;\n\t\t\t/** The settings' request options when preparation committed; a resend after recovery uses them unchanged. */\n\t\t\tstreamOptions: ConversationStreamOptions;\n\t\t\t/** Newest entry included in the request. */\n\t\t\tcutoff: EntryId;\n\t }\n\t| { phase: \"retry\"; attempt: number; compacted?: TaskId<CompactionResult>; until: number }\n\t| {\n\t\t\tphase: \"poll\";\n\t\t\tattempt: number;\n\t\t\tcompacted?: TaskId<CompactionResult>;\n\t\t\tmodel: ModelRef;\n\t\t\tcutoff: EntryId;\n\t\t\thandle: DeferredHandle;\n\t\t\tpollAt: number;\n\t }\n\t| {\n\t\t\t/** Waiting on the round's tool tasks, which the generation owns (spec §8.5). */\n\t\t\tphase: \"tools\";\n\t\t\t/** The tool-calling answer. */\n\t\t\tassistant: EntryId;\n\t\t\t/** Tool tasks created so far, in call order; grows by one per started call of a sequential round. */\n\t\t\ttools: TaskId<ToolTaskResult>[];\n\t\t\t/** Calls of a sequential round not started yet, in call order. */\n\t\t\tpending: string[];\n\t };\n\nexport type GenerationResult = { entryId: EntryId };\n\ntype Runtime = TaskRuntime<GenerationInput, GenerationCheckpoint, GenerationResult, GenerationHooks>;\ntype Next = NextTaskState<GenerationCheckpoint, GenerationResult>;\n\n/** What classification needs from the request that produced a message. */\ntype Request = {\n\treadonly attempt: number;\n\treadonly compacted: TaskId<CompactionResult> | undefined;\n\treadonly model: ModelRef;\n\treadonly cutoff: EntryId;\n\t/** Committed model context through `cutoff`, when the phase already derived it. */\n\treadonly messages?: readonly Message[];\n\t/** Set when the message came from polling, so a still deferred result polls strictly later. */\n\treadonly pollAt?: number;\n};\n\nconst DEFAULT_POLL_AFTER_MS = 5000;\n\n/**\n * Built-in generation task: prepares the positional system prompt and tool loadout, requests or polls the model,\n * retries, and classifies the response. The run's inputs live in `nyan.live.run`.\n */\nexport const GenerationTask = defineTask<GenerationInput, GenerationCheckpoint, GenerationResult, GenerationHooks>({\n\tname: generationTaskReference.definition.name,\n\tversion: generationTaskReference.definition.version,\n\tinitial: generationTaskReference.definition.initial,\n\tphases: {\n\t\t/**\n\t\t * Render the system prompt and tool loadout and append the positional `nyan.system` entries they need, then move to\n\t\t * `request`. The agent and settings resolved here are fixed for this request. Only the Harness writes to a busy\n\t\t * conversation, so the transcript read here is still the tail at the commit.\n\t\t */\n\t\tprepare: async (task, runtime, context) => {\n\t\t\tconst { conversationId } = runtime;\n\t\t\tconst agent = await runtime.agent(context);\n\t\t\tconst settings = runtime.settings;\n\t\t\tconst { model, thinkingLevel } = agent;\n\t\t\tconst resolved = model === undefined ? undefined : runtime.models.getModel(model.provider, model.modelId);\n\t\t\tif (model === undefined || resolved === undefined) return failNoModel(runtime, model, context);\n\t\t\tconst { attempt, compacted, overflow } = task.state.checkpoint;\n\t\t\tif (compacted !== undefined && overflow !== undefined) {\n\t\t\t\tconst [outcome] = await runtime.outcomes([compacted], context);\n\t\t\t\tif (outcome?.status !== \"completed\" || outcome.result.entryId === undefined) {\n\t\t\t\t\treturn failModelError(runtime, overflow, context);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst view = await runtime.context(conversationId, context);\n\t\t\tconst shown = replaySections(view.messages);\n\t\t\tconst report = (error: unknown) => runtime.report(error);\n\t\t\tlet env: ExecutionEnv | undefined;\n\t\t\ttry {\n\t\t\t\tenv = await runtime.env(context);\n\t\t\t} catch (error) {\n\t\t\t\tif (context.abortSignal?.aborted) throw error;\n\t\t\t\treport(error);\n\t\t\t}\n\t\t\tconst input: PromptInput = { conversationId, agent, env, shown: Object.fromEntries(shown), read: runtime };\n\t\t\tconst desired = await renderSections(agent.sections, input, shown, report, context);\n\t\t\tconst entries = planSystemEntries(view, desired, agent.tools, runtime.now());\n\t\t\tconst threshold =\n\t\t\t\tcompacted === undefined\n\t\t\t\t\t? thresholdCompaction(view, entries, resolved.contextWindow, settings.compaction)\n\t\t\t\t\t: undefined;\n\t\t\tif (threshold === \"blocking\") {\n\t\t\t\t// Compact first and prepare again; the transcript is unchanged until the compaction appends.\n\t\t\t\tawait runtime.commit(async (tx): Promise<Next> => {\n\t\t\t\t\tconst child = await createCompaction(tx, conversationId, { reason: \"threshold\" }, runtime.taskId);\n\t\t\t\t\tconst checkpoint = { phase: \"prepare\", attempt, compacted: child } as const;\n\t\t\t\t\treturn { status: \"waiting\", checkpoint, on: [child], policy: \"allSettled\" };\n\t\t\t\t}, context);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tlet cutoff = (await tx.scanEntries({ conversationId }, 1)).items[0]?.id;\n\t\t\t\tfor (const entry of entries) cutoff = (await tx.appendEntry(SystemEntry, conversationId, entry)).id;\n\t\t\t\tif (cutoff === undefined) throw new Error(`Conversation ${conversationId} has no entries to send`);\n\t\t\t\t// Checked in this commit, so a compaction admitted during preparation counts.\n\t\t\t\tif (threshold === \"background\" && (await tx.doc(LiveDoc, conversationId)).compactions === undefined) {\n\t\t\t\t\tawait createCompaction(tx, conversationId, { reason: \"threshold\" });\n\t\t\t\t}\n\t\t\t\tconst request = {\n\t\t\t\t\tattempt,\n\t\t\t\t\t...(compacted === undefined ? {} : { compacted }),\n\t\t\t\t\tmodel,\n\t\t\t\t\tthinkingLevel,\n\t\t\t\t\tstreamOptions: settings.stream,\n\t\t\t\t\tcutoff,\n\t\t\t\t};\n\t\t\t\treturn { status: \"running\", checkpoint: { phase: \"request\", ...request } };\n\t\t\t}, context);\n\t\t},\n\t\trequest: async (task, runtime, context) => {\n\t\t\tconst { attempt, compacted, model: ref, thinkingLevel, streamOptions, cutoff } = task.state.checkpoint;\n\t\t\tconst conversationId = runtime.conversationId;\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\t\t\tawait convertPartial(tx, live, conversationId);\n\t\t\t\tlive.generation = { attempt };\n\t\t\t\treturn undefined;\n\t\t\t}, context);\n\t\t\tconst model = runtime.models.getModel(ref.provider, ref.modelId);\n\t\t\tif (model === undefined) return failNoModel(runtime, ref, context);\n\t\t\tconst view = await runtime.context(conversationId, context, { at: cutoff });\n\t\t\tlet messages = view.messages;\n\t\t\tawait runtime.hooks.each(\"beforeRequest\", async (hook) => {\n\t\t\t\tconst replaced = await hook({ messages }, runtime, context);\n\t\t\t\tif (replaced !== undefined) messages = replaced.messages;\n\t\t\t});\n\t\t\tconst options: SimpleStreamOptions = {\n\t\t\t\t...streamOptions,\n\t\t\t\tsignal: runtime.signal,\n\t\t\t\tsessionId: await ensureProviderSessionId(runtime, context),\n\t\t\t\t...(thinkingLevel === \"off\" ? {} : { reasoning: thinkingLevel }),\n\t\t\t};\n\t\t\tconst message = await streamResponse(runtime, model, messages, options, attempt, context);\n\t\t\tconst request = { attempt, compacted, model: ref, cutoff, messages: view.messages };\n\t\t\tawait classify(runtime, request, message, context);\n\t\t},\n\t\tretry: async (task, runtime, context) => {\n\t\t\tconst { attempt, compacted, until } = task.state.checkpoint;\n\t\t\tawait runtime.sleep(until, context);\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\t(await tx.doc(LiveDoc, runtime.conversationId)).generation = { attempt: attempt + 1 };\n\t\t\t\tconst checkpoint: GenerationCheckpoint = {\n\t\t\t\t\tphase: \"prepare\",\n\t\t\t\t\tattempt: attempt + 1,\n\t\t\t\t\t...(compacted === undefined ? {} : { compacted }),\n\t\t\t\t};\n\t\t\t\treturn { status: \"running\", checkpoint };\n\t\t\t}, context);\n\t\t},\n\t\tpoll: async (task, runtime, context) => {\n\t\t\tconst { attempt, compacted, model: ref, cutoff, handle, pollAt } = task.state.checkpoint;\n\t\t\tconst model = runtime.models.getModel(ref.provider, ref.modelId);\n\t\t\tif (model === undefined) return failNoModel(runtime, ref, context);\n\t\t\tawait runtime.sleep(pollAt, context);\n\t\t\tconst message = await runtime.models.fetchDeferred(model, handle, { signal: runtime.signal });\n\t\t\tconst request = { attempt, compacted, model: ref, cutoff, pollAt };\n\t\t\tawait classify(runtime, request, message, context);\n\t\t},\n\t\ttools: async (task, runtime, context) => {\n\t\t\tconst { assistant, tools, pending } = task.state.checkpoint;\n\t\t\tconst [next, ...rest] = pending;\n\t\t\tif (next === undefined) return finishToolRound(runtime, assistant, tools, context);\n\t\t\t// Sequential round: start the next call and wait for it.\n\t\t\tawait runtime.commit(async (tx): Promise<Next> => {\n\t\t\t\tconst live = await tx.doc(LiveDoc, runtime.conversationId);\n\t\t\t\tconst taskId = await createToolTask(tx, runtime, assistant, next);\n\t\t\t\tconst slot = live.tools?.find((slot) => slot.callId === next && slot.taskId === undefined);\n\t\t\t\tif (slot !== undefined) slot.taskId = taskId;\n\t\t\t\tconst checkpoint: GenerationCheckpoint = {\n\t\t\t\t\tphase: \"tools\",\n\t\t\t\t\tassistant,\n\t\t\t\t\ttools: [...tools, taskId],\n\t\t\t\t\tpending: rest,\n\t\t\t\t};\n\t\t\t\treturn { status: \"waiting\", checkpoint, on: [taskId], policy: \"allSettled\" };\n\t\t\t}, context);\n\t\t},\n\t},\n\tabort: async (task, runtime, context) => {\n\t\tconst checkpoint = task.state.checkpoint;\n\t\tif (checkpoint.phase === \"poll\") {\n\t\t\tconst model = runtime.models.getModel(checkpoint.model.provider, checkpoint.model.modelId);\n\t\t\tif (model !== undefined) {\n\t\t\t\ttry {\n\t\t\t\t\tawait runtime.models.cancelDeferred(model, checkpoint.handle, { signal: runtime.signal });\n\t\t\t\t} catch (error) {\n\t\t\t\t\truntime.report(error);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst conversationId = runtime.conversationId;\n\t\t// Runs after the round's tool tasks are terminal; calls never started get `aborted` results (spec §8.5).\n\t\tconst unstarted =\n\t\t\tcheckpoint.phase === \"tools\"\n\t\t\t\t? await readCalls(runtime, checkpoint.assistant, checkpoint.pending, context)\n\t\t\t\t: [];\n\t\tawait runtime.commit(async (tx) => {\n\t\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\t\tawait convertPartial(tx, live, conversationId);\n\t\t\tfor (const call of unstarted) {\n\t\t\t\tconst result = harnessError(\"aborted\", `Tool ${call.name} was aborted`);\n\t\t\t\tawait appendToolResult(tx, conversationId, call, result, { timestamp: runtime.now() });\n\t\t\t}\n\t\t\tendRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"aborted\" });\n\t\t\treturn { status: \"terminal\", outcome: { status: \"aborted\" } };\n\t\t}, context);\n\t},\n});\n\n/** The calls `callIds` of the assistant entry, in the given order. */\nasync function readCalls(\n\truntime: Runtime,\n\tassistant: EntryId,\n\tcallIds: readonly string[],\n\tcontext: Context,\n): Promise<ToolCall[]> {\n\tconst message = (await runtime.entry(AssistantEntry, assistant, context))?.model?.[0];\n\tconst calls = message?.role === \"assistant\" ? message.content.filter((content) => content.type === \"toolCall\") : [];\n\treturn callIds.flatMap((id) => calls.filter((call) => call.id === id).slice(0, 1));\n}\n\n/** A tool task for call `callId`, owned by the generation. */\nfunction createToolTask(tx: Tx, runtime: Runtime, assistant: EntryId, callId: string): Promise<TaskId<ToolTaskResult>> {\n\treturn tx.createTask(\n\t\tToolTask,\n\t\t{ kind: \"model\", assistant, callId },\n\t\t{ ownership: { kind: \"task\", taskId: runtime.taskId } },\n\t);\n}\n\n/**\n * Which threshold compaction preparation starts before its request (spec §8.3): `blocking` above\n * `contextWindow - reserveTokens`, `background` above the background threshold, and only when range selection finds a\n * cut. The caller starts a background one only while no compaction is listed.\n */\nfunction thresholdCompaction(\n\tview: ContextView,\n\tplanned: readonly { readonly model?: readonly Message[] }[],\n\tcontextWindow: number,\n\tpolicy: CompactionPolicy,\n): \"blocking\" | \"background\" | undefined {\n\tif (!policy.enabled || contextWindow <= 0) return undefined;\n\tconst tokens = estimateContext(\n\t\tview,\n\t\tplanned.flatMap((entry) => entry.model ?? []),\n\t);\n\tconst blocking = contextWindow - policy.reserveTokens;\n\tconst background = blocking - policy.backgroundTokens;\n\tconst over =\n\t\ttokens > blocking ? \"blocking\" : policy.backgroundTokens > 0 && tokens > background ? \"background\" : undefined;\n\tif (over === undefined || selectCut(view, policy.keepRecentTokens) === undefined) return undefined;\n\treturn over;\n}\n\n/** Settle the run's inputs `unanswered` with `model_error` and fail with `text`. */\nasync function failModelError(runtime: Runtime, text: string, context: Context): Promise<void> {\n\tawait runtime.commit(async (tx) => {\n\t\tconst live = await tx.doc(LiveDoc, runtime.conversationId);\n\t\tendRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"model_error\", detail: text });\n\t\treturn {\n\t\t\tstatus: \"terminal\",\n\t\t\toutcome: { status: \"failed\", error: { message: text, detail: { reason: \"model_error\" } } },\n\t\t};\n\t}, context);\n}\n\n/** Settle the run's inputs `unanswered` with `no_model` and fail. */\nasync function failNoModel(runtime: Runtime, ref: ModelRef | undefined, context: Context): Promise<void> {\n\tconst message =\n\t\tref === undefined ? \"No model is configured\" : `Model ${ref.provider}/${ref.modelId} is not available`;\n\tawait runtime.commit(async (tx) => {\n\t\tconst live = await tx.doc(LiveDoc, runtime.conversationId);\n\t\tendRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"no_model\" });\n\t\treturn { status: \"terminal\", outcome: { status: \"failed\", error: { message, detail: { reason: \"no_model\" } } } };\n\t}, context);\n}\n\n/**\n * Stream one request and return the terminal message. Partials commit as trailing writes at most every\n * `progress.partialIntervalMs` (default 100 ms) with one commit in flight; `finally` stops the throttle and awaits that\n * commit, so no stale partial lands after the outcome.\n */\nasync function streamResponse(\n\truntime: Runtime,\n\tmodel: Model<Api>,\n\tmessages: readonly Message[],\n\toptions: SimpleStreamOptions,\n\tattempt: number,\n\tcontext: Context,\n): Promise<AssistantMessage> {\n\tconst interval = runtime.settings.progress.partialIntervalMs;\n\tlet pending: AssistantMessage | undefined;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet inFlight: Promise<void> | undefined;\n\tlet stopped = false;\n\tconst flush = (): void => {\n\t\ttimer = undefined;\n\t\tconst partial = pending;\n\t\tpending = undefined;\n\t\tif (partial === undefined || stopped) return;\n\t\tinFlight = (async () => {\n\t\t\t// Copy synchronously: the provider keeps mutating its partial.\n\t\t\tconst message = copyJson(partial, { omitUndefinedProperties: true });\n\t\t\tawait runtime.commit(async (tx) => {\n\t\t\t\tconst live = await tx.doc(LiveDoc, runtime.conversationId);\n\t\t\t\tlive.generation ??= { attempt };\n\t\t\t\tassignJson(live.generation as Draft<Record<string, JsonValue>>, \"message\", message);\n\t\t\t\treturn undefined;\n\t\t\t}, context);\n\t\t})()\n\t\t\t.catch((error: unknown) => {\n\t\t\t\t// Rejections after an abort mark or close are expected; the committed state stays consistent.\n\t\t\t\tif (!runtime.signal.aborted) runtime.report(error);\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tinFlight = undefined;\n\t\t\t\tif (pending !== undefined && !stopped) timer = setTimeout(flush, interval);\n\t\t\t});\n\t};\n\ttry {\n\t\tconst events = runtime.models.streamSimple(model, { messages: [...messages] }, options);\n\t\tfor await (const event of events) {\n\t\t\t// A partial without content, such as nyan-ai's opening `start` event, shows nothing; a deferred response\n\t\t\t// never gets past it, so it never leaves a partial.\n\t\t\tif (event.type === \"done\" || event.type === \"error\" || event.partial.content.length === 0) continue;\n\t\t\tpending = event.partial;\n\t\t\tif (timer === undefined && inFlight === undefined) timer = setTimeout(flush, interval);\n\t\t}\n\t\treturn await events.result();\n\t} finally {\n\t\tstopped = true;\n\t\tclearTimeout(timer);\n\t\tawait inFlight;\n\t}\n}\n\n/** Classify a terminal provider message in one commit that also clears the partial. */\nasync function classify(\n\truntime: Runtime,\n\trequest: Request,\n\tmessage: AssistantMessage,\n\tcontext: Context,\n): Promise<void> {\n\t// An abort mark or close: the abort invocation or the reopened run handles the committed state.\n\truntime.signal.throwIfAborted();\n\tconst conversationId = runtime.conversationId;\n\tconst { attempt, compacted, model: ref, cutoff } = request;\n\tif (message.stopReason === \"deferred\" && message.deferred !== undefined) {\n\t\tconst handle = message.deferred;\n\t\tconst pollAt = Math.max(\n\t\t\truntime.now() + (handle.pollAfterMs ?? DEFAULT_POLL_AFTER_MS),\n\t\t\trequest.pollAt === undefined ? Number.NEGATIVE_INFINITY : request.pollAt + 1,\n\t\t);\n\t\tawait runtime.commit(async (tx) => {\n\t\t\t(await tx.doc(LiveDoc, conversationId)).generation = { attempt, deferred: { pollAt } };\n\t\t\tconst checkpoint = {\n\t\t\t\tphase: \"poll\",\n\t\t\t\tattempt,\n\t\t\t\t...(compacted === undefined ? {} : { compacted }),\n\t\t\t\tmodel: ref,\n\t\t\t\tcutoff,\n\t\t\t\thandle,\n\t\t\t\tpollAt,\n\t\t\t} as const;\n\t\t\treturn { status: \"running\", checkpoint };\n\t\t}, context);\n\t\treturn;\n\t}\n\tawait runtime.hooks.each(\"afterResponse\", (hook) => hook(message, runtime, context));\n\tconst calls = message.content.filter((content): content is ToolCall => content.type === \"toolCall\");\n\tif (message.stopReason === \"toolUse\" && calls.length > 0) {\n\t\treturn startToolRound(runtime, request, message, calls, context);\n\t}\n\tif (message.stopReason === \"stop\" || message.stopReason === \"length\" || message.stopReason === \"toolUse\") {\n\t\treturn answer(runtime, message, context);\n\t}\n\t// The retry and compaction policies govern the next attempt, so they are read now rather than pinned at preparation.\n\tconst settings = runtime.settings;\n\tconst overflow = message.stopReason === \"error\" && isContextOverflow(message);\n\tif (overflow && compacted === undefined && settings.compaction.enabled) {\n\t\tconst policy = settings.compaction;\n\t\tconst view = await runtime.context(conversationId, context, { at: cutoff });\n\t\tif (selectCut(view, policy.keepRecentTokens) !== undefined) {\n\t\t\tconst text = message.errorMessage ?? \"Context overflow\";\n\t\t\tawait runtime.commit(async (tx): Promise<Next> => {\n\t\t\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\t\t\tawait appendAssistant(tx, conversationId, message);\n\t\t\t\tdelete live.generation;\n\t\t\t\tconst child = await createCompaction(tx, conversationId, { reason: \"overflow\" }, runtime.taskId);\n\t\t\t\tconst checkpoint = { phase: \"prepare\", attempt, compacted: child, overflow: text } as const;\n\t\t\t\treturn { status: \"waiting\", checkpoint, on: [child], policy: \"allSettled\" };\n\t\t\t}, context);\n\t\t\treturn;\n\t\t}\n\t}\n\tconst policy = settings.retry;\n\t// An overflow is never retried: only a compaction can make the next request fit.\n\tconst retry =\n\t\tmessage.stopReason === \"error\" &&\n\t\t!overflow &&\n\t\tisRetryableAssistantError(message) &&\n\t\tpolicy.enabled &&\n\t\tattempt <= policy.maxRetries;\n\tconst until = retry ? runtime.now() + retryDelayMs(policy, attempt) : 0;\n\tawait runtime.commit(async (tx): Promise<Next> => {\n\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\tawait appendAssistant(tx, conversationId, message);\n\t\tif (retry) {\n\t\t\tlive.generation = { attempt, retry: { at: until, error: message.errorMessage ?? \"\" } };\n\t\t\tconst checkpoint = {\n\t\t\t\tphase: \"retry\",\n\t\t\t\tattempt,\n\t\t\t\t...(compacted === undefined ? {} : { compacted }),\n\t\t\t\tuntil,\n\t\t\t} as const;\n\t\t\treturn { status: \"running\", checkpoint };\n\t\t}\n\t\tconst text = message.errorMessage ?? `Model response ended with stop reason ${message.stopReason}`;\n\t\tendRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"model_error\", detail: text });\n\t\treturn {\n\t\t\tstatus: \"terminal\",\n\t\t\toutcome: { status: \"failed\", error: { message: text, detail: { reason: \"model_error\" } } },\n\t\t};\n\t}, context);\n}\n\n/**\n * A final answer; the final boundary places queued items (spec §6). The first `onYield` continuation appends a user\n * message and hands the run to a successor generation, but only when the boundary selected no user item and no reset.\n * Otherwise the run's inputs settle `done`, and selected user items start the next run.\n */\nasync function answer(runtime: Runtime, message: AssistantMessage, context: Context): Promise<void> {\n\tlet continuation: UserInput | undefined;\n\tawait runtime.hooks.each(\"onYield\", async (hook) => {\n\t\tif (continuation !== undefined) return;\n\t\tcontinuation = (await hook(message, runtime, context))?.continue;\n\t});\n\tconst conversationId = runtime.conversationId;\n\tawait runtime.commit(async (tx): Promise<Next> => {\n\t\t// Queue modes are read on the Session line, when the boundary is decided.\n\t\tconst boundary = await prepareBoundary(tx, conversationId, runtime.settings);\n\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\tconst entry = await appendAssistant(tx, conversationId, message);\n\t\tconst result: Next = { status: \"terminal\", outcome: { status: \"completed\", result: { entryId: entry.id } } };\n\t\tconst { users, reset } = await applyBoundary(tx, boundary, \"final\", runtime.now());\n\t\tif (continuation !== undefined && users.length === 0 && !reset) {\n\t\t\tconst user = { role: \"user\", content: continuation, timestamp: runtime.now() } as const;\n\t\t\tawait tx.appendEntry(UserEntry, conversationId, { model: [user] });\n\t\t\thandOver(live, runtime.taskId, await createGeneration(tx, conversationId));\n\t\t\tdelete live.generation;\n\t\t\treturn result;\n\t\t}\n\t\tendRun(tx, live, runtime.taskId, { status: \"done\", answer: entry.id });\n\t\tif (users.length > 0) await startRun(tx, conversationId, live, users);\n\t\treturn result;\n\t}, context);\n}\n\n/**\n * Append the tool-calling answer and start its tool round in one commit (spec §8.3). A call to a tool the request did\n * not offer gets its `tool_unavailable` result here; every other call gets a tool task owned by the generation, only the\n * first one now when the round is sequential. The generation then waits for them in its `tools` phase, keeping the run.\n */\nasync function startToolRound(\n\truntime: Runtime,\n\trequest: Request,\n\tmessage: AssistantMessage,\n\tcalls: readonly ToolCall[],\n\tcontext: Context,\n): Promise<void> {\n\tconst conversationId = runtime.conversationId;\n\tconst messages =\n\t\trequest.messages ?? (await runtime.context(conversationId, context, { at: request.cutoff })).messages;\n\tconst offered = new Set(getCurrentTools(messages).map((tool) => tool.name));\n\t// Read as the round starts; a tool is resolved as its tool task resolves it.\n\tconst tools = (await runtime.agent(context)).tools;\n\tconst sequential =\n\t\truntime.settings.toolExecution === \"sequential\" ||\n\t\tcalls.some(\n\t\t\t(call) =>\n\t\t\t\toffered.has(call.name) && tools.find((tool) => tool.name === call.name)?.executionMode === \"sequential\",\n\t\t);\n\tawait runtime.commit(async (tx): Promise<Next> => {\n\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\tconst entry = await appendAssistant(tx, conversationId, message);\n\t\tconst slots: ToolSlot[] = [];\n\t\tconst tools: TaskId<ToolTaskResult>[] = [];\n\t\tconst pending: string[] = [];\n\t\tfor (const call of calls) {\n\t\t\tif (!offered.has(call.name)) {\n\t\t\t\tconst unavailable = harnessError(\"tool_unavailable\", `Tool ${call.name} is not available`);\n\t\t\t\tconst result = await appendToolResult(tx, conversationId, call, unavailable, { timestamp: runtime.now() });\n\t\t\t\tslots.push({ callId: call.id, name: call.name, status: \"done\", entry: result.id });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (sequential && tools.length > 0) {\n\t\t\t\tpending.push(call.id);\n\t\t\t\tslots.push({ callId: call.id, name: call.name, status: \"pending\" });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst taskId = await createToolTask(tx, runtime, entry.id, call.id);\n\t\t\ttools.push(taskId);\n\t\t\tslots.push({ callId: call.id, name: call.name, taskId, status: \"pending\" });\n\t\t}\n\t\tdelete live.generation;\n\t\tlive.tools = slots;\n\t\tconst checkpoint = { phase: \"tools\", assistant: entry.id, tools, pending } as const;\n\t\treturn { status: \"waiting\", checkpoint, on: tools, policy: \"allSettled\" };\n\t}, context);\n}\n\n/**\n * The round's tools are terminal: apply their controls and either end the run at the final boundary (`terminate`,\n * `handoff`, or a queued reset) or hand it to the next generation at the `postTools` boundary (spec §8.5).\n */\nasync function finishToolRound(\n\truntime: Runtime,\n\tassistant: EntryId,\n\ttools: readonly TaskId<ToolTaskResult>[],\n\tcontext: Context,\n): Promise<void> {\n\tconst conversationId = runtime.conversationId;\n\tconst controls = new Map<TaskId, ToolControl | undefined>();\n\tconst outcomes = await runtime.outcomes(tools, context);\n\ttools.forEach((id, index) => {\n\t\tconst outcome = outcomes[index]!;\n\t\t// Version 1 results have no kind; every result a generation's round reads is a model-issued call's.\n\t\tcontrols.set(\n\t\t\tid,\n\t\t\toutcome.status === \"completed\" && outcome.result.kind !== \"nested\" ? outcome.result.control : undefined,\n\t\t);\n\t});\n\tconst slots = (await runtime.snapshot(LiveDoc, conversationId, context))?.tools ?? [];\n\tconst results = slots.flatMap((slot) => (slot.entry === undefined ? [] : [slot.entry]));\n\tawait runtime.hooks.each(\"afterTools\", (hook) => hook(assistant, results, runtime, context));\n\t// Every call of the round, including those answered without a task, must ask to terminate.\n\tconst terminate =\n\t\tslots.length > 0 &&\n\t\tslots.every((slot) => slot.taskId !== undefined && controls.get(slot.taskId)?.terminate === true);\n\tconst added = [...controls.values()].flatMap((control) => control?.addTools ?? []);\n\t// The last handoff in call order wins.\n\tconst handoff = [...controls.values()].findLast((control) => control?.handoff !== undefined)?.handoff;\n\tawait runtime.commit(async (tx): Promise<Next> => {\n\t\tconst boundary = await prepareBoundary(tx, conversationId, runtime.settings);\n\t\tif (added.length > 0) await addTools(tx, conversationId, added);\n\t\tconst live = await tx.doc(LiveDoc, conversationId);\n\t\tconst now = runtime.now();\n\t\tif (terminate || handoff !== undefined) {\n\t\t\tif (handoff !== undefined) {\n\t\t\t\tconst message = { role: \"user\", content: handoff, timestamp: now } as const;\n\t\t\t\tconst entry = await tx.appendEntry(ResetEntry, conversationId, { head: \"self\", model: [message] });\n\t\t\t\tboundary.head = entry.id;\n\t\t\t}\n\t\t\tconst { users } = await applyBoundary(tx, boundary, \"final\", now);\n\t\t\tendRun(tx, live, runtime.taskId, { status: \"done\", answer: assistant });\n\t\t\tif (users.length > 0) await startRun(tx, conversationId, live, users);\n\t\t} else {\n\t\t\tconst { users, reset } = await applyBoundary(tx, boundary, \"postTools\", now);\n\t\t\tif (reset) {\n\t\t\t\t// The queued reset cut the run's context before an answer.\n\t\t\t\tendRun(tx, live, runtime.taskId, { status: \"unanswered\", reason: \"reset\" });\n\t\t\t\tif (users.length > 0) await startRun(tx, conversationId, live, users);\n\t\t\t} else {\n\t\t\t\tdelete live.tools;\n\t\t\t\tdelete live.nestedTools;\n\t\t\t\tif (live.run?.taskId === runtime.taskId) live.run.inputs.push(...users);\n\t\t\t\thandOver(live, runtime.taskId, await createGeneration(tx, conversationId));\n\t\t\t}\n\t\t}\n\t\treturn { status: \"terminal\", outcome: { status: \"completed\", result: { entryId: assistant } } };\n\t}, context);\n}\n"]}
|