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.

fix(execution): a paused command cleanup can recover on Windows and says why

leen.zhou759cac211740
diff --git a/apps/desktop/src/renderer/app/command-pause.ts b/apps/desktop/src/renderer/app/command-pause.ts
new file mode 100644
index 0000000..66812ce
--- /dev/null
+++ b/apps/desktop/src/renderer/app/command-pause.ts
@@ -0,0 +1,74 @@
+import type { CommandPause } from "@pibot/protocol";
+import { type Peer, useRpc } from "@pibot/renderer-kit";
+import { useMemo, useSyncExternalStore } from "react";
+
+const running: CommandPause = { paused: null };
+
+/** Unlike the sticky drain health, this pause clears by itself, so each update replaces the last. */
+class CommandPauseStore {
+ private state: CommandPause = running;
+ private listeners = new Set<() => void>();
+ private off?: () => void;
+ private epoch = 0;
+ constructor(private readonly peer: Peer) {}
+ snapshot = () => this.state;
+ subscribe = (listener: () => void) => {
+ this.listeners.add(listener);
+ if (this.listeners.size === 1) this.start();
+ return () => {
+ this.listeners.delete(listener);
+ if (this.listeners.size === 0) this.stop();
+ };
+ };
+ set = (next: CommandPause) => {
+ // A newer event or result supersedes a snapshot requested before it.
+ this.epoch++;
+ this.apply(next);
+ };
+ private apply(next: CommandPause) {
+ if (next.paused === this.state.paused) return;
+ this.state = next;
+ for (const listener of this.listeners) listener();
+ }
+ private start() {
+ const epoch = ++this.epoch;
+ this.off = this.peer.on("runtime.commands", (next) => this.set(next));
+ void this.peer
+ .call("runtime.commands.get", undefined)
+ .then((next) => {
+ if (epoch === this.epoch) this.apply(next);
+ })
+ .catch(() => {
+ // Advisory only: a missed snapshot hides the banner; the next event shows it again.
+ });
+ }
+ private stop() {
+ this.epoch++;
+ this.off?.();
+ this.off = undefined;
+ }
+}
+
+const stores = new WeakMap<Peer, CommandPauseStore>();
+const runningSnapshot = () => running;
+function useStore() {
+ const { peer } = useRpc();
+ return useMemo(() => {
+ if (!peer) return undefined;
+ let found = stores.get(peer);
+ if (!found) {
+ found = new CommandPauseStore(peer);
+ stores.set(peer, found);
+ }
+ return found;
+ }, [peer]);
+}
+export function useCommandPause(): CommandPause & { update?(next: CommandPause): void } {
+ const store = useStore();
+ const state = useSyncExternalStore(
+ store?.subscribe ?? (() => () => {}),
+ store?.snapshot ?? runningSnapshot,
+ store?.snapshot ?? runningSnapshot,
+ );
+ return store ? { ...state, update: store.set } : state;
+}
diff --git a/apps/desktop/src/renderer/features/runtime/CommandPause.tsx b/apps/desktop/src/renderer/features/runtime/CommandPause.tsx
new file mode 100644
index 0000000..410c5b6
--- /dev/null
+++ b/apps/desktop/src/renderer/features/runtime/CommandPause.tsx
@@ -0,0 +1,67 @@
+import type { CommandPause } from "@pibot/protocol";
+import { useAction, useRpc, useT } from "@pibot/renderer-kit";
+import { Button, IconTile } from "@pibot/ui";
+import { useCommandPause } from "../../app/command-pause.ts";
+
+/**
+ * Commands are paused because Pi Bot could not confirm a previous command stopped. The brain
+ * releases the pause only with proof, so "Check again" asks for one more check and never forces it.
+ */
+export function CommandPauseBanner({ className }: { className: string }) {
+ const pause = useCommandPause();
+ if (!pause.paused) return null;
+ // Keyed by state: an earlier "still paused" answer belongs to that state only.
+ return (
+ <PausedBanner
+ key={pause.paused}
+ className={className}
+ paused={pause.paused}
+ update={pause.update}
+ />
+ );
+}
+
+function PausedBanner({
+ className,
+ paused,
+ update,
+}: {
+ className: string;
+ paused: NonNullable<CommandPause["paused"]>;
+ update?: (next: CommandPause) => void;
+}) {
+ const t = useT();
+ const { peer } = useRpc();
+ const task = useAction();
+ return (
+ <div role="alert" className={className}>
+ <IconTile icon="warning" tone="red" size="sm" />
+ <span>
+ {t(paused === "stuck" ? "runtime.commandsPausedStuck" : "runtime.commandsPausedRetrying")}
+ {task.error && <> {t(task.error)}</>}
+ </span>
+ <Button
+ variant="secondary"
+ disabled={!peer}
+ loading={task.busy}
+ onClick={() => {
+ if (!peer) return;
+ // One check may wait for several slow process snapshots on a loaded Windows host.
+ void task
+ .run(
+ (signal) =>
+ peer.call("runtime.commands.recheck", undefined, { signal, timeoutMs: 120_000 }),
+ () => "runtime.commandsStillPaused",
+ )
+ .then((result) => {
+ if (!result) return;
+ if (result.paused) task.setError("runtime.commandsStillPaused");
+ update?.(result);
+ });
+ }}
+ >
+ {t("runtime.commandsRecheck")}
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/sidebar/index.tsx b/apps/desktop/src/renderer/features/sidebar/index.tsx
index cb97ac3..7b91344 100644
--- a/apps/desktop/src/renderer/features/sidebar/index.tsx
+++ b/apps/desktop/src/renderer/features/sidebar/index.tsx
@@ -6,6 +6,7 @@ import { Button, Icon, IconTile } from "@pibot/ui";
import { useEffect, useRef, useState } from "react";
import { useRuntimeHealth } from "../../app/runtime-health.ts";
import { AppMenu } from "../app-menu/AppMenu.tsx";
+import { CommandPauseBanner } from "../runtime/CommandPause.tsx";
import { ForceRelease } from "../runtime/ForceRelease.tsx";
import { updateBot } from "../settings/operations.ts";
import { newChatDialog } from "../workspace/new-chat/new-chat-dialog.ts";
@@ -278,6 +279,7 @@ export function Sidebar() {
<ForceRelease />
</div>
)}
+ <CommandPauseBanner className={styles.health} />
<div className={styles.search}>
<Icon name="search" size={15} className={styles.searchIcon} />
<input
diff --git a/packages/brain/src/local-service.ts b/packages/brain/src/local-service.ts
index 1cce2fd..297eeb7 100644
--- a/packages/brain/src/local-service.ts
+++ b/packages/brain/src/local-service.ts
@@ -234,6 +234,37 @@ export class LocalService {
readonly executionTargets = new ExecutionTargets();
/** Primary folders whose pre-A55 outputs were already looked at in this process. */
readonly outputMigrations = new Set<string>();
+ /**
+ * Tells the UI and the Records log that commands are paused, still paused or resumed. The state
+ * is read back from the target rather than derived from the event, so a repeat report can never
+ * show a pause that already cleared. Reporting must not affect the pause itself.
+ */
+ private reportCommandPause(
+ event: { phase: "paused" | "stuck" | "recovered"; runId?: string },
+ botId: string | undefined,
+ jobRunId: string | null | undefined,
+ ) {
+ try {
+ this.deps.peer.emit("runtime.commands", { paused: this.target.commandPause?.() ?? null });
+ const owner = botId ?? new BotsRepo(this.deps.db).getMain()?.id;
+ // Without any Bot the row has nowhere to be filed; the log line above still has the event.
+ if (!owner) return;
+ const runId = event.runId ?? jobRunId ?? undefined;
+ this.approvals.audit.append({
+ botId: owner,
+ ...(runId ? { runId } : {}),
+ kind: "runtime.commands_paused",
+ summary:
+ event.phase === "recovered"
+ ? "Commands resumed / 命令已恢复"
+ : "Commands paused / 命令已暂停",
+ detail: { reasonCode: event.phase },
+ });
+ } catch {
+ this.deps.logger.warn(JSON.stringify({ module: "exec", event: "command_pause_unreported" }));
+ }
+ }
+
targetFor(location?: { target: string }): ExecutionTarget {
return !location ||
location.target === "local" ||
@@ -298,14 +329,18 @@ export class LocalService {
// The pause blocks every command, so its owner (the job's Bot and topic) has to be
// in the log; without it 1,380 failures took 5.5 hours to trace.
const row = event.jobId ? this.background.repo.get(event.jobId) : undefined;
+ const botId =
+ row?.botId ?? (event.runId ? this.runContexts.get(event.runId)?.botId : undefined);
const fields = {
module: "exec",
event: `background.drain_${event.phase}`,
...event,
- ...(row ? { botId: row.botId, conversationId: row.conversationId } : {}),
+ ...(botId ? { botId } : {}),
+ ...(row ? { conversationId: row.conversationId } : {}),
};
if (event.phase === "recovered") deps.logger.info(JSON.stringify(fields));
else deps.logger.warn(JSON.stringify(fields));
+ if (event.phase !== "retrying") this.reportCommandPause(event, botId, row?.runId);
},
platform: deps.platform,
proxy: deps.proxy,
diff --git a/packages/brain/src/runtime/startup/business-rpc.ts b/packages/brain/src/runtime/startup/business-rpc.ts
index 901f43e..d63b54b 100644
--- a/packages/brain/src/runtime/startup/business-rpc.ts
+++ b/packages/brain/src/runtime/startup/business-rpc.ts
@@ -57,6 +57,8 @@ function internalDetail(error: unknown): string {
const contentIndependent = new Set<string>([
"runtime.health.get",
"runtime.forceRelease",
+ "runtime.commands.get",
+ "runtime.commands.recheck",
"chat.abort",
"groups.abort",
"app.about",
diff --git a/packages/brain/src/runtime/startup/register-health-rpc.ts b/packages/brain/src/runtime/startup/register-health-rpc.ts
index 6de8499..602058a 100644
--- a/packages/brain/src/runtime/startup/register-health-rpc.ts
+++ b/packages/brain/src/runtime/startup/register-health-rpc.ts
@@ -1,4 +1,5 @@
import {
+ type CommandPause,
type createPeer,
type KernelEvents,
type KernelMethods,
@@ -39,6 +40,20 @@ export function registerHealthRpc(ctx: StartupContext) {
return { healthy: false, reason: "interactive_drain_failed", botIds: run.botIds };
return run;
});
+ // A local command pause clears by itself once a check proves the previous command stopped; the
+ // UI pulls it on (re)connect like the drain health above, and live changes arrive as events.
+ const commandPause = (): CommandPause => ({
+ paused: ctx.capabilities.target.commandPause?.() ?? null,
+ });
+ ctx.handle("runtime.commands.get", async () => commandPause());
+ ctx.handle("runtime.commands.recheck", async (): Promise<CommandPause> => {
+ const recheck = ctx.capabilities.target.recheckCommandPause;
+ if (!recheck) return commandPause();
+ const paused = await recheck();
+ // A recovery is announced by the drain event; a refused check changes nothing to announce,
+ // and the result alone tells the person it is still paused.
+ return { paused };
+ });
/**
* The client-wide failure has its own state in this factory, so reopening it is
* the same detach a client performs, bounded: a drain that never settles must fail the release
diff --git a/packages/brain/src/runtime/tools/execution-paused.ts b/packages/brain/src/runtime/tools/execution-paused.ts
index 481282e..e4c65e2 100644
--- a/packages/brain/src/runtime/tools/execution-paused.ts
+++ b/packages/brain/src/runtime/tools/execution-paused.ts
@@ -6,7 +6,7 @@ import { ExecError } from "@pibot/execution";
* wording hid the real cause for 5.5 hours and 1,380 attempts.
*/
export const EXECUTION_PAUSED =
- "后台命令没能清理干净,为安全起见暂停新命令;正在自动重试清理,通常 30 秒内恢复,重启 Pi Bot 也能恢复 / A background command could not be cleaned up, so new commands are paused for safety. Cleanup is retried automatically (usually within 30 seconds); restarting Pi Bot also restores it.";
+ "Pi Bot 没能确认上一条命令已经停下,为安全起见暂停新命令;正在自动检查,确认后自动恢复。侧栏提示里可以「再检查一次」,一直不恢复请重启 Pi Bot / Pi Bot couldn't confirm a previous command stopped, so new commands are paused for safety. It keeps checking and resumes once that's confirmed; the sidebar notice offers \"Check again\", and restarting Pi Bot also clears it.";
/**
* Identifies the paused runtime from the error alone: the refusal comes from the command layer,
diff --git a/packages/client-core/src/audit/presentation.ts b/packages/client-core/src/audit/presentation.ts
index 33875c8..a872077 100644
--- a/packages/client-core/src/audit/presentation.ts
+++ b/packages/client-core/src/audit/presentation.ts
@@ -162,6 +162,7 @@ const kindGroups: Record<AuditKind, readonly [AuditGroup, ...AuditGroup[]]> = {
"execution.continuation.restored": ["run"],
"runtime.drain_failed": ["run"],
"runtime.force_release": ["run"],
+ "runtime.commands_paused": ["run"],
"execution.task.changed": ["run"],
"team.created": ["collaboration"],
"team.exported": ["collaboration"],
@@ -535,6 +536,14 @@ export function auditSummary(
);
case "runtime.drain_failed":
return t("runtime.auditDrainFailed");
+ case "runtime.commands_paused":
+ return t(
+ detail.reasonCode === "recovered"
+ ? "runtime.auditCommandsRecovered"
+ : detail.reasonCode === "stuck"
+ ? "runtime.auditCommandsStuck"
+ : "runtime.auditCommandsPaused",
+ );
case "runtime.force_release":
return t(
detail.reasonCode === "released"
diff --git a/packages/execution/src/command/background.ts b/packages/execution/src/command/background.ts
index ca2ac5f..ac1f5e8 100644
--- a/packages/execution/src/command/background.ts
+++ b/packages/execution/src/command/background.ts
@@ -31,18 +31,41 @@ const RETRY_MS = 30_000;
/** Log a still-blocked retry once in this many attempts; a stuck group stays quiet otherwise. */
const REPORT_EVERY = 10;
+/**
+ * Automatic checks stop after this many (about 10 minutes) and the pause is reported as stuck, so
+ * a tree that can never be proven gone no longer retries every 30 s for hours (Windows test
+ * 2026-11-21: 40 silent attempts). The pause itself stays: only a manual check or a restart ends it.
+ */
+const MAX_AUTO_ATTEMPTS = 20;
+
+/**
+ * A retry is off every command's path, so it may wait longer for a snapshot than the command
+ * monitor (10 s on Windows): the pause started because a starved host missed that limit, and
+ * the same limit would keep failing the proof for as long as the load lasts.
+ */
+const RETRY_SNAPSHOT_MS = 30_000;
+/** One attempt may take several snapshots (find, stop, confirm); bounded so shutdown never waits. */
+const ATTEMPT_MS = 90_000;
+
interface RetainedDrain {
reason: BackgroundDrainEvent["reason"];
/** Captured when the failure happened: the retained job may end before the retry runs. */
records: BackgroundProcessRecord[];
/** Every job whose cleanup was never confirmed; a second failure while paused joins this set. */
jobIds: string[];
+ /** The run that owned the failed foreground command, when exactly one did. */
+ runId?: string;
attempts: number;
/** Bumped when another failure joins; a retry that started earlier must not release the pause. */
revision: number;
+ /** Automatic checks ended without proof; only a manual check or a restart can release it. */
+ stuck: boolean;
timer?: ReturnType<typeof setTimeout>;
}
+/** What the person is told: commands are paused while Pi Bot checks, or until they act. */
+export type CommandPauseState = "retrying" | "stuck" | null;
+
/** Records are merged by tree identity so the same group is never checked or killed twice. */
const recordKey = (record: BackgroundProcessRecord) =>
`${record.group}:${record.processes
@@ -57,6 +80,7 @@ export function createBackgroundJobs(deps: BackgroundDependencies) {
let drainFailure: ExecError | undefined;
let drain: RetainedDrain | undefined;
let retrying: Promise<void> | undefined;
+ const healthyWaiters = new Set<() => void>();
const monitor = createBackgroundMonitor(deps, jobs, lifetime);
const processes = createBackgroundProcesses(deps);
const report = (event: BackgroundDrainEvent) => {
@@ -69,16 +93,24 @@ export function createBackgroundJobs(deps: BackgroundDependencies) {
const assertHealthy = () => {
if (drainFailure) throw drainFailure;
};
+ const owner = (current: RetainedDrain) => ({
+ ...(current.jobIds.length === 1 ? { jobId: current.jobIds[0] } : {}),
+ ...(current.runId ? { runId: current.runId } : {}),
+ });
+ /** Manual and scheduled checks share one attempt; two concurrent kills of one tree prove nothing. */
+ const attempt = () => {
+ retrying ??= retry().finally(() => {
+ retrying = undefined;
+ });
+ return retrying;
+ };
const schedule = () => {
- if (!drain || lifetime.signal.aborted) return;
+ if (!drain || drain.stuck || lifetime.signal.aborted) return;
clearTimeout(drain.timer);
const timer = setTimeout(() => {
if (drain) drain.timer = undefined;
- retrying = retry().finally(() => {
- retrying = undefined;
- // Recovery clears `drain`; anything else is still blocked and tries again later.
- schedule();
- });
+ // Recovery clears `drain`; anything else is still blocked and tries again later.
+ void attempt().then(schedule);
}, RETRY_MS);
// The retry is a safety net, not a reason to keep the process alive.
timer.unref?.();
@@ -91,16 +123,21 @@ export function createBackgroundJobs(deps: BackgroundDependencies) {
const revision = current.revision;
current.attempts += 1;
// Proof needs something to check: on POSIX the retained group id, on Windows the recorded
- // process identities. Without either, a restart stays the only way out.
+ // process identities or, when a starved snapshot never captured them, the root pid and spawn
+ // time. Without any of these, a restart stays the only way out.
const provable =
current.records.length > 0 &&
- (deps.platform !== "win32" || current.records.every((record) => record.processes.length > 0));
+ (deps.platform !== "win32" ||
+ current.records.every(
+ (record) => record.processes.length > 0 || record.spawnedAt !== undefined,
+ ));
let remaining = provable ? 0 : 1;
try {
if (provable) {
- const signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(RETRY_MS)]);
- remaining = await processes.killOrphans(current.records, signal);
+ const signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(ATTEMPT_MS)]);
+ remaining = await processes.killOrphans(current.records, signal, RETRY_SNAPSHOT_MS);
remaining += groupAlive(current.records, deps.platform);
+ if (!remaining) remaining = await processes.treeRemains(current.records, RETRY_SNAPSHOT_MS);
}
} catch {
// A failed snapshot proves nothing either way, so the pause continues.
@@ -110,13 +147,24 @@ export function createBackgroundJobs(deps: BackgroundDependencies) {
// Another failure joined while this attempt was running: its tree has not been checked yet,
// so releasing the pause here would strand it exactly like the first one was stranded.
if (drain !== current || current.revision !== revision) return;
- const jobId = current.jobIds.length === 1 ? { jobId: current.jobIds[0] } : {};
if (remaining) {
- if (current.attempts === 1 || current.attempts % REPORT_EVERY === 0)
+ const exhausted = !provable || current.attempts >= MAX_AUTO_ATTEMPTS;
+ if (exhausted) {
+ // Reported on the transition, and again for each manual check that still finds no proof.
+ current.stuck = true;
+ clearTimeout(current.timer);
+ report({
+ phase: "stuck",
+ reason: current.reason,
+ ...owner(current),
+ attempts: current.attempts,
+ remaining,
+ });
+ } else if (current.attempts === 1 || current.attempts % REPORT_EVERY === 0)
report({
phase: "retrying",
reason: current.reason,
- ...jobId,
+ ...owner(current),
attempts: current.attempts,
remaining,
});
@@ -136,22 +184,60 @@ export function createBackgroundJobs(deps: BackgroundDependencies) {
report({
phase: "recovered",
reason: current.reason,
- ...jobId,
+ ...owner(current),
attempts: current.attempts,
remaining: 0,
});
+ for (const resolve of [...healthyWaiters]) resolve();
}
- const failDrain = (error: ExecError, jobId?: string, record?: BackgroundProcessRecord) => {
+ /**
+ * Resolves once the pause is released; rejects when the instance closes. A run waits here for
+ * its temp folder instead of failing its drain, so a later proof frees the run's folder lease
+ * too and nothing but the commands themselves waited (Windows test 2026-11-21).
+ */
+ const whenHealthy = (signal?: AbortSignal) =>
+ new Promise<void>((resolve, reject) => {
+ if (!drainFailure) return resolve();
+ const stop = AbortSignal.any([lifetime.signal, ...(signal ? [signal] : [])]);
+ const done = () => {
+ healthyWaiters.delete(done);
+ stop.removeEventListener("abort", abort);
+ resolve();
+ };
+ const abort = () => {
+ healthyWaiters.delete(done);
+ reject(drainFailure ?? new ExecError("closed"));
+ };
+ if (stop.aborted) return abort();
+ healthyWaiters.add(done);
+ stop.addEventListener("abort", abort, { once: true });
+ });
+ const pauseState = (): CommandPauseState =>
+ drain ? (drain.stuck ? "stuck" : "retrying") : drainFailure ? "stuck" : null;
+ const failDrain = (
+ error: ExecError,
+ jobId?: string,
+ record?: BackgroundProcessRecord,
+ runId?: string,
+ ) => {
// Only the tree whose cleanup failed is retained; other background commands keep running and
// must never be killed by the retry or ended by the recovery.
// The failed job is read regardless of `running`: a reported failure may already have marked
// it stopped. Without an identifiable tree the pause cannot be proven clear, so it stays.
const failed = jobId ? jobs.get(jobId) : undefined;
- const retained = failed ? [failed.record()] : record ? [record] : [];
+ // A job's spawn time travels with its record, so a Windows tree whose identities a starved
+ // snapshot never captured can still be checked later.
+ const retained = failed
+ ? [{ ...failed.record(), spawnedAt: failed.startedAt }]
+ : record
+ ? [record]
+ : [];
// A failure while already paused is a different tree, not the same state: dropping it would
// let the first recovery release the pause with this tree unchecked.
const joined = drain;
if (joined) {
+ const before = joined.records.length;
+ const known = !!jobId && joined.jobIds.includes(jobId);
const seen = new Set(joined.records.map(recordKey));
for (const candidate of retained) {
const key = recordKey(candidate);
@@ -160,15 +246,26 @@ export function createBackgroundJobs(deps: BackgroundDependencies) {
joined.records.push(candidate);
}
if (jobId && !joined.jobIds.includes(jobId)) joined.jobIds.push(jobId);
+ if (runId && joined.runId !== runId) joined.runId = undefined;
// A retry may be mid-flight with the older set; its release must be refused.
joined.revision += 1;
- report({
- phase: "paused",
- reason: joined.reason,
- ...(jobId ? { jobId } : {}),
- attempts: joined.attempts,
- remaining: 0,
- });
+ const added = joined.records.length > before;
+ // A new tree deserves its own round of automatic checks; a repeat report of the same failure
+ // (the same error passes several layers) changes nothing and stays quiet.
+ if (added && joined.stuck) {
+ joined.stuck = false;
+ joined.attempts = 0;
+ schedule();
+ }
+ if (added || (jobId && !known))
+ report({
+ phase: "paused",
+ reason: joined.reason,
+ ...(jobId ? { jobId } : {}),
+ ...(runId ? { runId } : {}),
+ attempts: joined.attempts,
+ remaining: 0,
+ });
return;
}
drainFailure = error;
@@ -176,13 +273,16 @@ export function createBackgroundJobs(deps: BackgroundDependencies) {
reason: backgroundCleanupReason(error),
records: retained,
jobIds: jobId ? [jobId] : [],
+ ...(runId ? { runId } : {}),
attempts: 0,
revision: 0,
+ stuck: false,
};
report({
phase: "paused",
reason: drain.reason,
...(jobId ? { jobId } : {}),
+ ...(runId ? { runId } : {}),
attempts: 0,
remaining: 0,
});
@@ -210,13 +310,25 @@ export function createBackgroundJobs(deps: BackgroundDependencies) {
assertHealthy,
failDrain,
drainFailed: () => !!drainFailure,
- killOrphans: processes.killOrphans,
+ whenHealthy,
+ pauseState,
+ /**
+ * The person asked to check again: one attempt now, with the same proof as the automatic ones.
+ * Never a release without proof; the result is the state after the attempt.
+ */
+ async recheck(): Promise<CommandPauseState> {
+ if (drain) await attempt();
+ return pauseState();
+ },
+ killOrphans: (records: BackgroundProcessRecord[], signal: AbortSignal) =>
+ processes.killOrphans(records, signal),
get(id: string): BackgroundJob | undefined {
return jobs.get(id);
},
async dispose() {
lifetime.abort();
clearTimeout(drain?.timer);
+ healthyWaiters.clear();
drain = undefined;
const monitoring = monitor.dispose();
const results = await Promise.allSettled([...jobs.values()].map((job) => job.stop()));
diff --git a/packages/execution/src/command/background/processes.ts b/packages/execution/src/command/background/processes.ts
index 89b7988..82121d3 100644
--- a/packages/execution/src/command/background/processes.ts
+++ b/packages/execution/src/command/background/processes.ts
@@ -1,6 +1,6 @@
import { ExecError } from "../../core/types.ts";
import { windowsTree } from "../process.ts";
-import { snapshot } from "../process-tree.ts";
+import { type ProcessRow, snapshot } from "../process-tree.ts";
import type {
BackgroundDependencies,
BackgroundDrainReason,
@@ -9,6 +9,19 @@ import type {
} from "./types.ts";
const STOP_GRACE_MS = 3000;
+/** Spawn time is read just before (foreground) or after (background) the spawn; widen the match. */
+const SPAWN_MARGIN_MS = 2000;
+/** .NET ticks (100 ns since 0001-01-01) of the Unix epoch, the unit of Windows CreationDate. */
+const EPOCH_TICKS = 621355968000000000n;
+
+function createdAtOrAfter(row: ProcessRow, earliest: bigint) {
+ try {
+ return BigInt(row.started) >= earliest;
+ } catch {
+ // An unreadable creation time could be anything, so it counts as possibly part of the tree.
+ return true;
+ }
+}
/**
* Why a process tree did not provably exit: kept as a class so the cleanup retry can tell an
@@ -107,14 +120,18 @@ export function createBackgroundProcesses(deps: BackgroundDependencies) {
* Identity is pid + start time, so a recycled pid is never signalled; the recorded process
* group is included only while one of its recorded members still matches. Idempotent.
*/
- async function killOrphans(records: BackgroundProcessRecord[], signal: AbortSignal) {
+ async function killOrphans(
+ records: BackgroundProcessRecord[],
+ signal: AbortSignal,
+ snapshotTimeoutMs?: number,
+ ) {
const wanted = new Set(
records.flatMap((record) => record.processes.map((p) => `${p.pid}:${p.started}`)),
);
if (!wanted.size) return 0;
const env = deps.env();
const targets = async () => {
- const rows = await snapshot(env, platform);
+ const rows = await snapshot(env, platform, snapshotTimeoutMs);
const matched = rows.filter((row) => wanted.has(`${row.pid}:${row.started}`));
const groups = new Set(
platform === "win32"
@@ -186,5 +203,47 @@ export function createBackgroundProcesses(deps: BackgroundDependencies) {
return remaining.size;
}
- return { terminate, killOrphans };
+ /**
+ * Windows only: processes that may still belong to a retained tree, found by the same rule the
+ * command's own monitor uses (the root pid, then children created after their creator) but
+ * seeded with the root and every recorded pid even when they already exited, so a tree whose
+ * identities were never captured can still be shown to be gone. Check-only: a pid matched by
+ * creation time alone may be an unrelated process that reused it, so nothing is signalled, and
+ * every such match keeps the pause (the safe direction).
+ */
+ async function treeRemains(records: readonly BackgroundProcessRecord[], timeoutMs: number) {
+ const dated = records.filter((record) => record.spawnedAt !== undefined);
+ if (platform !== "win32" || !dated.length) return 0;
+ const rows = await snapshot(deps.env(), platform, timeoutMs);
+ const children = new Map<number, ProcessRow[]>();
+ for (const row of rows) {
+ const list = children.get(row.parent) ?? [];
+ list.push(row);
+ children.set(row.parent, list);
+ }
+ let remaining = 0;
+ for (const record of dated) {
+ const earliest =
+ BigInt(Math.max(0, (record.spawnedAt as number) - SPAWN_MARGIN_MS)) * 10_000n + EPOCH_TICKS;
+ const found = new Set<number>();
+ for (const row of rows)
+ if (row.pid === record.group && createdAtOrAfter(row, earliest)) found.add(row.pid);
+ const queue = [record.group, ...record.processes.map((process) => process.pid)];
+ const visited = new Set<number>();
+ for (let i = 0; i < queue.length; i++) {
+ const parent = queue[i] as number;
+ if (visited.has(parent)) continue;
+ visited.add(parent);
+ for (const row of children.get(parent) ?? []) {
+ if (found.has(row.pid) || !createdAtOrAfter(row, earliest)) continue;
+ found.add(row.pid);
+ queue.push(row.pid);
+ }
+ }
+ remaining += found.size;
+ }
+ return remaining;
+ }
+
+ return { terminate, killOrphans, treeRemains };
}
diff --git a/packages/execution/src/command/background/types.ts b/packages/execution/src/command/background/types.ts
index 9d523af..a6bc21f 100644
--- a/packages/execution/src/command/background/types.ts
+++ b/packages/execution/src/command/background/types.ts
@@ -21,16 +21,28 @@ export interface BackgroundProcessRecord {
/** POSIX process group (= root pid); Windows has none and uses the recorded tree only. */
group: number;
processes: { pid: number; started: string }[];
+ /**
+ * Foreground commands only (ms since epoch, taken before spawn). A Windows tree whose identities
+ * were never captured (snapshot timeout under load) can still be checked later: the root pid and
+ * its descendants created after this moment are the only processes that can belong to it.
+ */
+ spawnedAt?: number;
}
/** Fixed reason codes, so a log line never carries command text, paths or raw OS errors. */
export type BackgroundDrainReason = "cleanup_unconfirmed" | "cleanup_unverified" | "unknown";
export interface BackgroundDrainEvent {
- phase: "paused" | "retrying" | "recovered";
+ /**
+ * `stuck`: automatic checks ran out (or nothing identifies the tree), so the pause stays until a
+ * manual check proves it clean or Pi Bot restarts. Never a release: only `recovered` is.
+ */
+ phase: "paused" | "retrying" | "stuck" | "recovered";
reason: BackgroundDrainReason;
/** The job whose cleanup was not confirmed, when one job caused it. */
jobId?: string;
+ /** The run whose foreground command was not confirmed stopped, when one run caused it. */
+ runId?: string;
/** Cleanup attempts so far; zero for the first failure. */
attempts: number;
/** Processes or groups still found after the last attempt; zero once it is confirmed clean. */
diff --git a/packages/execution/src/command/command-context.ts b/packages/execution/src/command/command-context.ts
index 6f69ff7..646928b 100644
--- a/packages/execution/src/command/command-context.ts
+++ b/packages/execution/src/command/command-context.ts
@@ -28,7 +28,12 @@ export interface CommandDependencies {
background: ReturnType<typeof createBackgroundJobs>;
lifetime: AbortController;
/** `record` carries the failed foreground command's own tree when no job is involved. */
- failDrain(error: ExecError, jobId?: string, record?: BackgroundProcessRecord): void;
+ failDrain(
+ error: ExecError,
+ jobId?: string,
+ record?: BackgroundProcessRecord,
+ runId?: string,
+ ): void;
drainFailed(): boolean;
retainCommand(work: Promise<unknown>, runId: string): void;
adoptForeground(job: import("./background.ts").BackgroundJob): void;
diff --git a/packages/execution/src/command/command-run.ts b/packages/execution/src/command/command-run.ts
index 8ffe937..46d2fed 100644
--- a/packages/execution/src/command/command-run.ts
+++ b/packages/execution/src/command/command-run.ts
@@ -39,7 +39,7 @@ import { executeHostedCommand } from "./foreground-host.ts";
import { runPromotableCommand } from "./foreground-promotion.ts";
import { PERMISSION_OUTPUT_NOTICE, timeoutOutput } from "./output-notices.ts";
import { consumeOutsideSandboxPermit, pinSystemFilters } from "./outside-sandbox.ts";
-import { executeProcess, type ProcessControl } from "./process.ts";
+import { cleanupRecord, executeProcess, type ProcessControl } from "./process.ts";
import { createRollingCommandLog } from "./rolling-command-log.ts";
import { verifyScriptInterpreters } from "./script-interpreters.ts";
import { verifyScriptPins } from "./script-pins.ts";
@@ -362,7 +362,9 @@ async function executePhase(
return pinnedFilters ? { ...direct, pinnedFilters } : direct;
} catch (error) {
if (error instanceof ExecError && error.reason === "cleanup_failed")
- deps.failDrain(error, undefined, control?.record());
+ // The error's own record also covers a tree whose snapshots all timed out before `control`
+ // was published, which left the Windows pause unprovable until a restart.
+ deps.failDrain(error, undefined, cleanupRecord(error) ?? control?.record(), input.runId);
throw error;
} finally {
log?.destroy();
diff --git a/packages/execution/src/command/command.ts b/packages/execution/src/command/command.ts
index d02e111..acb10c3 100644
--- a/packages/execution/src/command/command.ts
+++ b/packages/execution/src/command/command.ts
@@ -17,6 +17,7 @@ import { createCommandRunner } from "./command-run.ts";
import { createCommandTemps } from "./command-temp.ts";
import { commandEnvironment } from "./environment.ts";
import { UnsafeSandboxEnvironmentError } from "./host-environment.ts";
+import { cleanupRecord } from "./process.ts";
import { commandDeadline } from "./run-deadline.ts";
import { secretOutputRedactor } from "./secret-output.ts";
@@ -53,6 +54,21 @@ export function createExec(options: ExecOptions) {
const retiringRuns = new Map<string, Promise<void>>();
let closing: Promise<void> | undefined;
const promoted = new Map<string, import("./background.ts").BackgroundJob>();
+ /**
+ * Temp folders of commands that settled while paused: the unconfirmed tree may still use them,
+ * so they stay pinned until the pause is proven clear, then are released like any other.
+ */
+ const heldPins: string[] = [];
+ const releaseHeldPins = () => {
+ for (const runId of heldPins.splice(0)) temps.unpin(runId);
+ };
+ const unpin = (runId: string) => {
+ if (!background.drainFailed()) return temps.unpin(runId);
+ heldPins.push(runId);
+ void background.whenHealthy().then(releaseHeldPins, () => {
+ // Closing: dispose removes every folder, pinned or not.
+ });
+ };
const dependencies: CommandDependencies = {
options,
sandbox,
@@ -60,8 +76,8 @@ export function createExec(options: ExecOptions) {
violations,
lifetime,
background,
- failDrain(error, jobId, record) {
- background.failDrain(error, jobId, record);
+ failDrain(error, jobId, record, runId) {
+ background.failDrain(error, jobId, record, runId);
},
// The background instance owns the retry; a copy here would outlive its recovery.
drainFailed: () => background.drainFailed(),
@@ -71,12 +87,10 @@ export function createExec(options: ExecOptions) {
work
.catch((error: unknown) => {
if (error instanceof ExecError && error.reason === "cleanup_failed")
- background.failDrain(error);
+ background.failDrain(error, undefined, cleanupRecord(error), runId);
throw error;
})
- .finally(() => {
- if (!background.drainFailed()) temps.unpin(runId);
- }),
+ .finally(() => unpin(runId)),
runId,
);
},
@@ -162,12 +176,10 @@ export function createExec(options: ExecOptions) {
const raw = execute({ ...input, signal })
.catch((error: unknown) => {
if (error instanceof ExecError && error.reason === "cleanup_failed")
- background.failDrain(error);
+ background.failDrain(error, undefined, cleanupRecord(error), input.runId);
throw error;
})
- .finally(() => {
- if (!background.drainFailed()) temps.unpin(input.runId);
- });
+ .finally(() => unpin(input.runId));
track(raw, input.runId);
return commandDeadline(raw, input.timeoutSec, signal, commandLifetime).catch(
(error: unknown) => {
@@ -215,20 +227,34 @@ export function createExec(options: ExecOptions) {
throw new ExecError("command_failed", "cleanup_unconfirmed");
});
},
- /** The run ended: its commands' private temp folder goes (idempotent). */
- releaseRun(runId: string): Promise<void> {
+ /**
+ * The run ended: its commands' private temp folder goes (idempotent). `signal` bounds only the
+ * wait for a paused cleanup; a caller that cannot wait gets the pause's failure instead.
+ */
+ releaseRun(runId: string, signal?: AbortSignal): Promise<void> {
const previous = retiringRuns.get(runId);
if (previous) return previous;
const released = (async () => {
await Promise.allSettled(
[...active].filter(([, owner]) => owner === runId).map(([work]) => work),
);
- if (background.drainFailed()) background.assertHealthy();
+ // While paused the run's folder may still be in use, so the run waits for the proof
+ // (automatic checks, then the person's "Check again") instead of failing its drain: a
+ // failed drain kept the run's folder lease until a restart, so every later step of that
+ // folder timed out (Windows test 2026-11-21). Closing rejects the wait.
+ if (background.drainFailed()) {
+ await background.whenHealthy(signal);
+ releaseHeldPins();
+ }
await temps.releaseRun(runId);
})().finally(() => retiringRuns.delete(runId));
retiringRuns.set(runId, released);
return released;
},
+ /** Commands are paused because a cleanup is unconfirmed: still checking, or out of checks. */
+ commandPause: () => background.pauseState(),
+ /** The person asked to check again; proof is required exactly as for the automatic checks. */
+ recheckCommandPause: () => background.recheck(),
background: {
get: (id: string) => promoted.get(id) ?? background.get(id),
/** Brain restart: stop processes a previous brain recorded (idempotent). */
diff --git a/packages/execution/src/command/process-tree.ts b/packages/execution/src/command/process-tree.ts
index 013d39c..c346253 100644
--- a/packages/execution/src/command/process-tree.ts
+++ b/packages/execution/src/command/process-tree.ts
@@ -22,6 +22,7 @@ const POLL_BLIND_MS = 6_000;
export async function snapshot(
env: NodeJS.ProcessEnv,
platform: NodeJS.Platform,
+ timeoutMs?: number,
): Promise<ProcessRow[]> {
return new Promise((resolve, reject) => {
const windows = platform === "win32";
@@ -48,7 +49,7 @@ export async function snapshot(
ps.stdout.destroy();
ps.unref();
},
- SNAPSHOT_TIMEOUT_MS[windows ? "win32" : "default"],
+ timeoutMs ?? SNAPSHOT_TIMEOUT_MS[windows ? "win32" : "default"],
);
ps.stdout.on("data", (chunk: Buffer) => {
text += chunk.toString("utf8");
diff --git a/packages/execution/src/command/process.ts b/packages/execution/src/command/process.ts
index eb44daf..9f3244d 100644
--- a/packages/execution/src/command/process.ts
+++ b/packages/execution/src/command/process.ts
@@ -22,6 +22,26 @@ export interface ProcessControl {
drained?(): boolean;
}
+/**
+ * A foreground cleanup that could not be confirmed, with the tree it leaves behind: the root pid,
+ * whatever identities the monitor captured (none when every snapshot timed out under load) and the
+ * spawn time, so the retry can still prove the tree gone instead of pausing until a restart.
+ */
+export class ProcessCleanupError extends ExecError {
+ constructor(
+ readonly record:
+ | { group: number; processes: { pid: number; started: string }[]; spawnedAt: number }
+ | undefined,
+ ) {
+ super("command_failed", "cleanup_failed");
+ }
+}
+
+/** The tree a cleanup failure retained, when the failure came from a foreground process. */
+export function cleanupRecord(error: unknown) {
+ return error instanceof ProcessCleanupError ? error.record : undefined;
+}
+
const HostViolationsSchema = z
.array(z.string().max(MAX_VIOLATION_CHARS))
.max(MAX_REPORTED_VIOLATIONS);
@@ -146,7 +166,7 @@ export async function executeProcess(options: {
// retryable monitor fault (found in review).
const late = rootClosed || exitCode !== null || killTask !== undefined;
processFailure ??= late
- ? new ExecError("command_failed", "cleanup_failed")
+ ? cleanupFailed()
: error instanceof ExecError
? error
: new ExecError("command_failed", "process_monitor_failed");
@@ -156,6 +176,12 @@ export async function executeProcess(options: {
spawnedAt,
)
: undefined;
+ const cleanupFailed = () =>
+ new ProcessCleanupError(
+ child.pid
+ ? { group: child.pid, processes: tree?.record().processes ?? [], spawnedAt }
+ : undefined,
+ );
const terminate = () => {
if (killTask) return;
// Neither an escaped session retaining pipes nor failed OS cleanup may hold busy forever.
@@ -347,11 +373,11 @@ export async function executeProcess(options: {
? await tree.members().then(
(members) => members.length,
() => {
- throw new ExecError("command_failed", "cleanup_failed");
+ throw cleanupFailed();
},
)
: 0;
- if (!rootClosed || leftovers) throw new ExecError("command_failed", "cleanup_failed");
+ if (!rootClosed || leftovers) throw cleanupFailed();
drained = true;
for (const flush of flushChannels) flush();
const truncatedOutput = await Promise.race([
diff --git a/packages/execution/src/diagnostics/session.ts b/packages/execution/src/diagnostics/session.ts
index 5d9f0fe..1d4fe81 100644
--- a/packages/execution/src/diagnostics/session.ts
+++ b/packages/execution/src/diagnostics/session.ts
@@ -29,6 +29,8 @@ export interface SandboxDiagnosticCheck {
verify?(): Promise<boolean>;
}
+/** A paused cleanup gets the automatic checks' first round, then the row reports it unconfirmed. */
+const RELEASE_WAIT_MS = 45_000;
const diagnosticError = (error: unknown) =>
error instanceof ExecError
? error.reason === "cleanup_failed"
@@ -196,7 +198,8 @@ export async function createSandboxDiagnosticSession(options: SandboxDiagnosticO
result = row(check.tool, "failed", diagnosticError(error));
} finally {
try {
- await runner.releaseRun(runId);
+ // A self-test must not wait for a paused cleanup the way a run does: it reports it.
+ await runner.releaseRun(runId, AbortSignal.timeout(RELEASE_WAIT_MS));
} catch {
retain = true;
}
diff --git a/packages/execution/src/index.ts b/packages/execution/src/index.ts
index 9ba07b4..64d1e23 100644
--- a/packages/execution/src/index.ts
+++ b/packages/execution/src/index.ts
@@ -13,9 +13,11 @@ export {
externalAgentSandboxConfig,
} from "./agents/external-agent-sandbox.ts";
export type {
+ BackgroundDrainEvent,
BackgroundEndReason,
BackgroundJob,
BackgroundProcessRecord,
+ CommandPauseState,
} from "./command/background.ts";
export { createExec } from "./command/command.ts";
export { commandPaths, discoverCommandPaths } from "./command/command-paths.ts";
diff --git a/packages/execution/src/target/execution-target.ts b/packages/execution/src/target/execution-target.ts
index be9b539..922c9ef 100644
--- a/packages/execution/src/target/execution-target.ts
+++ b/packages/execution/src/target/execution-target.ts
@@ -47,6 +47,9 @@ export interface ExecutionTarget {
};
/** Owner facts only; zero is not a substitute for dispose/drain confirmation. */
activitySnapshot?(): { runningCommands: number; backgroundTasks: number };
+ /** Local only: commands are paused because a previous command was not confirmed stopped. */
+ commandPause?: LocalExec["commandPause"];
+ recheckCommandPause?: LocalExec["recheckCommandPause"];
readonly supportsCommandPromotion?: boolean;
/**
* Operations that always fail on this target whatever the input, so callers can avoid offering
@@ -147,6 +150,8 @@ export function createLocalExecutionTarget(options: LocalExecutionTargetOptions)
return { path: result, ...(stat ? fileIdentity(stat) : { device: null, inode: null }) };
},
activitySnapshot: exec.activitySnapshot,
+ commandPause: exec.commandPause,
+ recheckCommandPause: exec.recheckCommandPause,
isolationStatus: exec.isolationStatus,
runCommand: exec.runCommand,
releaseRun: exec.releaseRun,
diff --git a/packages/i18n/src/sections/runtime.ts b/packages/i18n/src/sections/runtime.ts
index 122ba15..9972174 100644
--- a/packages/i18n/src/sections/runtime.ts
+++ b/packages/i18n/src/sections/runtime.ts
@@ -9,6 +9,15 @@ export const runtimeZh = {
"runtime.auditForceRequested": "强制释放:已请求",
"runtime.auditForceReleased": "强制释放:已释放",
"runtime.auditForceRefused": "强制释放:未能确认退出",
+ "runtime.commandsPausedRetrying":
+ "命令已暂停:Pi Bot 还没能确认上一条命令已经停下,正在自动检查。确认后会自动恢复。",
+ "runtime.commandsPausedStuck":
+ "命令已暂停:Pi Bot 没能确认上一条命令已经停下。可以再检查一次;还是不行,请重启 Pi Bot。",
+ "runtime.commandsRecheck": "再检查一次",
+ "runtime.commandsStillPaused": "还是没能确认,命令仍然暂停。请重启 Pi Bot。",
+ "runtime.auditCommandsPaused": "命令已暂停:上一条命令未确认停下",
+ "runtime.auditCommandsStuck": "命令仍暂停:自动检查没能确认,需要再检查或重启",
+ "runtime.auditCommandsRecovered": "已确认上一条命令停下,命令恢复",
"runtime.continuationPrompt": "有未完成的自动接续,是否继续?",
"runtime.continuationResume": "继续",
"runtime.continuationDiscard": "放弃",
@@ -38,6 +47,16 @@ export const runtimeEn: Record<keyof typeof runtimeZh, string> = {
"runtime.auditForceRequested": "Force release requested",
"runtime.auditForceReleased": "Force release: released",
"runtime.auditForceRefused": "Force release refused: still running",
+ "runtime.commandsPausedRetrying":
+ "Commands are paused: Pi Bot couldn't confirm the previous command stopped and is checking automatically. They resume once it's confirmed.",
+ "runtime.commandsPausedStuck":
+ "Commands are paused: Pi Bot couldn't confirm the previous command stopped. Check again, or restart Pi Bot if that doesn't help.",
+ "runtime.commandsRecheck": "Check again",
+ "runtime.commandsStillPaused": "Still not confirmed, so commands stay paused. Restart Pi Bot.",
+ "runtime.auditCommandsPaused": "Commands paused: previous command not confirmed stopped",
+ "runtime.auditCommandsStuck":
+ "Commands still paused: automatic checks couldn't confirm; check again or restart",
+ "runtime.auditCommandsRecovered": "Previous command confirmed stopped; commands resumed",
"runtime.continuationPrompt": "Some automatic follow-ups didn't finish. Continue them?",
"runtime.continuationResume": "Continue",
"runtime.continuationDiscard": "Discard",
diff --git a/packages/protocol-base/src/core/kernel-api.ts b/packages/protocol-base/src/core/kernel-api.ts
index 6715c7d..5a151bd 100644
--- a/packages/protocol-base/src/core/kernel-api.ts
+++ b/packages/protocol-base/src/core/kernel-api.ts
@@ -235,6 +235,7 @@ export const KernelEventEnvelopeSchema = z.discriminatedUnion("method", [
eventSchema("inbox.changed"),
eventSchema("sidebar.changed"),
eventSchema("runtime.health"),
+ eventSchema("runtime.commands"),
eventSchema("runtime.activeRuns"),
eventSchema("continuations.pending"),
eventSchema("chat.notice"),
diff --git a/packages/protocol-base/src/execution/runtime-health.ts b/packages/protocol-base/src/execution/runtime-health.ts
index 724a84c..2ab30d6 100644
--- a/packages/protocol-base/src/execution/runtime-health.ts
+++ b/packages/protocol-base/src/execution/runtime-health.ts
@@ -15,6 +15,15 @@ export const RuntimeHealthSchema = z
})
.refine((value) => value.healthy === (value.reason === null));
export type RuntimeHealth = z.infer<typeof RuntimeHealthSchema>;
+/**
+ * New commands are paused because Pi Bot could not confirm a previous command stopped:
+ * `retrying` while automatic checks run, `stuck` once they ran out (check again, or restart).
+ * Separate from `RuntimeHealth`, which is sticky until restart; this clears on its own.
+ */
+export const CommandPauseSchema = z.strictObject({
+ paused: z.enum(["retrying", "stuck"]).nullable(),
+});
+export type CommandPause = z.infer<typeof CommandPauseSchema>;
export const RuntimeMethods = {
// The UI pulls the current health once on (re)connect so a missed event is not final.
"runtime.health.get": { params: noParams, result: RuntimeHealthSchema },
@@ -25,10 +34,15 @@ export const RuntimeMethods = {
params: z.strictObject({ botId: IdSchema.optional(), confirmed: z.literal(true) }),
result: RuntimeHealthSchema,
},
+ "runtime.commands.get": { params: noParams, result: CommandPauseSchema },
+ // The person asked to check again. The brain re-checks with the same proof as its automatic
+ // checks; nothing is released without it, so the result may still be paused.
+ "runtime.commands.recheck": { params: noParams, result: CommandPauseSchema },
} as const;
export const RuntimeEvents = {
/** Authoritative snapshot, including parked approvals, deduplicated by run ID. */
"runtime.activeRuns": z.strictObject({ count: z.number().int().nonnegative().safe() }),
// A drain failure is sticky; `botIds` names the Bots whose sessions stayed open.
"runtime.health": RuntimeHealthSchema,
+ "runtime.commands": CommandPauseSchema,
} as const;
diff --git a/packages/protocol-base/src/permissions/audit.ts b/packages/protocol-base/src/permissions/audit.ts
index e0f44db..fd00d58 100644
--- a/packages/protocol-base/src/permissions/audit.ts
+++ b/packages/protocol-base/src/permissions/audit.ts
@@ -133,6 +133,9 @@ export const AuditKindSchema = z.enum([
"runtime.drain_failed",
// The user asked to force-release a failed drain (requested / released / refused).
"runtime.force_release",
+ // New commands paused because a previous command was not confirmed stopped (reasonCode
+ // paused / stuck / recovered); fixed codes only, never command text.
+ "runtime.commands_paused",
"execution.task.changed",
// Bots/groups created from a role, template, profession or imported file; a group file
// exported. Counts and built-in ids only, never personas, norms or skill content.
diff --git a/packages/protocol/src/aggregate/api.ts b/packages/protocol/src/aggregate/api.ts
index 8c1fc83..859cef2 100644
--- a/packages/protocol/src/aggregate/api.ts
+++ b/packages/protocol/src/aggregate/api.ts
@@ -325,6 +325,7 @@ export const EventEnvelopeSchema = z.discriminatedUnion("method", [
eventSchema("providers.loginStep"),
eventSchema("sidebar.changed"),
eventSchema("runtime.health"),
+ eventSchema("runtime.commands"),
eventSchema("runtime.activeRuns"),
eventSchema("continuations.pending"),
eventSchema("computer.step"),
diff --git a/packages/protocol/test/schemas.test.ts b/packages/protocol/test/schemas.test.ts
index fc1286f..38a8933 100644
--- a/packages/protocol/test/schemas.test.ts
+++ b/packages/protocol/test/schemas.test.ts
@@ -3202,6 +3202,18 @@ const methodCases = {
badParams: { botId: id, confirmed: false },
badResult: { healthy: false, reason: null, botIds: [] },
},
+ "runtime.commands.get": {
+ params: undefined,
+ result: { paused: null },
+ badParams: { unexpected: true },
+ badResult: { paused: "unknown" },
+ },
+ "runtime.commands.recheck": {
+ params: undefined,
+ result: { paused: "stuck" },
+ badParams: { unexpected: true },
+ badResult: {},
+ },
} satisfies Cases<MethodParams, MethodResults>;
const hostCases = {
"host.office.render": {
@@ -3882,6 +3894,7 @@ const eventCases = {
payload: { healthy: false, reason: "run_drain_failed", botIds: [id] },
bad: { healthy: false, reason: "unknown", botIds: [] },
},
+ "runtime.commands": { payload: { paused: "retrying" }, bad: { paused: "paused" } },
"runtime.activeRuns": { payload: { count: 1 }, bad: { count: -1 } },
"bots.changed": { payload: { botId: id, reason: "created" }, bad: { unexpected: true } },
"groups.changed": { payload: { groupId: id, reason: "created" }, bad: { unexpected: true } },
diff --git a/packages/runner/src/host.ts b/packages/runner/src/host.ts
index a1f75a5..b0eaa2f 100644
--- a/packages/runner/src/host.ts
+++ b/packages/runner/src/host.ts
@@ -797,9 +797,10 @@ async function attachRunnerSession(options: SessionOptions, detached: () => void
}
}),
);
- handle("runner.command.release", async ({ idempotencyKey, issuedAt, runId }) =>
+ handle("runner.command.release", async ({ idempotencyKey, issuedAt, runId }, context) =>
once(idempotencyKey, issuedAt, async () => {
- await options.target.releaseRun(runId);
+ // A paused cleanup makes the release wait for its proof; the caller's deadline bounds it.
+ await options.target.releaseRun(runId, context.signal);
return null;
}),
);