Skip to content

armgit / pibot

Public Imported from GitHub
0

Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.

feat(groups): a step continued after the group's pause is told what its stopped run did

leen.zhou6eede4c03240
diff --git a/packages/orchestration/src/conversations/groups/group-step-resume-summary.ts b/packages/orchestration/src/conversations/groups/group-step-resume-summary.ts
new file mode 100644
index 0000000..0847698
--- /dev/null
+++ b/packages/orchestration/src/conversations/groups/group-step-resume-summary.ts
@@ -0,0 +1,224 @@
+import { lstat, opendir } from "node:fs/promises";
+import { join, resolve } from "node:path";
+import type { StoredToolCall } from "@pibot/storage";
+import type { GroupService } from "./group-service.ts";
+import { changedFiles } from "./group-verification-facts.ts";
+import { groupWorkflowBriefPrompts } from "./prompts/group-workflow-brief.ts";
+
+const FILES = 20;
+const COMMANDS = 8;
+const COMMAND_CHARS = 120;
+const PATH_CHARS = 200;
+const SCAN_MS = 3_000;
+const SCAN_ENTRIES = 20_000;
+/** Pi Bot's own state, git internals and installed packages are never someone's edit. */
+const NOT_SCANNED = new Set([".pibot", ".git", "node_modules"]);
+/** A command whose record ended this close to the run's end was cut off by the pause. */
+const STOP_SLACK_MS = 10_000;
+const LEVELS = [
+ [FILES, COMMANDS, FILES],
+ [10, 4, 10],
+ [5, 2, 5],
+ [2, 1, 2],
+ [2, 1, 0],
+ [2, 0, 0],
+] as const;
+
+type Paths = typeof import("node:path").posix;
+interface Listed {
+ items: string[];
+ total: number;
+}
+/**
+ * Maintainers 2026-11-21: what Pi Bot's own records say about the run the group's pause stopped,
+ * for its rerun's brief (a new conversation that does not see that run). No model call.
+ */
+export interface ResumeSummary {
+ files: Listed;
+ /** Oldest first; `total` counts every command the run made. */
+ commands: { items: { command: string; outcome: string; stopped: boolean }[]; total: number };
+ /** Absent when the folder could not be compared cheaply and reliably. */
+ others?: Listed;
+}
+
+export interface ResumeSummaryInput {
+ runId: string;
+ pausedAt?: string;
+ continuedAt?: string;
+ /** The step's working folder as the stopped run saw it (the group's, or the primary it mirrored). */
+ cwd: string;
+ isolated?: { root: string; primary: string };
+ paths: Paths;
+ /** The step works in the group's local folder, where the user may have edited during the pause. */
+ scanShared: boolean;
+}
+
+const clean = (value: string, max: number) => {
+ const text = [...value]
+ .map((character) => (character.charCodeAt(0) < 32 ? " " : character))
+ .join("")
+ .replace(/\s+/gu, " ")
+ .trim();
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
+};
+
+function outcome(call: StoredToolCall, pausedAt: number | undefined, latest: boolean) {
+ const text = groupWorkflowBriefPrompts.summary;
+ const finished = call.finishedAt ? Date.parse(call.finishedAt) : undefined;
+ const stopped =
+ call.status === "running" ||
+ call.status === "pending" ||
+ (call.status === "aborted" &&
+ (pausedAt !== undefined && finished !== undefined
+ ? finished >= pausedAt - STOP_SLACK_MS
+ : latest));
+ if (stopped) return { outcome: text.stopped, stopped };
+ if (call.status === "aborted") return { outcome: text.aborted, stopped };
+ if (call.status === "blocked") return { outcome: text.blocked, stopped };
+ if (call.exitCode !== null) return { outcome: text.exit({ code: call.exitCode }), stopped };
+ return { outcome: call.status === "done" ? text.done : text.failed, stopped };
+}
+
+/**
+ * Files under `root` modified after the stopped run ended and before the group continued. Bounded
+ * by time and entries; when either bound is hit the answer is not reliable, so there is none.
+ */
+async function changedDuringPause(
+ root: string,
+ from: number,
+ to: number,
+ dataDir: string,
+ outer: AbortSignal,
+): Promise<Listed | undefined> {
+ const signal = AbortSignal.any([outer, AbortSignal.timeout(SCAN_MS)]);
+ const skipped = resolve(dataDir);
+ const items: string[] = [];
+ let total = 0;
+ let seen = 0;
+ const queue = [""];
+ for (let index = 0; index < queue.length; index++) {
+ const folder = queue[index] as string;
+ const absolute = join(root, folder);
+ if (resolve(absolute) === skipped) continue;
+ let handle: Awaited<ReturnType<typeof opendir>>;
+ try {
+ handle = await opendir(absolute);
+ } catch {
+ // An unreadable subfolder is no one's edit we could see; an unreadable root means no answer.
+ if (!folder) return undefined;
+ continue;
+ }
+ // Leaving the loop early closes the directory handle.
+ for await (const entry of handle) {
+ if (signal.aborted || ++seen > SCAN_ENTRIES) return undefined;
+ if (entry.isSymbolicLink()) continue;
+ const relative = folder ? `${folder}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) {
+ if (!NOT_SCANNED.has(entry.name.toLowerCase())) queue.push(relative);
+ continue;
+ }
+ if (!entry.isFile()) continue;
+ const info = await lstat(join(root, relative)).catch(() => undefined);
+ if (!info || info.mtimeMs <= from || info.mtimeMs > to) continue;
+ total++;
+ if (items.length < FILES) items.push(relative);
+ }
+ }
+ return signal.aborted ? undefined : { items, total };
+}
+
+export async function resumeSummary(
+ service: GroupService,
+ input: ResumeSummaryInput,
+ signal: AbortSignal,
+): Promise<ResumeSummary> {
+ const redact = (value: string) => service.deps.redactor.redact(value);
+ const rows = service.deps.local.workspaceServices?.changes.turn.repo.summarize(input.runId) ?? [];
+ const changed = [...new Set(changedFiles(rows, input.paths, input.cwd, input.isolated))];
+ const files = {
+ items: changed.slice(0, FILES).map((file) => clean(redact(file), PATH_CHARS)),
+ total: changed.length,
+ };
+ const pausedAt = input.pausedAt ? Date.parse(input.pausedAt) : undefined;
+ const recent = service.deps.local.tools.recentForRun(input.runId, "run_command", COMMANDS);
+ const commands = {
+ items: recent.calls
+ .map((call, index) => ({
+ command: clean(redact(call.summary.replace(/^run_command:\s*/u, "")), COMMAND_CHARS),
+ ...outcome(call, pausedAt, index === 0),
+ }))
+ .reverse(),
+ total: recent.total,
+ };
+ const continuedAt = input.continuedAt ? Date.parse(input.continuedAt) : undefined;
+ const others =
+ input.scanShared && pausedAt !== undefined && continuedAt !== undefined
+ ? await changedDuringPause(input.cwd, pausedAt, continuedAt, service.deps.dataDir, signal)
+ : undefined;
+ signal.throwIfAborted();
+ return {
+ files,
+ commands,
+ ...(others
+ ? {
+ others: {
+ items: others.items.map((file) => clean(redact(file), PATH_CHARS)),
+ total: others.total,
+ },
+ }
+ : {}),
+ };
+}
+
+function render(
+ summary: ResumeSummary,
+ [files, commands, others]: readonly number[],
+ lost: boolean,
+) {
+ const text = groupWorkflowBriefPrompts.summary;
+ const parts: string[] = [];
+ const list = (header: string, listed: Listed | undefined, cap = 0) => {
+ if (!listed?.total || !cap) return;
+ const shown = listed.items.slice(0, cap);
+ parts.push(
+ [
+ header,
+ ...shown.map((item) => `- ${item}`),
+ ...(listed.total > shown.length
+ ? [`- ${text.more({ count: listed.total - shown.length })}`]
+ : []),
+ ].join("\n"),
+ );
+ };
+ list(lost ? text.filesLost : text.files, summary.files, files);
+ if (summary.commands.total && commands) {
+ const shown = summary.commands.items.slice(-commands);
+ parts.push(
+ [
+ text.commands,
+ ...(summary.commands.total > shown.length
+ ? [text.earlier({ count: summary.commands.total - shown.length })]
+ : []),
+ ...shown.map((item) => `- ${item.command} → ${item.outcome}`),
+ ].join("\n"),
+ );
+ }
+ list(text.others, summary.others, others);
+ return parts.join("\n\n");
+}
+
+/** The fullest form that fits `room` characters; lists shrink first, and none at all is fine. */
+export function resumeSummaryText(summary: ResumeSummary, room: number, lost = false): string {
+ for (const level of LEVELS) {
+ const text = render(summary, level, lost);
+ if (text.length <= room) return text;
+ }
+ return "";
+}
+
+export const resumeSummaryCounts = (summary: ResumeSummary) => ({
+ files: summary.files.total,
+ commands: summary.commands.total,
+ stopped: summary.commands.items.filter((item) => item.stopped).length,
+ others: summary.others?.total ?? null,
+});
diff --git a/packages/orchestration/src/conversations/groups/group-verification-facts.ts b/packages/orchestration/src/conversations/groups/group-verification-facts.ts
index df589f2..cdadffb 100644
--- a/packages/orchestration/src/conversations/groups/group-verification-facts.ts
+++ b/packages/orchestration/src/conversations/groups/group-verification-facts.ts
@@ -42,7 +42,8 @@ type ChangeRows = readonly import("@pibot/storage").RunFileSummary[];
type Paths = typeof import("node:path").posix;
type Isolated = { root: string; primary: string };
-function changedFiles(rows: ChangeRows, paths: Paths, root: string, isolated?: Isolated) {
+/** Every path a run changed in its working folder (or its own workspace), relative to it. */
+export function changedFiles(rows: ChangeRows, paths: Paths, root: string, isolated?: Isolated) {
return rows.flatMap((row) => {
if (row.root !== root && !(isolated?.root === row.root && isolated.primary === root)) return [];
if (
diff --git a/packages/orchestration/src/conversations/groups/group-workflow-brief.ts b/packages/orchestration/src/conversations/groups/group-workflow-brief.ts
index d65c0f4..bf5c8e5 100644
--- a/packages/orchestration/src/conversations/groups/group-workflow-brief.ts
+++ b/packages/orchestration/src/conversations/groups/group-workflow-brief.ts
@@ -2,6 +2,7 @@ import { deliveryCorrectionText } from "@pibot/brain/orchestration-kit";
import type { GroupExecutionPlan, HandoffSpec, WorkflowStep } from "@pibot/protocol-base";
import type { HandoffRecord } from "@pibot/storage";
import { handoffBrief } from "./group-handoff-text.ts";
+import { type ResumeSummary, resumeSummaryText } from "./group-step-resume-summary.ts";
import { groupWorkflowBriefPrompts } from "./prompts/group-workflow-brief.ts";
export function stepHandoff(step: WorkflowStep, workflowRunId: string): HandoffSpec {
@@ -16,6 +17,8 @@ export function stepHandoff(step: WorkflowStep, workflowRunId: string): HandoffS
};
}
+const BRIEF_CHARS = 16_000;
+
/** Never truncate required paths/acceptance or input values silently; fail admission explicitly. */
export function stepInstructions(
plan: GroupExecutionPlan & { folder: string },
@@ -33,9 +36,10 @@ export function stepInstructions(
ownWorkspace = false,
/**
* Maintainers 2026-11-21: the rerun of a step the group's pause stopped. Fixed lines at the end,
- * so every other brief keeps its text; `lost` when its unmerged workspace could not be kept.
+ * so every other brief keeps its text; `lost` when its unmerged workspace could not be kept, and
+ * Pi Bot's record of the stopped run last, shortened to fit (the task itself is never cut).
*/
- continued?: { lost: boolean },
+ continued?: { lost: boolean; summary?: ResumeSummary },
): string | undefined {
const failed = previous?.result?.items.filter((item) => item.status === "fail") ?? [];
const text = redact(
@@ -60,7 +64,11 @@ export function stepInstructions(
.filter(Boolean)
.join("\n\n"),
);
- return text.length <= 16_000 ? text : undefined;
+ if (text.length > BRIEF_CHARS) return undefined;
+ const summary = continued?.summary
+ ? resumeSummaryText(continued.summary, BRIEF_CHARS - text.length - 2, continued.lost)
+ : "";
+ return summary ? `${text}\n\n${summary}` : text;
}
/** Defer only declared human checks; missing evidence and unreadable program checks still stop. */
diff --git a/packages/orchestration/src/conversations/groups/group-workflow-dispatch.ts b/packages/orchestration/src/conversations/groups/group-workflow-dispatch.ts
index 17247ce..05c1247 100644
--- a/packages/orchestration/src/conversations/groups/group-workflow-dispatch.ts
+++ b/packages/orchestration/src/conversations/groups/group-workflow-dispatch.ts
@@ -23,6 +23,7 @@ import {
import { checkMethodFolderInputs } from "./group-method-inputs.ts";
import { stepMerged, workspaceFolder, workspaceSteps } from "./group-plan-step-workspaces.ts";
import { assertPlanWorkplace } from "./group-plan-workplace.ts";
+import { resumeSummary, resumeSummaryCounts } from "./group-step-resume-summary.ts";
import { stepHandoff, stepInstructions } from "./group-workflow-brief.ts";
import { reviewPrompt, reviewRequirements, summaryStep } from "./group-workflow-delivery-review.ts";
import { progressOf } from "./group-workflow-progress.ts";
@@ -191,10 +192,8 @@ export class GroupWorkflowDispatcher {
return this.engine.block(record, definition, state, "budget_exhausted");
const group = service.active(record.groupId, state.ownerBotId);
const frozenGroup = workflow.workplace ? { ...group, ...workflow.workplace } : group;
- const access = workspaceFiles(
- service.deps.local,
- (await groupWorkplace(service.deps.local, state.ownerBotId, frozenGroup, signal)).boundary,
- );
+ const place = await groupWorkplace(service.deps.local, state.ownerBotId, frozenGroup, signal);
+ const access = workspaceFiles(service.deps.local, place.boundary);
if (workflow.source.kind === "dynamic" && workflow.delivery)
await checkMethodFolderInputs(
workflow,
@@ -282,6 +281,12 @@ export class GroupWorkflowDispatcher {
: undefined;
const kept = keep?.state === "kept" && ownFolder ? keep : undefined;
const lost = keep?.state === "lost" || (keep?.state === "kept" && !ownFolder);
+ // Read before the transaction and before the old workspace is discarded (its root names it).
+ // Every rerun but a kept workspace's starts from the group folder, so edits there matter.
+ const summary =
+ continued && marker
+ ? await this.resumeSummary(marker, place.cwd, previousTaskId, !kept, access, signal)
+ : undefined;
// A redone step starts from the latest merged base; its earlier workspace is never merged
// (a kept one is the new task's from the transaction below).
if (previousTaskId) {
@@ -312,7 +317,7 @@ export class GroupWorkflowDispatcher {
(value) => service.deps.redactor.redact(value),
text,
!!ownFolder,
- continued ? { lost } : undefined,
+ continued ? { lost, ...(summary ? { summary } : {}) } : undefined,
);
const reviewText =
review && reviewPrompt(service, review, workflow.contract.steps ?? [], states);
@@ -454,11 +459,61 @@ export class GroupWorkflowDispatcher {
workspace: kept ? "kept" : lost ? "lost" : "none",
}),
);
+ if (summary)
+ service.deps.logger.info(
+ JSON.stringify({
+ module: "group-workflow",
+ event: "step_resume_summary",
+ workflowRunId: record.id,
+ stepId: definition.id,
+ ...resumeSummaryCounts(summary),
+ }),
+ );
// Only needed by the step's merge, long after its run started.
if (kept && previousTaskId)
await service.memberWorktrees.adoptedStep(previousTaskId, task.task.id);
}
+ /** Auxiliary context: a failure leaves the rerun's brief without it, never the step blocked. */
+ private async resumeSummary(
+ marker: NonNullable<ReturnType<typeof progressOf>["resumed"]>[string],
+ cwd: string,
+ previousTaskId: string | null | undefined,
+ shared: boolean,
+ access: ReturnType<typeof workspaceFiles>,
+ signal: AbortSignal,
+ ) {
+ const { service } = this.engine;
+ try {
+ const isolated = previousTaskId
+ ? service.memberWorktrees.isolated(previousTaskId)
+ : undefined;
+ return await resumeSummary(
+ service,
+ {
+ runId: marker.runId,
+ ...(marker.pausedAt ? { pausedAt: marker.pausedAt } : {}),
+ ...(marker.continuedAt ? { continuedAt: marker.continuedAt } : {}),
+ cwd,
+ ...(isolated?.primary === cwd ? { isolated } : {}),
+ paths: access.paths,
+ scanShared: shared && !access.remote,
+ },
+ signal,
+ );
+ } catch (error) {
+ if (signal.aborted) throw error;
+ service.deps.logger.warn(
+ JSON.stringify({
+ module: "group-workflow",
+ event: "step_resume_summary_failed",
+ code: error instanceof RpcError ? error.message : "internal",
+ }),
+ );
+ return undefined;
+ }
+ }
+
private async discard(taskId: string) {
const { service } = this.engine;
try {
diff --git a/packages/orchestration/src/conversations/groups/group-workflow-pause.ts b/packages/orchestration/src/conversations/groups/group-workflow-pause.ts
index 7dc1f55..474892e 100644
--- a/packages/orchestration/src/conversations/groups/group-workflow-pause.ts
+++ b/packages/orchestration/src/conversations/groups/group-workflow-pause.ts
@@ -142,10 +142,17 @@ export class GroupWorkflowPause {
// The rerun of each is told files may have changed and keeps the workspace it had
// (dispatch); the marker names the stopped run, so only that rerun reads it.
const resumed = { ...ledger.resumed };
+ const continuedAt = new Date().toISOString();
for (const stepId of picked) {
const state = ready.get(stepId);
- if (state?.executionRunId)
- resumed[stepId] = { runId: state.executionRunId, attempt: state.attempt };
+ if (!state?.executionRunId) continue;
+ // The stopped run's end bounds what "changed during the pause" means for its rerun.
+ const pausedAt = service.runs.get(state.executionRunId)?.finishedAt ?? undefined;
+ resumed[stepId] = {
+ runId: state.executionRunId,
+ attempt: state.attempt,
+ ...(pausedAt ? { pausedAt, continuedAt } : {}),
+ };
}
progress.save(latest, {
...ledger,
diff --git a/packages/orchestration/src/conversations/groups/group-workflow-progress.ts b/packages/orchestration/src/conversations/groups/group-workflow-progress.ts
index 279fb47..6ab0f2e 100644
--- a/packages/orchestration/src/conversations/groups/group-workflow-progress.ts
+++ b/packages/orchestration/src/conversations/groups/group-workflow-progress.ts
@@ -92,7 +92,13 @@ const Progress = z.strictObject({
resumed: z
.record(
z.string(),
- z.strictObject({ runId: z.string().max(64), attempt: z.number().int().nonnegative() }),
+ z.strictObject({
+ runId: z.string().max(64),
+ attempt: z.number().int().nonnegative(),
+ /** When the stopped run ended and when the group continued: the rerun's summary window. */
+ pausedAt: z.iso.datetime().optional(),
+ continuedAt: z.iso.datetime().optional(),
+ }),
)
.refine((items) => Object.keys(items).length <= 20)
.optional(),
diff --git a/packages/orchestration/src/conversations/groups/prompts/group-workflow-brief.md b/packages/orchestration/src/conversations/groups/prompts/group-workflow-brief.md
index 7cc437c..82fb1d0 100644
--- a/packages/orchestration/src/conversations/groups/prompts/group-workflow-brief.md
+++ b/packages/orchestration/src/conversations/groups/prompts/group-workflow-brief.md
@@ -1,6 +1,6 @@
# group-workflow-brief
-Prompt text used by `group-workflow-brief.ts` (a plan step's brief). Each `## \`key\`` block is sent to the model exactly as written (blank lines around a block are ignored); `{{name}}` is filled in by the code. After editing, run `pnpm gen:prompts`. Changing a block changes the cached prompt prefix (see docs/prompt-cache.md). These lines are appended at the end of a brief, and only to the rerun of a step the group's pause stopped, so other briefs keep their text.
+Prompt text used by `group-workflow-brief.ts` (a plan step's brief). Each `## \`key\`` block is sent to the model exactly as written (blank lines around a block are ignored); `{{name}}` is filled in by the code. After editing, run `pnpm gen:prompts`. Changing a block changes the cached prompt prefix (see docs/prompt-cache.md). These lines are appended at the end of a brief, and only to the rerun of a step the group's pause stopped, so other briefs keep their text. The `summary.*` blocks head the lists Pi Bot builds from its own records of the stopped run (no model call); each list follows its line as `- item` lines.
## `resumed`
@@ -9,3 +9,51 @@ Prompt text used by `group-workflow-brief.ts` (a plan step's brief). Each `## \`
## `resumedLost`
这一步之前在自己工作区里还没合并的改动没能保留,这次从当前的群文件夹开始。 / The unmerged changes this step had made in its own workspace could not be kept; this run starts from the current group folder.
+
+## `summary.files`
+
+上次被暂停停下的运行改过这些文件(Pi Bot 的记录,路径相对于你的工作文件夹): / Files the stopped run changed (Pi Bot's records; paths relative to your working folder):
+
+## `summary.filesLost`
+
+上次被暂停停下的运行在自己工作区里改过这些文件,这些改动没有保留(路径相对于你的工作文件夹): / Files the stopped run had changed in its own workspace; those changes were not kept (paths relative to your working folder):
+
+## `summary.commands`
+
+它最近运行的命令和结果(按先后): / The latest commands it ran and their outcome (in order):
+
+## `summary.others`
+
+暂停期间有人(比如用户)改过这些文件: / Files someone else (for example the user) changed during the pause:
+
+## `summary.more`
+
+…还有 {{count}} 个 / …and {{count}} more
+
+## `summary.earlier`
+
+(之前还有 {{count}} 条) / ({{count}} earlier not shown)
+
+## `summary.exit`
+
+退出码 {{code}} / exit {{code}}
+
+## `summary.done`
+
+完成 / done
+
+## `summary.failed`
+
+失败 / failed
+
+## `summary.blocked`
+
+未运行(被拦下) / not run (blocked)
+
+## `summary.aborted`
+
+已中止 / aborted
+
+## `summary.stopped`
+
+被暂停打断 / stopped by the pause
diff --git a/packages/orchestration/src/conversations/groups/prompts/group-workflow-brief.ts b/packages/orchestration/src/conversations/groups/prompts/group-workflow-brief.ts
index 8f23bc9..a50bc8f 100644
--- a/packages/orchestration/src/conversations/groups/prompts/group-workflow-brief.ts
+++ b/packages/orchestration/src/conversations/groups/prompts/group-workflow-brief.ts
@@ -4,4 +4,23 @@ export const groupWorkflowBriefPrompts = {
"这一步因群组暂停被中断,现在继续:暂停期间文件可能有变化(包括用户的修改),继续前先重新读取你要依赖的文件和当前进度,已经完成的部分不要重做。 / This step was interrupted by the group pause and is continuing now: files may have changed during the pause (including by the user). Re-read the files and progress you rely on before editing, and don't redo parts that are already done.",
resumedLost:
"这一步之前在自己工作区里还没合并的改动没能保留,这次从当前的群文件夹开始。 / The unmerged changes this step had made in its own workspace could not be kept; this run starts from the current group folder.",
+ summary: {
+ files:
+ "上次被暂停停下的运行改过这些文件(Pi Bot 的记录,路径相对于你的工作文件夹): / Files the stopped run changed (Pi Bot's records; paths relative to your working folder):",
+ filesLost:
+ "上次被暂停停下的运行在自己工作区里改过这些文件,这些改动没有保留(路径相对于你的工作文件夹): / Files the stopped run had changed in its own workspace; those changes were not kept (paths relative to your working folder):",
+ commands:
+ "它最近运行的命令和结果(按先后): / The latest commands it ran and their outcome (in order):",
+ others:
+ "暂停期间有人(比如用户)改过这些文件: / Files someone else (for example the user) changed during the pause:",
+ more: (v: { count: string | number }) => `…还有 ${v.count} 个 / …and ${v.count} more`,
+ earlier: (v: { count: string | number }) =>
+ `(之前还有 ${v.count} 条) / (${v.count} earlier not shown)`,
+ exit: (v: { code: string | number }) => `退出码 ${v.code} / exit ${v.code}`,
+ done: "完成 / done",
+ failed: "失败 / failed",
+ blocked: "未运行(被拦下) / not run (blocked)",
+ aborted: "已中止 / aborted",
+ stopped: "被暂停打断 / stopped by the pause",
+ },
} as const;
diff --git a/packages/storage/src/runs/tool-calls.ts b/packages/storage/src/runs/tool-calls.ts
index 9980193..87bcdfd 100644
--- a/packages/storage/src/runs/tool-calls.ts
+++ b/packages/storage/src/runs/tool-calls.ts
@@ -252,6 +252,26 @@ export class ToolCallsRepo {
return result;
}
+ /** A run's latest calls of one tool, newest first, and how many it made in all. */
+ recentForRun(
+ runId: string,
+ tool: string,
+ limit: number,
+ ): { calls: StoredToolCall[]; total: number } {
+ const calls = this.db
+ .prepare(`SELECT ${columns} FROM ${source} JOIN messages m ON m.id = t.message_id
+ WHERE m.run_id = ? AND t.tool = ? ORDER BY t.created_at DESC, t.rowid DESC LIMIT ?`)
+ .all(runId, tool, Math.max(0, Math.min(limit, 50)))
+ .map(parseTool);
+ const total = Number(
+ this.db
+ .prepare(`SELECT count(*) AS n FROM tool_calls t JOIN messages m ON m.id = t.message_id
+ WHERE m.run_id = ? AND t.tool = ?`)
+ .get(runId, tool)?.n ?? 0,
+ );
+ return { calls, total };
+ }
+
getLogPath(runId: string, toolCallId?: string): string | undefined {
// A run may hold one log per command. The step's tool call selects its own; without it only a
// unique run log is safe to use — conflicting persisted paths must not choose an arbitrary file.