diff --git a/lib/hosts/session-ops.test.mjs b/lib/hosts/session-ops.test.mjs index ac0d0b97..8e7e7295 100644 --- a/lib/hosts/session-ops.test.mjs +++ b/lib/hosts/session-ops.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; @@ -117,6 +117,42 @@ test("preparePoolProject rejects malformed authenticated inputs without a launch } }); +test("preparePoolProject refuses a clone root inside pi's agent directory", () => withAgentDir(async () => { + const result = await sessionOps.preparePoolProject({ + projectId: "registered-project", creationId: "creation-1", + origin: "https://fixture.invalid/repo.git", cloneRoot: join(process.env.PI_CODING_AGENT_DIR, "skills", "repo"), + }); + assert.equal(result.ok, false); + assert.equal(result.status, 403); + assert.equal(result.code, "agent_dir_read_only"); + + // A root that would hold a not-yet-created agent directory: a cloned `agent/` would become pi's configuration. + const previous = process.env.PI_CODING_AGENT_DIR; + // macOS temp directories sit under the /var symlink, which pool preparation refuses before this check. + const missingParent = join(realpathSync(previous), "missing-pi"); + process.env.PI_CODING_AGENT_DIR = join(missingParent, "agent"); + try { + const holding = await sessionOps.preparePoolProject({ + projectId: "registered-project", creationId: "creation-1", + origin: "https://fixture.invalid/repo.git", cloneRoot: missingParent, + }); + assert.equal(holding.code, "agent_dir_read_only"); + // An existing checkout that holds it (a dotfiles repository at $HOME) only gets sibling worktrees: not refused here. + mkdirSync(missingParent); + const existing = await sessionOps.preparePoolProject({ + projectId: "registered-project", creationId: "creation-1", + origin: "https://fixture.invalid/repo.git", cloneRoot: missingParent, + }); + assert.notEqual(existing.code, "agent_dir_read_only"); + } finally { + process.env.PI_CODING_AGENT_DIR = previous; + } + const root = await sessionOps.preparePoolProject({ + projectId: "registered-project", creationId: "creation-1", origin: "https://fixture.invalid/repo.git", cloneRoot: "/", + }); + assert.equal(root.status, 400, "a filesystem root is invalid, not read-only"); +})); + test("searchSessions accepts the exact query limit and empty queries", () => withAgentDir(async () => { for (const query of ["", " ", '""', "z".repeat(500)]) { assert.deepEqual(await sessionOps.searchSessions(query), { ok: true, value: {} }); diff --git a/lib/hosts/session-ops.ts b/lib/hosts/session-ops.ts index 000a30c0..6414ef6a 100644 --- a/lib/hosts/session-ops.ts +++ b/lib/hosts/session-ops.ts @@ -29,6 +29,8 @@ import { writeSessionFileAtomicSync, } from "../pi/session-files"; import { preparePoolProject, type PreparedPoolProject } from "../pooled-projects"; +import { HostOpError } from "./link-protocol"; +import { assertOutsideAgentDir } from "./workspace-roots"; import { projectIdentityKey, sessionPathKey } from "../paths"; import { hideProject, @@ -802,6 +804,14 @@ export const sessionOps: SessionOps = { || (input.ref !== undefined && typeof input.ref !== "string")) { return fail(400, "invalid_request", "Invalid pool project preparation input"); } + // A clone root inside pi's agent directory or ~/.pi would let a pool clone write pi's configuration (a clone that + // would create a root holding a missing one is refused where it clones). A malformed root is left to the 400. + try { + if (isAbsolute(input.cloneRoot) && resolve(input.cloneRoot) === input.cloneRoot) assertOutsideAgentDir(input.cloneRoot); + } catch (error) { + if (error instanceof HostOpError) return fail(error.status, error.code, error.message); + throw error; + } return preparePoolProject(input); }, }; diff --git a/lib/pooled-projects.test.mjs b/lib/pooled-projects.test.mjs index 25ae43b2..9931ac79 100644 --- a/lib/pooled-projects.test.mjs +++ b/lib/pooled-projects.test.mjs @@ -151,6 +151,20 @@ test("fetches pushed refs from another clone without resetting a dirty checkout" assert.equal(git(f.cloneRoot, "rev-parse", "HEAD"), f.baseCommit); })); +test("a session worktree that would hold pi's agent directory is refused before checkout", () => fixture(async (f) => { + const previous = process.env.PI_CODING_AGENT_DIR; + process.env.PI_CODING_AGENT_DIR = join(worktree(f), "agent"); + try { + const result = await preparePoolProject(f.input); + rejected(result); + assert.equal(result.code, "agent_dir_read_only"); + assert.equal(existsSync(worktree(f)), false); + } finally { + if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previous; + } +})); + test("same creation is idempotent and preserves its dirty worktree", () => fixture(async (f) => { const first = prepared(await preparePoolProject(f.input)); writeFileSync(join(first.cwd, "tracked.txt"), "session edit\n"); diff --git a/lib/pooled-projects.ts b/lib/pooled-projects.ts index b10d5ae3..c391cbc1 100644 --- a/lib/pooled-projects.ts +++ b/lib/pooled-projects.ts @@ -7,6 +7,8 @@ import { cloneDirectoryName, repositoryKey } from "./git-clone"; import { cloneRepository, withProjectReservation } from "./project-clone"; import { createGitEnvironment } from "./project-command-env"; import type { OpResult } from "./hosts/session-ops"; +import { HostOpError } from "./hosts/link-protocol"; +import { assertRemovableOutsideAgentDir } from "./hosts/workspace-roots"; export interface PreparedPoolProject { cwd: string; @@ -81,6 +83,14 @@ function hasHttpsCredentials(origin: string): boolean { } } +/** Refuses a path that is, lies in, or would hold pi's agent directory or ~/.pi, as a preparation error. */ +function outsideAgentDir(path: string): void { + try { assertRemovableOutsideAgentDir(path); } catch (error) { + if (error instanceof HostOpError) throw new PreparationError(error.code, error.message, error.status); + throw error; + } +} + async function git(cwd: string, ...args: string[]): Promise { const { stdout } = await exec("git", ["-C", cwd, ...args], { encoding: "utf8", @@ -157,6 +167,8 @@ async function prepare(input: { } if (!existingClone) { + // A new root that would hold a missing agent directory or ~/.pi: a cloned `agent/` would become pi's configuration. + outsideAgentDir(cloneRoot); // Clone into the helper's exclusively mkdir-acquired final root. A rename // cannot publish safely here: POSIX rename may replace somebody else's empty reservation. const cloned = await cloneRepository({ origin, target: cloneRoot }); @@ -218,6 +230,7 @@ async function prepare(input: { } // Fetch the remote ref itself, not a possibly unpublished local branch. Never reset or clean. + outsideAgentDir(cwd); // the session worktree is checked out at cwd: it must not land in or around the agent directory await fetchRemoteRef(cloneRoot, ref ?? "HEAD"); const baseCommit = await git(cloneRoot, "rev-parse", "--verify", "FETCH_HEAD^{commit}"); await mkdir(sessionRoot, { recursive: true }); diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 4e53b636..cd2ad152 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -1087,14 +1087,222 @@ test("terminal failures, new runs, aborts and idle reconciliation cannot revive await wrapper.send({ type: "get_state" }); assertCleared(); assert.equal(wrapper.getStreamSnapshot().isPromptRunning, false); - seed(); + // A failed prompt from an idle session clears output left from before it (no run owns it). + emit({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text: "old" }] } }); + emit({ type: "tool_execution_start", toolCallId: "old-tool", toolName: "bash" }); failPrompt = true; await assert.rejects(wrapper.send({ type: "prompt", message: "retry" }), /prompt rejected/); assertCleared(); + assert.equal(wrapper.isRunning(), false); await wrapper.destroyAndWait(); assert.equal(wrapper.getStreamSnapshot().isStreaming, false); }); +const REFUSAL = "Agent is already processing."; + +/** A session whose prompts stay unanswered until the test settles them through `held`; frames can arrive meanwhile. */ +function heldPromptSession(t, isStreaming = true) { + const held = []; + const session = snapshotSession(t, (command) => { + if (command.type === "prompt") return new Promise((resolve, reject) => { held.push({ resolve, reject }); }); + if (command.type === "get_state") return Promise.resolve({ sessionId: "refusal", isStreaming, isCompacting: false }); + return Promise.resolve({}); + }); + return { ...session, held }; +} + +test("pi refusing a prompt during a run (already processing) keeps that run, its output and its grace window", async (t) => { + const { wrapper, emit, held } = heldPromptSession(t, false); + emit({ type: "agent_start" }); + emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "working" }] } }); + emit({ type: "tool_execution_start", toolCallId: "live-tool", toolName: "bash" }); + const refused = wrapper.send({ type: "prompt", message: "too soon" }); + emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "while in flight" }] } }); + held[0].reject(new Error(REFUSAL)); + await assert.rejects(refused, /already processing/); + const snapshot = wrapper.getStreamSnapshot(); + assert.equal(wrapper.isRunning(), true); + assert.equal(snapshot.isStreaming, true); + assert.equal(snapshot.isPromptRunning, true); + assert.equal(snapshot.responseObserved, true); + assert.equal(snapshot.toolEvents[0].toolCallId, "live-tool"); + + // Between continuation turns pi reports idle; the grace window must still hold the run after a refusal. + emit({ type: "agent_end", isTerminal: false }); + const between = wrapper.send({ type: "prompt", message: "between turns" }); + held[1].reject(new Error(REFUSAL)); + await assert.rejects(between, /already processing/); + assert.equal((await wrapper.send({ type: "get_state" })).isPromptRunning, true); + // The idle read above left only promptRunning and the grace window; a refusal now must not settle the run either. + const afterRead = wrapper.send({ type: "prompt", message: "after the read" }); + held[2].reject(new Error(REFUSAL)); + await assert.rejects(afterRead, /already processing/); + assert.equal(wrapper.getStreamSnapshot().isPromptRunning, true); +}); + +test("a failed prompt that joins a run (streamingBehavior) or runs an extension command beside it leaves the run alone", async (t) => { + const { wrapper, emit, held } = heldPromptSession(t); + emit({ type: "agent_start" }); + emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "working" }] } }); + emit({ type: "tool_execution_start", toolCallId: "live-tool", toolName: "bash" }); + const joined = wrapper.send({ type: "prompt", message: "/cmd", streamingBehavior: "followUp" }); + held[0].reject(new Error("request_too_large")); + await assert.rejects(joined, /request_too_large/); + assert.equal(wrapper.isRunning(), true); + assert.equal(wrapper.getStreamSnapshot().toolEvents[0].toolCallId, "live-tool"); + + const command = wrapper.send({ type: "prompt", message: "/extension-command" }); + held[1].resolve({ agentInvoked: false }); + assert.deepEqual(await command, { agentInvoked: false }); + assert.equal(wrapper.isRunning(), true); + assert.equal(wrapper.getStreamSnapshot().responseObserved, true, "the run's evidence stays"); + assert.equal(wrapper.getStreamSnapshot().toolEvents[0].toolCallId, "live-tool"); + + // An idle prompt still in flight owns promptRunning: a failed streamingBehavior prompt must not settle it. + const idle = heldPromptSession(t, false); + const first = idle.wrapper.send({ type: "prompt", message: "first" }); + const queued = idle.wrapper.send({ type: "prompt", message: "/cmd", streamingBehavior: "followUp" }); + idle.held[1].reject(new Error("request_too_large")); + await assert.rejects(queued, /request_too_large/); + assert.equal(idle.wrapper.isRunning(), true); + idle.held[0].resolve({ agentInvoked: true }); + await first; +}); + +test("a prompt pi takes after the run it joined ended starts its own run: the old run's answer is not its evidence", async (t) => { + const { wrapper, emit, held } = heldPromptSession(t, false); + emit({ type: "agent_start" }); + const next = wrapper.send({ type: "prompt", message: "next question" }); + emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "late old answer" }] } }); + emit({ type: "agent_end", isTerminal: true }); + held[0].resolve({ agentInvoked: true }); + await next; + const state = await wrapper.send({ type: "get_state" }); + assert.equal(state.responseObserved, false); + assert.equal(state.isPromptRunning, true, "its agent_start is awaited"); + + // Its run starts and answers before the ack arrives: the ack must not reset that run's evidence. + const early = heldPromptSession(t); + early.emit({ type: "agent_start" }); + const taken = early.wrapper.send({ type: "prompt", message: "next question" }); + early.emit({ type: "agent_end", isTerminal: true }); + early.emit({ type: "agent_start" }); + early.emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "new answer" }] } }); + early.held[0].resolve({ agentInvoked: true }); + await taken; + assert.equal(early.wrapper.getStreamSnapshot().responseObserved, true); +}); + +test("a refused prompt leaves a run that started meanwhile, ends with one that ended, and keeps an earlier prompt's pending start", async (t) => { + // Idle when sent; another tab's run starts before pi refuses this prompt. + const started = heldPromptSession(t); + const raced = started.wrapper.send({ type: "prompt", message: "raced" }); + started.emit({ type: "agent_start" }); + started.emit({ type: "tool_execution_start", toolCallId: "other-tab", toolName: "bash" }); + started.held[0].reject(new Error(REFUSAL)); + await assert.rejects(raced, /already processing/); + assert.equal(started.wrapper.isRunning(), true); + assert.equal(started.wrapper.getStreamSnapshot().toolEvents[0].toolCallId, "other-tab"); + + // Running when sent; the run ends before the refusal: the session is idle. + const ended = heldPromptSession(t, false); + ended.emit({ type: "agent_start" }); + const afterEnd = ended.wrapper.send({ type: "prompt", message: "too soon" }); + ended.emit({ type: "agent_end", isTerminal: true }); + ended.held[0].reject(new Error(REFUSAL)); + await assert.rejects(afterEnd, /already processing/); + assert.equal(ended.wrapper.isRunning(), false); + + // Prompt A is acked and waits for agent_start when B, sent meanwhile, is refused: A's pending start stays. + const pending = heldPromptSession(t, false); + const a = pending.wrapper.send({ type: "prompt", message: "a" }); + const b = pending.wrapper.send({ type: "prompt", message: "b" }); + pending.held[0].resolve({ agentInvoked: true }); + await a; + pending.held[1].reject(new Error(REFUSAL)); + await assert.rejects(b, /already processing/); + assert.equal((await pending.wrapper.send({ type: "get_state" })).isPromptRunning, true, "A's agent_start is still awaited"); + + // The run ends while B is in flight, then C is acked: B's refusal leaves C's pending start. + const later = heldPromptSession(t, false); + later.emit({ type: "agent_start" }); + const b2 = later.wrapper.send({ type: "prompt", message: "b" }); + later.emit({ type: "agent_end", isTerminal: true }); + const c2 = later.wrapper.send({ type: "prompt", message: "c" }); + later.held[1].resolve({ agentInvoked: true }); + await c2; + later.held[0].reject(new Error(REFUSAL)); + await assert.rejects(b2, /already processing/); + assert.equal((await later.wrapper.send({ type: "get_state" })).isPromptRunning, true, "C's agent_start is still awaited"); +}); + +test("an idle prompt's refusal leaves a later prompt that is in flight, or acked and awaiting its start", async (t) => { + const inFlight = heldPromptSession(t, false); + const b = inFlight.wrapper.send({ type: "prompt", message: "b" }); + const c = inFlight.wrapper.send({ type: "prompt", message: "c" }); + inFlight.held[0].reject(new Error("No API key")); + await assert.rejects(b, /No API key/); + assert.equal(inFlight.wrapper.isRunning(), true, "C is still in flight"); + inFlight.held[1].resolve({ agentInvoked: true }); + await c; + + const acked = heldPromptSession(t, false); + const b2 = acked.wrapper.send({ type: "prompt", message: "b" }); + const c2 = acked.wrapper.send({ type: "prompt", message: "c" }); + acked.held[1].resolve({ agentInvoked: true }); + await c2; + acked.held[0].reject(new Error("No API key")); + await assert.rejects(b2, /No API key/); + assert.equal((await acked.wrapper.send({ type: "get_state" })).isPromptRunning, true, "C's agent_start is still awaited"); +}); + +test("an extension command acked after the prompt it joined failed leaves the session idle", async (t) => { + const { wrapper, held } = heldPromptSession(t, false); + const a = wrapper.send({ type: "prompt", message: "a" }); + const b = wrapper.send({ type: "prompt", message: "/extension-command" }); + held[0].reject(new Error("No API key")); + await assert.rejects(a, /No API key/); + held[1].resolve({ agentInvoked: false }); + assert.deepEqual(await b, { agentInvoked: false }); + assert.equal(wrapper.isRunning(), false); +}); + +test("two prompts refused in turn, in either order, leave the session idle", async (t) => { + for (const order of [[0, 1], [1, 0]]) { + const { wrapper, held } = heldPromptSession(t, false); + const sent = [wrapper.send({ type: "prompt", message: "b" }), wrapper.send({ type: "prompt", message: "c" })]; + for (const index of order) { + held[index].reject(new Error("No API key")); + await assert.rejects(sent[index], /No API key/); + } + assert.equal(wrapper.isRunning(), false, `order ${order}`); + } +}); + +test("a prompt refused during compaction leaves the session idle once compaction ends", async (t) => { + const { wrapper, emit, held } = heldPromptSession(t, false); + emit({ type: "auto_compaction_start" }); + emit({ type: "tool_execution_start", toolCallId: "compaction-tool", toolName: "bash" }); + const refused = wrapper.send({ type: "prompt", message: "while compacting" }); + held[0].reject(new Error(REFUSAL)); + await assert.rejects(refused, /already processing/); + assert.equal(wrapper.getStreamSnapshot().toolEvents[0]?.toolCallId, "compaction-tool"); + assert.equal(wrapper.getStreamSnapshot().isPromptRunning, false); + emit({ type: "auto_compaction_end" }); + assert.equal(wrapper.isRunning(), false); +}); + +test("a prompt ack timeout during a run still recycles the unresponsive child", async (t) => { + const { RpcCommandTimeoutError } = await import("./pi/rpc-process.ts"); + const { wrapper, emit } = snapshotSession(t, async (command) => { + if (command.type === "prompt") throw new RpcCommandTimeoutError("prompt", 30000); + return {}; + }); + emit({ type: "agent_start" }); + await assert.rejects(wrapper.send({ type: "prompt", message: "lost" }), (error) => error.code === "session_unresponsive"); + assert.equal(wrapper.isAlive(), false); +}); + test("session identity changes invalidate the stream epoch and all prior partial output", async (t) => { let sessionId = "identity-before"; const { wrapper, emit } = snapshotSession(t, async (command) => { @@ -1242,14 +1450,14 @@ test("a new prompt cannot reuse old response evidence before agent_start", async emit({ type: "agent_start" }); emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "old answer" }] } }); assert.equal(wrapper.getStreamSnapshot().responseObserved, true); + // Sent during the run, the prompt leaves that run's evidence until pi takes it (pi refuses it while the run lasts). const pending = wrapper.send({ type, message: "next question" }); - assert.equal(wrapper.getStreamSnapshot().responseObserved, false); // An old completion while the prompt is in flight belongs to the earlier turn. emit({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "late old answer" }] } }); emit({ type: "agent_end", isTerminal: true }); - assert.equal(wrapper.getStreamSnapshot().responseObserved, false); release(); await pending; + assert.equal(wrapper.getStreamSnapshot().responseObserved, false); emit({ type: "agent_start" }); emit({ type: "agent_end", isTerminal: true }); assert.equal((await wrapper.send({ type: "get_state" })).responseObserved, false); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index f8a5a88f..a83d4c1d 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -411,6 +411,8 @@ export class AgentSessionWrapper { /** Positive evidence for this run, retained after native completion but before disk append. */ private responseObserved = false; private responseRunActive = false; + /** agent_start frames seen: a prompt acknowledged after one arrived knows its run already started. */ + private runStarts = 0; private idleTimer: ReturnType | null = null; /** Lazily-armed deadline for tearing down a session nobody is watching. */ private reapTimer: ReturnType | null = null; @@ -930,6 +932,7 @@ export class AgentSessionWrapper { switch (event.type) { case "agent_start": + this.runStarts += 1; this.unsettled = true; this.promptRunning = true; this.streaming = true; @@ -2087,6 +2090,15 @@ export class AgentSessionWrapper { } } + /** A failed prompt's last word: `promptRunning` with no run, compaction, pending start, continuation window or other + * prompt in flight belongs to nobody (two prompts refused in turn leave it so), and would keep the session running. */ + private settleOrphanedPrompt(ownDispatches: number): void { + if (!this.promptRunning || this.streaming || this.compacting || this.awaitingAgentStart + || this.promptDispatchPendingCount > ownDispatches || Date.now() < this.continuationGraceUntil) return; + this.promptRunning = false; + notifyRunningChange(); + } + private async dispatchCommand(command: Record, preserveUnknownDelivery = false, correlationKey: object = command): Promise { const type = command.type as string; @@ -2101,13 +2113,17 @@ export class AgentSessionWrapper { switch (type) { case "prompt": { const streamingBehavior = command.streamingBehavior as "steer" | "followUp" | undefined; - if (!streamingBehavior) { + // pi refuses a bare prompt during a run ("already processing"). Sent while a run, compaction or another + // prompt is active, the prompt leaves that state alone; only pi taking it (the run had ended) starts its own. + const joinsRun = !streamingBehavior && (this.streaming || this.promptRunning || this.compacting); + const runStarts = this.runStarts; + if (!streamingBehavior) this.promptDispatchPendingCount += 1; + if (!streamingBehavior && !joinsRun) { this.responseObserved = false; this.responseRunActive = false; if (!this.isRunning()) this.clearLiveSnapshots(); this.streamSequence += 1; this.promptRunning = true; - this.promptDispatchPendingCount += 1; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0; this.continuationGraceUntil = 0; @@ -2124,6 +2140,22 @@ export class AgentSessionWrapper { ...(isClientMessageId(command.clientMessageId) ? { clientMessageId: command.clientMessageId } : {}), ...(isRecord(command.origin) ? { origin: command.origin } : {}), }, PROMPT_ACK_TIMEOUT_MS, correlationKey); + if (joinsRun) { + // An extension command ran beside the run (agentInvoked:false), or a run already started: nothing to start. + if (ack?.agentInvoked !== false && this.runStarts === runStarts) { + this.responseObserved = false; + this.responseRunActive = false; + this.promptRunning = true; + this.awaitingAgentStart = true; + this.awaitingAgentStartDeadline = Date.now() + AWAITING_AGENT_START_TIMEOUT_MS; + this.continuationGraceUntil = 0; + notifyRunningChange(); + } + if (ack?.agentInvoked !== false) return null; + // A command that ran beside a prompt which failed meanwhile is the last one out of a promptRunning nobody owns. + this.settleOrphanedPrompt(1); + return ack; + } // Slash commands fully consumed by a builtin report agentInvoked:false // in the ack itself — no prompt_result frame follows. if (ack?.agentInvoked === false && !streamingBehavior) { @@ -2143,6 +2175,15 @@ export class AgentSessionWrapper { if (preserveUnknownDelivery && error instanceof RpcCommandTimeoutError) { throw new WebRpcError("The initial prompt may have reached its session; check that session before sending it again.", "host_offline", "unknown"); } + if (!(error instanceof RpcCommandTimeoutError)) { + // A prompt that joined a run never touched its state. An idle prompt leaves the state to a run that started + // meanwhile (another tab or server), a compaction, or a prompt still in flight or awaiting its agent_start. + const inFlight = streamingBehavior ? 0 : 1; + if (streamingBehavior || joinsRun || this.streaming || this.compacting || this.awaitingAgentStart || this.promptDispatchPendingCount > inFlight) { + this.settleOrphanedPrompt(inFlight); + throw error; + } + } this.promptRunning = false; this.awaitingAgentStart = false; this.awaitingAgentStartDeadline = 0;