返回源码地图

packages/durable/src/harness/generation.ts

v1.3.0 · 71023aec1546 · 11:读取1–220及定位各阶段;部分流恢复另追专门测试,不声称全文审计

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import { type Context, copyJson, type Draft, type JsonValue } from "@earendil-works/chord";
2import type {
3 Api,
4 AssistantMessage,
5 DeferredHandle,
6 Message,
7 Model,
8 ModelThinkingLevel,
9 SimpleStreamOptions,
10 ToolCall,
11} from "@earendil-works/pi-ai";
12import { isContextOverflow } from "@earendil-works/pi-ai/utils/overflow";
13import { isRetryableAssistantError, retryDelayMs } from "@earendil-works/pi-ai/utils/retry";
14import { getCurrentTools } from "@earendil-works/pi-ai/utils/transcript";
15import { AssistantEntry, ResetEntry, SystemEntry, UserEntry } from "../entries.ts";
16import type { ExecutionEnv } from "../env/index.ts";
17import { defineTask } from "../tasks.ts";
18import type {
19 ConversationId,
20 EntryId,
21 NextTaskState,
22 SubmissionId,
23 TaskId,
24 TaskOutcome,
25 TaskRuntime,
26 Tx,
27 TypedEntry,
28} from "../types.ts";
29import { addTools } from "./agent.ts";
30import { createCompaction, estimateContext, selectCut } from "./compaction.ts";
31import { applyBoundary, prepareBoundary } from "./inbox.ts";
32import { assignJson } from "./json.ts";
33import { endRun, LiveDoc, type LiveState, type ToolSlot } from "./live.ts";
34import { planSystemEntries, renderSections, replaySections } from "./prompt.ts";
35import { ensureProviderSessionId } from "./provider.ts";
36import { appendToolResult, harnessError, ToolTask, type ToolTaskResult } from "./tool.ts";
37import type {
38 CompactionPolicy,
39 CompactionResult,
40 ContextView,
41 ConversationStreamOptions,
42 GenerationHooks,
43 ModelRef,
44 PromptInput,
45 ToolControl,
46 UserInput,
47} from "./types.ts";
48import { recordUsage } from "./usage.ts";
49
50export type GenerationInput = Record<string, never>;
51
52export type GenerationCheckpoint =
53 | {
54 phase: "prepare";
55 attempt: number;
56 /** The blocking compaction this generation waited for; it starts no other compaction (spec §8.3). */
57 compacted?: TaskId<CompactionResult>;
58 /** Error text of the overflow that started `compacted`; checked once when `prepare` resumes. */
59 overflow?: string;
60 /** Set when the blocking threshold started `compacted`; its outcome is checked once when `prepare` resumes. */
61 threshold?: true;
62 }
63 | {
64 phase: "request";
65 attempt: number;
66 compacted?: TaskId<CompactionResult>;
67 model: ModelRef;
68 thinkingLevel: ModelThinkingLevel;
69 /** The settings' request options when preparation committed; a resend after recovery uses them unchanged. */
70 streamOptions: ConversationStreamOptions;
71 /** Newest entry included in the request. */
72 cutoff: EntryId;
73 }
74 | { phase: "retry"; attempt: number; compacted?: TaskId<CompactionResult>; until: number }
75 | {
76 phase: "poll";
77 attempt: number;
78 compacted?: TaskId<CompactionResult>;
79 model: ModelRef;
80 cutoff: EntryId;
81 handle: DeferredHandle;
82 pollAt: number;
83 }
84 | {
85 /** Waiting on the round's tool tasks, which the generation owns (spec §8.5). */
86 phase: "tools";
87 /** The tool-calling answer. */
88 assistant: EntryId;
89 /** Tool tasks created so far, in call order; grows by one per started call of a sequential round. */
90 tools: TaskId<ToolTaskResult>[];
91 /** Calls of a sequential round not started yet, in call order. */
92 pending: string[];
93 };
94
95export type GenerationResult = { entryId: EntryId };
96
97type Runtime = TaskRuntime<GenerationInput, GenerationCheckpoint, GenerationResult, GenerationHooks>;
98type Next = NextTaskState<GenerationCheckpoint, GenerationResult>;
99
100/** What classification needs from the request that produced a message. */
101type Request = {
102 readonly attempt: number;
103 readonly compacted: TaskId<CompactionResult> | undefined;
104 readonly model: ModelRef;
105 readonly cutoff: EntryId;
106 /** Committed model context through `cutoff`, when the phase already derived it. */
107 readonly messages?: readonly Message[];
108 /** Set when the message came from polling, so a still deferred result polls strictly later. */
109 readonly pollAt?: number;
110};
111
112const DEFAULT_POLL_AFTER_MS = 5000;
113
114/**
115 * Built-in generation task: prepares the positional system prompt and tool loadout, requests or polls the model,
116 * retries, and classifies the response. The run's inputs live in `pi.live.run`.
117 */
118export const GenerationTask = defineTask<GenerationInput, GenerationCheckpoint, GenerationResult, GenerationHooks>({
119 name: "pi.generation",
120 version: 1,
121 initial: () => ({ phase: "prepare", attempt: 1 }),
122 phases: {
123 /**
124 * Render the system prompt and tool loadout and append the positional `pi.system` entries they need, then move to
125 * `request`. The agent and settings resolved here are fixed for this request. Only the Harness writes model
126 * context to a busy conversation, so the context read here is still current at the commit; display-only entries
127 * may land meanwhile.
128 */
129 prepare: async (task, runtime, context) => {
130 const { conversationId } = runtime;
131 const agent = await runtime.agent(context);
132 const settings = runtime.settings;
133 const { model, thinkingLevel } = agent;
134 const resolved = model === undefined ? undefined : runtime.models.getModel(model.provider, model.modelId);
135 if (model === undefined || resolved === undefined) return failNoModel(runtime, model, context);
136 const { attempt, compacted, overflow, threshold: blocked } = task.state.checkpoint;
137 if (compacted !== undefined && overflow !== undefined) {
138 const [outcome] = await runtime.outcomes([compacted], context);
139 if (outcome?.status !== "completed" || outcome.result.entryId === undefined) {
140 return failModelError(runtime, overflow, context);
141 }
142 }
143 // A threshold compaction that found nothing to compact or was declined leaves a request that may still fit. One
144 // that failed left a context it judged too large: sending it would at best leave no room for the answer.
145 if (compacted !== undefined && blocked === true) {
146 const [outcome] = await runtime.outcomes([compacted], context);
147 if (outcome !== undefined && outcome.status !== "completed") {
148 return failModelError(runtime, compactionFailure(outcome), context);
149 }
150 }
151 const view = await runtime.context(conversationId, context);
152 const shown = replaySections(view.messages);
153 const report = (error: unknown) => runtime.report(error);
154 let env: ExecutionEnv | undefined;
155 try {
156 env = await runtime.env(context);
157 } catch (error) {
158 if (context.abortSignal?.aborted) throw error;
159 report(error);
160 }
161 const input: PromptInput = { conversationId, agent, env, shown: Object.fromEntries(shown), read: runtime };
162 const desired = await renderSections(agent.sections, input, shown, report, context);
163 const entries = planSystemEntries(view, desired, agent.tools, runtime.now());
164 const threshold =
165 compacted === undefined
166 ? thresholdCompaction(view, entries, resolved.contextWindow, settings.compaction)
167 : undefined;
168 if (threshold === "blocking") {
169 // Compact first and prepare again; the transcript is unchanged until the compaction appends.
170 await runtime.commit(async (tx): Promise<Next> => {
171 const child = await createCompaction(tx, conversationId, { reason: "threshold" }, runtime.taskId);
172 const checkpoint = { phase: "prepare", attempt, compacted: child, threshold: true } as const;
173 return { status: "waiting", checkpoint, on: [child], policy: "allSettled" };
174 }, context);
175 return;
176 }
177 await runtime.commit(async (tx) => {
178 let cutoff = (await tx.scanEntries({ conversationId }, 1)).items[0]?.id;
179 for (const entry of entries) cutoff = (await tx.appendEntry(SystemEntry, conversationId, entry)).id;
180 if (cutoff === undefined) throw new Error(`Conversation ${conversationId} has no entries to send`);
181 // Checked in this commit, so a compaction admitted during preparation counts.
182 if (threshold === "background" && (await tx.doc(LiveDoc, conversationId)).compactions === undefined) {
183 await createCompaction(tx, conversationId, { reason: "threshold" });
184 }
185 const request = {
186 attempt,
187 ...(compacted === undefined ? {} : { compacted }),
188 model,
189 thinkingLevel,
190 streamOptions: settings.stream,
191 cutoff,
192 };
193 return { status: "running", checkpoint: { phase: "request", ...request } };
194 }, context);
195 },
196 request: async (task, runtime, context) => {
197 const { attempt, compacted, model: ref, thinkingLevel, streamOptions, cutoff } = task.state.checkpoint;
198 const conversationId = runtime.conversationId;
199 await runtime.commit(async (tx) => {
200 const live = await tx.doc(LiveDoc, conversationId);
201 await convertPartial(tx, live, conversationId);
202 live.generation = { attempt };
203 return undefined;
204 }, context);
205 const model = runtime.models.getModel(ref.provider, ref.modelId);
206 if (model === undefined) return failNoModel(runtime, ref, context);
207 const view = await runtime.context(conversationId, context, { at: cutoff });
208 let messages = view.messages;
209 await runtime.hooks.each("beforeRequest", async (hook) => {
210 const replaced = await hook({ messages }, runtime, context);
211 if (replaced !== undefined) messages = replaced.messages;
212 });
213 const options: SimpleStreamOptions = {
214 ...streamOptions,
215 signal: runtime.signal,
216 sessionId: await ensureProviderSessionId(runtime, context),
217 ...(thinkingLevel === "off" ? {} : { reasoning: thinkingLevel }),
218 };
219 const message = await streamResponse(runtime, model, messages, options, attempt, context);
220 const request = { attempt, compacted, model: ref, cutoff, messages: view.messages };
221 await classify(runtime, request, message, context);
222 },
223 retry: async (task, runtime, context) => {
224 const { attempt, compacted, until } = task.state.checkpoint;
225 await runtime.sleep(until, context);
226 await runtime.commit(async (tx) => {
227 (await tx.doc(LiveDoc, runtime.conversationId)).generation = { attempt: attempt + 1 };
228 const checkpoint: GenerationCheckpoint = {
229 phase: "prepare",
230 attempt: attempt + 1,
231 ...(compacted === undefined ? {} : { compacted }),
232 };
233 return { status: "running", checkpoint };
234 }, context);
235 },
236 poll: async (task, runtime, context) => {
237 const { attempt, compacted, model: ref, cutoff, handle, pollAt } = task.state.checkpoint;
238 const model = runtime.models.getModel(ref.provider, ref.modelId);
239 if (model === undefined) return failNoModel(runtime, ref, context);
240 await runtime.sleep(pollAt, context);
241 const message = await runtime.models.fetchDeferred(model, handle, { signal: runtime.signal });
242 const request = { attempt, compacted, model: ref, cutoff, pollAt };
243 await classify(runtime, request, message, context);
244 },
245 tools: async (task, runtime, context) => {
246 const { assistant, tools, pending } = task.state.checkpoint;
247 const [next, ...rest] = pending;
248 if (next === undefined) return finishToolRound(runtime, assistant, tools, context);
249 // Sequential round: start the next call and wait for it.
250 await runtime.commit(async (tx): Promise<Next> => {
251 const live = await tx.doc(LiveDoc, runtime.conversationId);
252 const taskId = await createToolTask(tx, runtime, assistant, next);
253 const slot = live.tools?.find((slot) => slot.callId === next && slot.taskId === undefined);
254 if (slot !== undefined) slot.taskId = taskId;
255 const checkpoint: GenerationCheckpoint = {
256 phase: "tools",
257 assistant,
258 tools: [...tools, taskId],
259 pending: rest,
260 };
261 return { status: "waiting", checkpoint, on: [taskId], policy: "allSettled" };
262 }, context);
263 },
264 },
265 abort: async (task, runtime, context) => {
266 const checkpoint = task.state.checkpoint;
267 if (checkpoint.phase === "poll") {
268 const model = runtime.models.getModel(checkpoint.model.provider, checkpoint.model.modelId);
269 if (model !== undefined) {
270 try {
271 await runtime.models.cancelDeferred(model, checkpoint.handle, { signal: runtime.signal });
272 } catch (error) {
273 runtime.report(error);
274 }
275 }
276 }
277 const conversationId = runtime.conversationId;
278 // Runs after the round's tool tasks are terminal; calls never started get `aborted` results (spec §8.5).
279 const unstarted =
280 checkpoint.phase === "tools"
281 ? await readCalls(runtime, checkpoint.assistant, checkpoint.pending, context)
282 : [];
283 await runtime.commit(async (tx) => {
284 const live = await tx.doc(LiveDoc, conversationId);
285 await convertPartial(tx, live, conversationId);
286 for (const call of unstarted) {
287 const result = harnessError("aborted", `Tool ${call.name} was aborted`);
288 await appendToolResult(tx, conversationId, call, result, { timestamp: runtime.now() });
289 }
290 endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "aborted" });
291 return { status: "terminal", outcome: { status: "aborted" } };
292 }, context);
293 },
294});
295
296/** The calls `callIds` of the assistant entry, in the given order. */
297async function readCalls(
298 runtime: Runtime,
299 assistant: EntryId,
300 callIds: readonly string[],
301 context: Context,
302): Promise<ToolCall[]> {
303 const message = (await runtime.entry(AssistantEntry, assistant, context))?.model?.[0];
304 const calls = message?.role === "assistant" ? message.content.filter((content) => content.type === "toolCall") : [];
305 return callIds.flatMap((id) => calls.filter((call) => call.id === id).slice(0, 1));
306}
307
308/** A tool task for call `callId`, owned by the generation. */
309function createToolTask(tx: Tx, runtime: Runtime, assistant: EntryId, callId: string): Promise<TaskId<ToolTaskResult>> {
310 return tx.createTask(
311 ToolTask,
312 { kind: "model", assistant, callId },
313 { ownership: { kind: "task", taskId: runtime.taskId } },
314 );
315}
316
317/**
318 * Which threshold compaction preparation starts before its request (spec §8.3): `blocking` above
319 * `contextWindow - reserveTokens`, `background` above the background threshold, and only when range selection finds a
320 * cut. The caller starts a background one only while no compaction is listed.
321 */
322function thresholdCompaction(
323 view: ContextView,
324 planned: readonly { readonly model?: readonly Message[] }[],
325 contextWindow: number,
326 policy: CompactionPolicy,
327): "blocking" | "background" | undefined {
328 if (!policy.enabled || contextWindow <= 0) return undefined;
329 const tokens = estimateContext(
330 view,
331 planned.flatMap((entry) => entry.model ?? []),
332 );
333 const blocking = contextWindow - policy.reserveTokens;
334 const background = blocking - policy.backgroundTokens;
335 const over =
336 tokens > blocking ? "blocking" : policy.backgroundTokens > 0 && tokens > background ? "background" : undefined;
337 if (over === undefined || selectCut(view, policy.keepRecentTokens) === undefined) return undefined;
338 return over;
339}
340
341/** Error text for a generation whose blocking compaction ended without completing. */
342function compactionFailure(outcome: Exclude<TaskOutcome<CompactionResult>, { status: "completed" }>): string {
343 switch (outcome.status) {
344 case "failed":
345 case "faulted":
346 return `Compaction failed: ${outcome.error.message}`;
347 case "orphaned":
348 return `Compaction failed: ${outcome.reason}`;
349 case "aborted":
350 return "Compaction was aborted";
351 }
352}
353
354/** Settle the run's inputs `unanswered` with `model_error` and fail with `text`. */
355async function failModelError(runtime: Runtime, text: string, context: Context): Promise<void> {
356 await runtime.commit(async (tx) => {
357 const live = await tx.doc(LiveDoc, runtime.conversationId);
358 endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "model_error", detail: text });
359 return {
360 status: "terminal",
361 outcome: { status: "failed", error: { message: text, detail: { reason: "model_error" } } },
362 };
363 }, context);
364}
365
366/** Settle the run's inputs `unanswered` with `no_model` and fail. */
367async function failNoModel(runtime: Runtime, ref: ModelRef | undefined, context: Context): Promise<void> {
368 const message =
369 ref === undefined ? "No model is configured" : `Model ${ref.provider}/${ref.modelId} is not available`;
370 await runtime.commit(async (tx) => {
371 const live = await tx.doc(LiveDoc, runtime.conversationId);
372 endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "no_model" });
373 return { status: "terminal", outcome: { status: "failed", error: { message, detail: { reason: "no_model" } } } };
374 }, context);
375}
376
377/**
378 * Append a committed partial left by an interrupted, aborted, faulted, or orphaned attempt as an aborted assistant
379 * entry; the caller replaces or removes `generation`.
380 */
381export async function convertPartial(tx: Tx, live: Draft<LiveState>, conversationId: ConversationId): Promise<void> {
382 const partial = live.generation?.message;
383 if (partial === undefined) return;
384 const message = copyJson(partial) as unknown as AssistantMessage;
385 await appendAssistant(tx, conversationId, { ...message, stopReason: "aborted" });
386}
387
388/**
389 * Stream one request and return the terminal message. Partials commit as trailing writes at most every
390 * `progress.partialIntervalMs` (default 100 ms) with one commit in flight; `finally` stops the throttle and awaits that
391 * commit, so no stale partial lands after the outcome.
392 */
393async function streamResponse(
394 runtime: Runtime,
395 model: Model<Api>,
396 messages: readonly Message[],
397 options: SimpleStreamOptions,
398 attempt: number,
399 context: Context,
400): Promise<AssistantMessage> {
401 const interval = runtime.settings.progress.partialIntervalMs;
402 let pending: AssistantMessage | undefined;
403 let timer: ReturnType<typeof setTimeout> | undefined;
404 let inFlight: Promise<void> | undefined;
405 let stopped = false;
406 const flush = (): void => {
407 timer = undefined;
408 const partial = pending;
409 pending = undefined;
410 if (partial === undefined || stopped) return;
411 inFlight = (async () => {
412 // Copy synchronously: the provider keeps mutating its partial.
413 const message = copyJson(partial, { omitUndefinedProperties: true });
414 await runtime.commit(async (tx) => {
415 const live = await tx.doc(LiveDoc, runtime.conversationId);
416 live.generation ??= { attempt };
417 assignJson(live.generation as Draft<Record<string, JsonValue>>, "message", message);
418 return undefined;
419 }, context);
420 })()
421 .catch((error: unknown) => {
422 // Rejections after an abort mark or close are expected; the committed state stays consistent.
423 if (!runtime.signal.aborted) runtime.report(error);
424 })
425 .finally(() => {
426 inFlight = undefined;
427 if (pending !== undefined && !stopped) timer = setTimeout(flush, interval);
428 });
429 };
430 try {
431 const events = runtime.models.streamSimple(model, { messages: [...messages] }, options);
432 for await (const event of events) {
433 // A partial without content, such as pi-ai's opening `start` event, shows nothing; a deferred response
434 // never gets past it, so it never leaves a partial.
435 if (event.type === "done" || event.type === "error" || event.partial.content.length === 0) continue;
436 pending = event.partial;
437 if (timer === undefined && inFlight === undefined) timer = setTimeout(flush, interval);
438 }
439 return await events.result();
440 } finally {
441 stopped = true;
442 clearTimeout(timer);
443 await inFlight;
444 }
445}
446
447/** Classify a terminal provider message in one commit that also clears the partial. */
448async function classify(
449 runtime: Runtime,
450 request: Request,
451 message: AssistantMessage,
452 context: Context,
453): Promise<void> {
454 // An abort mark or close: the abort invocation or the reopened run handles the committed state.
455 runtime.signal.throwIfAborted();
456 const conversationId = runtime.conversationId;
457 const { attempt, compacted, model: ref, cutoff } = request;
458 if (message.stopReason === "deferred" && message.deferred !== undefined) {
459 const handle = message.deferred;
460 const pollAt = Math.max(
461 runtime.now() + (handle.pollAfterMs ?? DEFAULT_POLL_AFTER_MS),
462 request.pollAt === undefined ? Number.NEGATIVE_INFINITY : request.pollAt + 1,
463 );
464 await runtime.commit(async (tx) => {
465 (await tx.doc(LiveDoc, conversationId)).generation = { attempt, deferred: { pollAt } };
466 const checkpoint = {
467 phase: "poll",
468 attempt,
469 ...(compacted === undefined ? {} : { compacted }),
470 model: ref,
471 cutoff,
472 handle,
473 pollAt,
474 } as const;
475 return { status: "running", checkpoint };
476 }, context);
477 return;
478 }
479 await runtime.hooks.each("afterResponse", (hook) => hook(message, runtime, context));
480 const calls = message.content.filter((content): content is ToolCall => content.type === "toolCall");
481 if (message.stopReason === "toolUse" && calls.length > 0) {
482 return startToolRound(runtime, request, message, calls, context);
483 }
484 if (message.stopReason === "stop" || message.stopReason === "length" || message.stopReason === "toolUse") {
485 return answer(runtime, message, context);
486 }
487 // The retry and compaction policies govern the next attempt, so they are read now rather than pinned at preparation.
488 const settings = runtime.settings;
489 const overflow = message.stopReason === "error" && isContextOverflow(message);
490 if (overflow && compacted === undefined && settings.compaction.enabled) {
491 const policy = settings.compaction;
492 const view = await runtime.context(conversationId, context, { at: cutoff });
493 if (selectCut(view, policy.keepRecentTokens) !== undefined) {
494 const text = message.errorMessage ?? "Context overflow";
495 await runtime.commit(async (tx): Promise<Next> => {
496 const live = await tx.doc(LiveDoc, conversationId);
497 await appendAssistant(tx, conversationId, message);
498 delete live.generation;
499 const child = await createCompaction(tx, conversationId, { reason: "overflow" }, runtime.taskId);
500 const checkpoint = { phase: "prepare", attempt, compacted: child, overflow: text } as const;
501 return { status: "waiting", checkpoint, on: [child], policy: "allSettled" };
502 }, context);
503 return;
504 }
505 }
506 const policy = settings.retry;
507 // An overflow is never retried: only a compaction can make the next request fit.
508 const retry =
509 message.stopReason === "error" &&
510 !overflow &&
511 isRetryableAssistantError(message) &&
512 policy.enabled &&
513 attempt <= policy.maxRetries;
514 const until = retry ? runtime.now() + retryDelayMs(policy, attempt) : 0;
515 await runtime.commit(async (tx): Promise<Next> => {
516 const live = await tx.doc(LiveDoc, conversationId);
517 await appendAssistant(tx, conversationId, message);
518 if (retry) {
519 live.generation = { attempt, retry: { at: until, error: message.errorMessage ?? "" } };
520 const checkpoint = {
521 phase: "retry",
522 attempt,
523 ...(compacted === undefined ? {} : { compacted }),
524 until,
525 } as const;
526 return { status: "running", checkpoint };
527 }
528 const text = message.errorMessage ?? `Model response ended with stop reason ${message.stopReason}`;
529 endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "model_error", detail: text });
530 return {
531 status: "terminal",
532 outcome: { status: "failed", error: { message: text, detail: { reason: "model_error" } } },
533 };
534 }, context);
535}
536
537/**
538 * A final answer; the final boundary places queued items (spec §6). The first `onYield` continuation appends a user
539 * message and hands the run to a successor generation, but only when the boundary selected no user item and no reset.
540 * Otherwise the run's inputs settle `done`, and selected user items start the next run.
541 */
542async function answer(runtime: Runtime, message: AssistantMessage, context: Context): Promise<void> {
543 let continuation: UserInput | undefined;
544 await runtime.hooks.each("onYield", async (hook) => {
545 if (continuation !== undefined) return;
546 continuation = (await hook(message, runtime, context))?.continue;
547 });
548 const conversationId = runtime.conversationId;
549 await runtime.commit(async (tx): Promise<Next> => {
550 // Queue modes are read on the Session line, when the boundary is decided.
551 const boundary = await prepareBoundary(tx, conversationId, runtime.settings);
552 const live = await tx.doc(LiveDoc, conversationId);
553 const entry = await appendAssistant(tx, conversationId, message);
554 const result: Next = { status: "terminal", outcome: { status: "completed", result: { entryId: entry.id } } };
555 const { users, reset } = await applyBoundary(tx, boundary, "final", runtime.now());
556 if (continuation !== undefined && users.length === 0 && !reset) {
557 const user = { role: "user", content: continuation, timestamp: runtime.now() } as const;
558 await tx.appendEntry(UserEntry, conversationId, { model: [user] });
559 handOver(live, runtime.taskId, await createGeneration(tx, conversationId));
560 delete live.generation;
561 return result;
562 }
563 endRun(tx, live, runtime.taskId, { status: "done", answer: entry.id });
564 if (users.length > 0) await startRun(tx, conversationId, live, users);
565 return result;
566 }, context);
567}
568
569/**
570 * Append the tool-calling answer and start its tool round in one commit (spec §8.3). A call to a tool the request did
571 * not offer gets its `tool_unavailable` result here; every other call gets a tool task owned by the generation, only the
572 * first one now when the round is sequential. The generation then waits for them in its `tools` phase, keeping the run.
573 */
574async function startToolRound(
575 runtime: Runtime,
576 request: Request,
577 message: AssistantMessage,
578 calls: readonly ToolCall[],
579 context: Context,
580): Promise<void> {
581 const conversationId = runtime.conversationId;
582 const messages =
583 request.messages ?? (await runtime.context(conversationId, context, { at: request.cutoff })).messages;
584 const offered = new Set(getCurrentTools(messages).map((tool) => tool.name));
585 // Read as the round starts; a tool is resolved as its tool task resolves it.
586 const tools = (await runtime.agent(context)).tools;
587 const sequential =
588 runtime.settings.toolExecution === "sequential" ||
589 calls.some(
590 (call) =>
591 offered.has(call.name) && tools.find((tool) => tool.name === call.name)?.executionMode === "sequential",
592 );
593 await runtime.commit(async (tx): Promise<Next> => {
594 const live = await tx.doc(LiveDoc, conversationId);
595 const entry = await appendAssistant(tx, conversationId, message);
596 const slots: ToolSlot[] = [];
597 const tools: TaskId<ToolTaskResult>[] = [];
598 const pending: string[] = [];
599 for (const call of calls) {
600 if (!offered.has(call.name)) {
601 const unavailable = harnessError("tool_unavailable", `Tool ${call.name} is not available`);
602 const result = await appendToolResult(tx, conversationId, call, unavailable, { timestamp: runtime.now() });
603 slots.push({ callId: call.id, name: call.name, status: "done", entry: result.id });
604 continue;
605 }
606 if (sequential && tools.length > 0) {
607 pending.push(call.id);
608 slots.push({ callId: call.id, name: call.name, status: "pending" });
609 continue;
610 }
611 const taskId = await createToolTask(tx, runtime, entry.id, call.id);
612 tools.push(taskId);
613 slots.push({ callId: call.id, name: call.name, taskId, status: "pending" });
614 }
615 delete live.generation;
616 live.tools = slots;
617 const checkpoint = { phase: "tools", assistant: entry.id, tools, pending } as const;
618 return { status: "waiting", checkpoint, on: tools, policy: "allSettled" };
619 }, context);
620}
621
622/**
623 * The round's tools are terminal: apply their controls and either end the run at the final boundary (`terminate`,
624 * `handoff`, or a queued reset) or hand it to the next generation at the `postTools` boundary (spec §8.5).
625 */
626async function finishToolRound(
627 runtime: Runtime,
628 assistant: EntryId,
629 tools: readonly TaskId<ToolTaskResult>[],
630 context: Context,
631): Promise<void> {
632 const conversationId = runtime.conversationId;
633 const controls = new Map<TaskId, ToolControl | undefined>();
634 const outcomes = await runtime.outcomes(tools, context);
635 tools.forEach((id, index) => {
636 const outcome = outcomes[index]!;
637 // Version 1 results have no kind; every result a generation's round reads is a model-issued call's.
638 controls.set(
639 id,
640 outcome.status === "completed" && outcome.result.kind !== "nested" ? outcome.result.control : undefined,
641 );
642 });
643 const slots = (await runtime.snapshot(LiveDoc, conversationId, context))?.tools ?? [];
644 const results = slots.flatMap((slot) => (slot.entry === undefined ? [] : [slot.entry]));
645 await runtime.hooks.each("afterTools", (hook) => hook(assistant, results, runtime, context));
646 // Every call of the round, including those answered without a task, must ask to terminate.
647 const terminate =
648 slots.length > 0 &&
649 slots.every((slot) => slot.taskId !== undefined && controls.get(slot.taskId)?.terminate === true);
650 const added = [...controls.values()].flatMap((control) => control?.addTools ?? []);
651 // The last handoff in call order wins.
652 const handoff = [...controls.values()].findLast((control) => control?.handoff !== undefined)?.handoff;
653 await runtime.commit(async (tx): Promise<Next> => {
654 const boundary = await prepareBoundary(tx, conversationId, runtime.settings);
655 if (added.length > 0) await addTools(tx, conversationId, added);
656 const live = await tx.doc(LiveDoc, conversationId);
657 const now = runtime.now();
658 if (terminate || handoff !== undefined) {
659 if (handoff !== undefined) {
660 const message = { role: "user", content: handoff, timestamp: now } as const;
661 const entry = await tx.appendEntry(ResetEntry, conversationId, { head: "self", model: [message] });
662 boundary.head = entry.id;
663 }
664 const { users } = await applyBoundary(tx, boundary, "final", now);
665 endRun(tx, live, runtime.taskId, { status: "done", answer: assistant });
666 if (users.length > 0) await startRun(tx, conversationId, live, users);
667 } else {
668 const { users, reset } = await applyBoundary(tx, boundary, "postTools", now);
669 if (reset) {
670 // The queued reset cut the run's context before an answer.
671 endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "reset" });
672 if (users.length > 0) await startRun(tx, conversationId, live, users);
673 } else {
674 delete live.tools;
675 delete live.nestedTools;
676 if (live.run?.taskId === runtime.taskId) live.run.inputs.push(...users);
677 handOver(live, runtime.taskId, await createGeneration(tx, conversationId));
678 }
679 }
680 return { status: "terminal", outcome: { status: "completed", result: { entryId: assistant } } };
681 }, context);
682}
683
684/**
685 * Append a provider result and add its usage to `pi.usage` in the same commit.
686 * REMINDER: every built-in writer of assistant entries goes through here, so the usage ledger stays complete.
687 */
688async function appendAssistant(
689 tx: Tx,
690 conversationId: ConversationId,
691 message: AssistantMessage,
692): Promise<TypedEntry<never>> {
693 await recordUsage(tx, conversationId, "models", `${message.provider}/${message.model}`, message.usage);
694 return tx.appendEntry(AssistantEntry, conversationId, { model: [message] });
695}
696
697/** Start a run for `inputs`, placed input submissions: a new generation takes `pi.live.run`. */
698export async function startRun(
699 tx: Tx,
700 conversationId: ConversationId,
701 live: Draft<LiveState>,
702 inputs: SubmissionId[],
703): Promise<void> {
704 live.run = { taskId: await createGeneration(tx, conversationId), inputs };
705}
706
707/** A generation owned by its conversation. */
708function createGeneration(tx: Tx, conversationId: ConversationId): Promise<TaskId<GenerationResult>> {
709 return tx.createTask(GenerationTask, {}, { ownership: { kind: "conversation" }, conversationId });
710}
711
712/** Hand run control from `from` to `to`; the run's inputs move with it. */
713export function handOver(live: Draft<LiveState>, from: TaskId, to: TaskId): void {
714 if (live.run?.taskId === from) live.run.taskId = to;
715}