mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-16 13:24:55 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c54bc39e79 | ||
|
|
228e6f75ea |
@@ -150,13 +150,12 @@ Users can also detach an existing subagent from the subagents track. Detach is d
|
||||
|
||||
`notifyOnFinish` defaults to `true` for agent-scoped creation and prompt follow-ups because most delegated work needs to report back to the creating agent. Set it to `false` for explicit reporting or no completion callback.
|
||||
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. Idle recipients retain the two-second quiet window. While a recipient has a running or starting turn (including compaction), messages stay queued across quiet windows and are delivered together after that turn settles, including failure or cancellation. A ready batch is released when the daemon observes the recipient settle; the two-second timer also retries it. Agent callers using `steer`, including the default, wait for the turn to end; only explicit `interrupt` replaces a running turn. An explicit interrupt or a command the provider accepts out of band runs before earlier queued messages. Those messages stay queued and are delivered after the running or replacement turn ends. Human prompts dispatch directly with their existing behavior. Conflicting session-mode choices retain separate ordered dispatches.
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch, allowing a child to report and finish in the same two-second quiet window. Human prompts dispatch directly. Conflicting explicit interruption or session-mode choices retain separate ordered dispatches.
|
||||
|
||||
The pending message window is in memory. Clean shutdown flushes it before closing agents; an abrupt
|
||||
crash can lose queued prompts. A durable send receipt remains pending until actual dispatch
|
||||
acknowledgment, so a lost window never becomes a completed receipt. Completion waits cover queued
|
||||
admission within their original timeout and cancellation scope, and return permission checkpoints
|
||||
while messages are waiting.
|
||||
admission within their original timeout and cancellation scope.
|
||||
|
||||
Finish notification intent has a separate daemon-owned lifetime. The finish-subscriptions module
|
||||
persists caller, child, host, and ownership policy through an injectable store; its JSON adapter uses
|
||||
|
||||
@@ -6,7 +6,7 @@ Do not replace the Linux implementation with `fs.watch({ recursive: true })`. No
|
||||
|
||||
Closing an observation must remain safe after its root is renamed or removed. Workspace archive removes owned worktrees while releasing observation references, so teardown cannot assume the watched path still exists.
|
||||
|
||||
`unsubscribe()` is an awaited barrier. Once it resolves, no scan, reconciliation, queued event, native handle, or callback may remain. `updateIgnore()` is the equivalent barrier for excluded paths: events queued below a newly excluded root cannot be delivered after it resolves. Treat path disappearance while scanning, attaching, or receiving a watcher error as rename/archive churn. Surface permission and resource errors so WorkspaceGit can enter bounded polling. `subscribe()` accepts an abort signal; aborting it before it resolves stops the startup scan and rejects. WorkspaceGit aborts every subscription that misses its setup deadline, because an abandoned scan otherwise keeps walking the tree. A timed-out directory retries on the recovery ladder (30 seconds doubling to five minutes), and each consecutive timeout keeps doubling the delay up to one hour. Under sustained CPU load the next scan misses the deadline too, and each attempt repeats the full scan. An accepted subscription resets the timeout streak. Degraded polling keeps its own cadence throughout.
|
||||
`unsubscribe()` is an awaited barrier. Once it resolves, no scan, reconciliation, queued event, native handle, or callback may remain. `updateIgnore()` is the equivalent barrier for excluded paths: events queued below a newly excluded root cannot be delivered after it resolves. Treat path disappearance while scanning, attaching, or receiving a watcher error as rename/archive churn. Surface permission and resource errors so WorkspaceGit can enter bounded polling.
|
||||
|
||||
Linux topology repair is trailing-debounced and scoped to the renamed path. A file rename needs one classification stat; a new or moved directory scans only its subtree. Full-tree scans are reserved for startup and ignore-set replacement. A subscription reports changes after `subscribe()` resolves, not the files that already existed. macOS FSEvents can still replay writes made moments before the stream started. Consumers read their initial state after `subscribe()` resolves; WorkspaceGit re-reads its checkout once observation setup completes, because its first refresh runs in parallel with setup. The Linux startup scan therefore emits nothing; only a scoped reconciliation of new topology reports files found before their directory's watcher was installed. Startup creates made every cold diff compute and discard a first revision. Benchmark startup cost with pre-populated trees.
|
||||
|
||||
|
||||
@@ -29,7 +29,6 @@ The worker writes `$PASEO_HOME/terminal-worker/<pid>.json` (owner-only) with its
|
||||
- Workers never query their own birth time or command line. Readers accept legacy identity fields but ignore them. Daemons through 0.15.1 report new records unreadable and cannot adopt them.
|
||||
- Windows terminal programs have no recorded birth time and terminal lifecycle operations never launch PowerShell. Linux and macOS retain program birth-time checks through `ps` with `LC_ALL=C`; Linux also walks sessions to find surviving jobs.
|
||||
- Unix socket paths have a byte budget (103 on macOS, 107 on Linux). Long dev homes use an owner-only fallback under `$TMPDIR/paseo-<uid>/` or `/tmp/paseo-<uid>/`. An existing directory must be a real `0700` directory owned by you; a shared root is never chmodded.
|
||||
- A home on a filesystem that refuses Unix sockets (AFS, some network mounts) passes those checks and then fails the bind with `EPERM`, `EACCES`, `EOPNOTSUPP` or `ENOTSUP`. The worker moves on to the next directory on those codes only; any other listen error fails the start. The record carries the path the worker bound, so nothing else recomputes it.
|
||||
- A kill cleanup that cannot confirm every process gone writes `closing-<recordId>.json` beside the worker record. The worker rewrites its own record whenever a terminal starts or exits, so the kill intent has to live in a file it never writes. A closing record is never adopted; the next stop or start retries it.
|
||||
- An unreadable record of either kind makes `daemon status` and a kill restart fail with its path: a kill cleanup that met it could not check what it names, and leaves nothing else behind. A read that fails with `EPERM`, `EBUSY` or `EACCES` is retried for 250ms first: on Windows, opening a record while the worker renames its new copy over it fails that way for a moment.
|
||||
|
||||
|
||||
@@ -121,7 +121,7 @@ export async function startIsolatedHostDaemon(
|
||||
serverId: string,
|
||||
options: IsolatedHostDaemonOptions = {},
|
||||
): Promise<IsolatedHostDaemon> {
|
||||
let port = await getAvailableHostDaemonPort();
|
||||
const port = await getAvailableHostDaemonPort();
|
||||
|
||||
const metroPort = process.env.E2E_METRO_PORT;
|
||||
if (!metroPort) throw new Error("E2E_METRO_PORT is required to start an isolated host daemon");
|
||||
@@ -231,25 +231,8 @@ export async function startIsolatedHostDaemon(
|
||||
}
|
||||
};
|
||||
|
||||
// The reserved port is released before the daemon binds it, so another
|
||||
// process can take it in between. Only the first start picks a new port:
|
||||
// restart() keeps the endpoint the app already knows.
|
||||
const startOnFreePort = async (): Promise<void> => {
|
||||
for (let attempt = 1; ; attempt += 1) {
|
||||
try {
|
||||
await spawnDaemon();
|
||||
return;
|
||||
} catch (error) {
|
||||
const lostPort = error instanceof Error && error.message.includes("EADDRINUSE");
|
||||
if (!lostPort || attempt === 3) throw error;
|
||||
await stopDaemon();
|
||||
port = await getAvailableHostDaemonPort();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
await startOnFreePort();
|
||||
await spawnDaemon();
|
||||
} catch (error) {
|
||||
await stopDaemon();
|
||||
if (!options.preserveHome) {
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
toolbarSlot,
|
||||
type ToolbarGlyphs,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import { shortModelLabel } from "./utils";
|
||||
|
||||
const SNAP_POINTS = ["80%", "90%"];
|
||||
const MODEL_LIST_TOP_INSET = 4;
|
||||
@@ -67,6 +66,11 @@ interface CompactModelSheetProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
function shortModelLabel(label: string): string {
|
||||
const separatorIndex = label.lastIndexOf("/");
|
||||
return separatorIndex === -1 ? label : label.slice(separatorIndex + 1);
|
||||
}
|
||||
|
||||
function resolveModelSheetProfileActions(
|
||||
onCreateProfile: ((seed: AgentProfileSeed) => void) | undefined,
|
||||
onEditProfile: ((profileId: string) => void) | undefined,
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
getAgentControlHintKey,
|
||||
normalizeModelId,
|
||||
resolveAgentModelSelection,
|
||||
shortModelLabel,
|
||||
} from "./utils";
|
||||
|
||||
describe("getAgentControlHintKey", () => {
|
||||
@@ -252,19 +251,3 @@ describe("resolveAgentModelSelection", () => {
|
||||
expect(selection.displayThinking).toBe("Max");
|
||||
});
|
||||
});
|
||||
|
||||
describe("shortModelLabel", () => {
|
||||
it("drops a provider namespace", () => {
|
||||
expect(shortModelLabel("openrouter/gpt-5.5")).toBe("gpt-5.5");
|
||||
expect(shortModelLabel("openrouter/google/gemini-2.5-flash")).toBe("gemini-2.5-flash");
|
||||
});
|
||||
|
||||
it("keeps slashes inside a display name", () => {
|
||||
expect(shortModelLabel("DeepSeek V4.1 Flash (~6-7 tok/s, 56/56)")).toBe(
|
||||
"DeepSeek V4.1 Flash (~6-7 tok/s, 56/56)",
|
||||
);
|
||||
expect(shortModelLabel("llama-swap/DeepSeek V4.1 Flash (56/56)")).toBe(
|
||||
"DeepSeek V4.1 Flash (56/56)",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -35,12 +35,6 @@ export function normalizeModelId(modelId: string | null | undefined): string | n
|
||||
return normalized;
|
||||
}
|
||||
|
||||
// Drops a provider namespace ("openrouter/gpt-5.5" -> "gpt-5.5") for the compact trigger.
|
||||
// A namespace segment has no spaces, so slashes inside a display name ("52/56") survive.
|
||||
export function shortModelLabel(label: string): string {
|
||||
return label.replace(/^(?:[^\s/]+\/)+(?=\S)/, "");
|
||||
}
|
||||
|
||||
export function getFeatureHighlightColor(featureId: string): FeatureHighlightColor {
|
||||
switch (featureId) {
|
||||
case FAST_MODE_FEATURE_ID:
|
||||
|
||||
@@ -762,7 +762,7 @@ function ChatAgentContent({
|
||||
});
|
||||
const reportAttentionError = useCallback(
|
||||
(error: unknown) => {
|
||||
toastApi.error(toErrorMessage(error));
|
||||
toastApi.show(String(error), { variant: "error", durationMs: null });
|
||||
},
|
||||
[toastApi],
|
||||
);
|
||||
|
||||
@@ -47,7 +47,7 @@ export function addSendOptions(cmd: Command): Command {
|
||||
.addOption(
|
||||
new Option(
|
||||
"--behavior <behavior>",
|
||||
"Active-turn behavior (agent default: steer waits for turn end; otherwise: interrupt)",
|
||||
"Active-turn behavior (agent default: steer; otherwise: interrupt)",
|
||||
).choices(["interrupt", "steer"]),
|
||||
)
|
||||
.option("--no-wait", "Return immediately without waiting for completion");
|
||||
@@ -218,7 +218,7 @@ export async function runSendCommand(
|
||||
status: receipt.deliveryStatus ?? "sent",
|
||||
message:
|
||||
receipt.deliveryStatus === "queued"
|
||||
? "Message queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested"
|
||||
? "Message queued for delivery after two quiet seconds"
|
||||
: "Message sent, not waiting for completion",
|
||||
},
|
||||
schema: agentSendSchema,
|
||||
|
||||
@@ -449,7 +449,7 @@ test("a timed-out subscription rejects and cannot replay on reconnect", async ()
|
||||
h.open();
|
||||
await connecting;
|
||||
const observation = h.client.observeAgents({ timeout: 10 });
|
||||
await expect(observation.ready).rejects.toMatchObject({ code: "DAEMON_REQUEST_TIMEOUT" });
|
||||
await expect(observation.ready).rejects.toThrow(/timed out|timeout/i);
|
||||
await observation.release();
|
||||
const reconnecting = h.client.connect();
|
||||
h.open();
|
||||
|
||||
@@ -1492,7 +1492,7 @@ test("keeps the transport connected when a session RPC ping times out", async ()
|
||||
await connectPromise;
|
||||
expect(client.getConnectionState().status).toBe("connected");
|
||||
|
||||
await expect(client.ping({ timeoutMs: 1 })).rejects.toThrow("No response to ping after");
|
||||
await expect(client.ping({ timeoutMs: 1 })).rejects.toThrow("Timeout waiting for message");
|
||||
|
||||
expect(client.getConnectionState().status).toBe("connected");
|
||||
});
|
||||
@@ -1541,9 +1541,7 @@ test("bounds the wait for push token revocation", async () => {
|
||||
await connectPromise;
|
||||
|
||||
const revocation = client.unregisterPushToken("ExponentPushToken[test-device]");
|
||||
const rejection = expect(revocation).rejects.toThrow(
|
||||
"No response to push.unregister.request after 2000ms",
|
||||
);
|
||||
const rejection = expect(revocation).rejects.toThrow("Timeout waiting for message (2000ms)");
|
||||
await vi.advanceTimersByTimeAsync(1_999);
|
||||
expect(client.getConnectionState().status).toBe("connected");
|
||||
|
||||
@@ -1552,30 +1550,6 @@ test("bounds the wait for push token revocation", async () => {
|
||||
expect(client.getConnectionState().status).toBe("connected");
|
||||
});
|
||||
|
||||
test("identifies the request when marking an agent as read times out", async () => {
|
||||
useHeartbeatClock();
|
||||
const transport = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "clsk_attention_timeout",
|
||||
reconnect: { enabled: false },
|
||||
transportFactory: () => transport.transport,
|
||||
});
|
||||
clients.push(client);
|
||||
const connected = client.connect();
|
||||
transport.triggerOpen();
|
||||
await connected;
|
||||
|
||||
const outcome = client.clearAgentAttention("agent-1").catch((error: unknown) => error);
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(await outcome).toMatchObject({
|
||||
name: "DaemonConnectionError",
|
||||
code: "DAEMON_REQUEST_TIMEOUT",
|
||||
message: "No response to clear_agent_attention after 60000ms",
|
||||
});
|
||||
expect(client.isConnected).toBe(true);
|
||||
});
|
||||
|
||||
test("defaults session RPC waiters to sixty seconds", async () => {
|
||||
useHeartbeatClock();
|
||||
const logger = createMockLogger();
|
||||
@@ -1620,7 +1594,7 @@ test("defaults session RPC waiters to sixty seconds", async () => {
|
||||
expect(settled).toBe(false);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(responsePromise).rejects.toThrow("No response to fetch_agent_request after 60000ms");
|
||||
await expect(responsePromise).rejects.toThrow("Timeout waiting for message (60000ms)");
|
||||
});
|
||||
|
||||
test("honors explicit fetchAgent timeout below the session RPC default", async () => {
|
||||
@@ -1668,7 +1642,7 @@ test("honors explicit fetchAgent timeout below the session RPC default", async (
|
||||
expect(settled).toBe(false);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(responsePromise).rejects.toThrow("No response to fetch_agent_request after 5000ms");
|
||||
await expect(responsePromise).rejects.toThrow("Timeout waiting for message (5000ms)");
|
||||
});
|
||||
|
||||
test("preserves legacy fetchAgent id overload", async () => {
|
||||
@@ -1832,9 +1806,7 @@ test("honors explicit fetchAgentTimeline timeout below the session RPC default",
|
||||
expect(settled).toBe(false);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(responsePromise).rejects.toThrow(
|
||||
"No response to fetch_agent_timeline_request after 2000ms",
|
||||
);
|
||||
await expect(responsePromise).rejects.toThrow("Timeout waiting for message (2000ms)");
|
||||
});
|
||||
|
||||
test("lists the full agent prompt index", async () => {
|
||||
@@ -1927,7 +1899,7 @@ test("honors explicit fetchAgents timeout below the session RPC default", async
|
||||
expect(settled).toBe(false);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(responsePromise).rejects.toThrow("No response to fetch_agents_request after 1200ms");
|
||||
await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1200ms)");
|
||||
});
|
||||
|
||||
test("honors explicit shutdownServer timeout below the session RPC default", async () => {
|
||||
@@ -1973,9 +1945,7 @@ test("honors explicit shutdownServer timeout below the session RPC default", asy
|
||||
expect(settled).toBe(false);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(responsePromise).rejects.toThrow(
|
||||
"No response to shutdown_server_request after 1500ms",
|
||||
);
|
||||
await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1500ms)");
|
||||
});
|
||||
|
||||
test("honors explicit getDaemonStatus timeout below the session RPC default", async () => {
|
||||
@@ -2021,9 +1991,7 @@ test("honors explicit getDaemonStatus timeout below the session RPC default", as
|
||||
expect(settled).toBe(false);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(responsePromise).rejects.toThrow(
|
||||
"No response to daemon.get_status.request after 1500ms",
|
||||
);
|
||||
await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1500ms)");
|
||||
});
|
||||
|
||||
test("honors explicit getDaemonPairingOffer timeout below the session RPC default", async () => {
|
||||
@@ -2069,9 +2037,7 @@ test("honors explicit getDaemonPairingOffer timeout below the session RPC defaul
|
||||
expect(settled).toBe(false);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(responsePromise).rejects.toThrow(
|
||||
"No response to daemon.get_pairing_offer.request after 1500ms",
|
||||
);
|
||||
await expect(responsePromise).rejects.toThrow("Timeout waiting for message (1500ms)");
|
||||
});
|
||||
|
||||
test("gates config reload on the daemon capability", async () => {
|
||||
@@ -2477,9 +2443,7 @@ test("keeps enable and disable inside the session RPC deadline", async () => {
|
||||
expect(settled).toBe(false);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(pending).rejects.toThrow(
|
||||
`No response to plugin.${action}.request after 60000ms`,
|
||||
);
|
||||
await expect(pending).rejects.toThrow("Timeout waiting for message (60000ms)");
|
||||
}
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
@@ -8655,9 +8619,7 @@ test("usage request timeout detaches its update listener", async () => {
|
||||
const result = client.listUsageReports({ requestId: "timeout-usage" }, (report) =>
|
||||
updates.push(report),
|
||||
);
|
||||
const rejected = expect(result).rejects.toThrow(
|
||||
"No response to usage.list_reports.request after 60000ms",
|
||||
);
|
||||
const rejected = expect(result).rejects.toThrow("Timeout waiting for message (60000ms)");
|
||||
await vi.advanceTimersByTimeAsync(60_001);
|
||||
await rejected;
|
||||
mock.triggerMessage(
|
||||
@@ -9441,7 +9403,7 @@ test("RPC deadlines remain active while a preceding frame waits for drain", asyn
|
||||
blocked = true;
|
||||
const first = client.sendHostFrame("route", new Uint8Array([1]));
|
||||
try {
|
||||
await expect(client.ping({ timeoutMs: 20 })).rejects.toThrow("No response to ping after");
|
||||
await expect(client.ping({ timeoutMs: 20 })).rejects.toThrow("Timeout waiting for message");
|
||||
expect(client.isConnected).toBe(true);
|
||||
} finally {
|
||||
drain();
|
||||
|
||||
@@ -483,7 +483,7 @@ export interface SendMessageOptions {
|
||||
sourceAgentServerId?: string;
|
||||
sessionMode?: string;
|
||||
messageId?: string;
|
||||
/** Agent sources wait for turn end unless interrupt is explicit. Human sources default to interrupt. */
|
||||
/** What happens when the agent is mid-turn. The daemon interrupts the turn when omitted. */
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments?: SendAgentMessageRequest["attachments"];
|
||||
@@ -1023,7 +1023,6 @@ interface WaitHandle<T> {
|
||||
interface WaitOptions {
|
||||
skipQueue?: boolean;
|
||||
requestId?: string;
|
||||
requestType?: SessionInboundMessage["type"];
|
||||
}
|
||||
|
||||
interface CorrelatedResponseIdentity {
|
||||
@@ -2360,7 +2359,7 @@ export class DaemonClient {
|
||||
return { kind: "ok", value };
|
||||
},
|
||||
timeout,
|
||||
{ ...params.options, requestId: params.requestId, requestType: params.message.type },
|
||||
{ ...params.options, requestId: params.requestId },
|
||||
);
|
||||
|
||||
// The response deadline still applies while the transport waits for drain.
|
||||
@@ -8108,9 +8107,7 @@ export class DaemonClient {
|
||||
): WaitHandle<T> {
|
||||
// Capture stack trace at call site, not inside setTimeout
|
||||
const timeoutError = new DaemonConnectionError(
|
||||
options?.requestType
|
||||
? `No response to ${options.requestType} after ${timeout}ms`
|
||||
: `Timeout waiting for message (${timeout}ms)`,
|
||||
`Timeout waiting for message (${timeout}ms)`,
|
||||
"DAEMON_REQUEST_TIMEOUT",
|
||||
);
|
||||
|
||||
|
||||
@@ -88,8 +88,6 @@ export interface PluginSessionOpenRequest {
|
||||
readonly background: boolean;
|
||||
readonly labels: Readonly<Record<string, string>>;
|
||||
readonly metadata: Readonly<Record<string, JsonValue>>;
|
||||
/** Instructions appended for this open; not saved on the agent. */
|
||||
appendSystemPrompt?: string[];
|
||||
tools: AgentToolDefinition[];
|
||||
env: Record<string, string>;
|
||||
mcpServers: NonNullable<AgentSessionConfig["mcpServers"]>;
|
||||
|
||||
@@ -26,8 +26,7 @@ import { buildStoredAgentPayload, toAgentPayload } from "./agent-projections.js"
|
||||
import type { ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import { projectTimelineRows } from "./timeline-projection.js";
|
||||
import { getOpenAgentTabLabel, PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels";
|
||||
import { createAgentMessageDelivery } from "./agent-messages/index.js";
|
||||
import { AgentTurnBusyError, sendPreparedPromptToAgent, startAgentRun } from "./agent-prompt.js";
|
||||
import { startAgentRun } from "./agent-prompt.js";
|
||||
import { StaleProviderSessionError } from "./stale-provider-session-error.js";
|
||||
import { ensureAgentLoaded, ensureUnarchivedAgentLoaded } from "./agent-loading.js";
|
||||
import type { StoredAgentRecord } from "./agent-storage.js";
|
||||
@@ -674,48 +673,6 @@ async function startAndSteerThroughManager(
|
||||
return { manager, agentId: agent.id, workdir };
|
||||
}
|
||||
|
||||
test("OpenCode persistence excludes launch-only instructions from storage and clients", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-plugin-persistence-"));
|
||||
const harness = new V2Harness();
|
||||
harness.info.location.directory = workdir;
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const client = new OpenCodeV2AgentClient({ logger, runtime: harness.runtime });
|
||||
const manager = new AgentManager({
|
||||
clients: { opencode: client },
|
||||
registry: storage,
|
||||
logger,
|
||||
appendSystemPrompt: "Daemon instruction",
|
||||
pluginLifecycle: {
|
||||
emit: () => {},
|
||||
before: async (name, request) =>
|
||||
name === "agent.open.before"
|
||||
? { ...request, appendSystemPrompt: ["Plugin instruction"] }
|
||||
: request,
|
||||
},
|
||||
});
|
||||
const agent = await manager.createAgent({ provider: "opencode", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
try {
|
||||
expect(harness.instructions.get("paseo")).toBe("Daemon instruction\n\nPlugin instruction");
|
||||
await manager.flush();
|
||||
const record = await storage.get(agent.id);
|
||||
expect(record?.persistence?.metadata).not.toHaveProperty("pluginAppendSystemPrompt");
|
||||
expect(record?.persistence?.metadata).not.toHaveProperty("daemonAppendSystemPrompt");
|
||||
const live = manager.getAgent(agent.id)!;
|
||||
expect(toAgentPayload(live).persistence?.metadata).not.toHaveProperty(
|
||||
"pluginAppendSystemPrompt",
|
||||
);
|
||||
expect(toAgentPayload(live).persistence?.metadata).not.toHaveProperty(
|
||||
"daemonAppendSystemPrompt",
|
||||
);
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
await client.shutdown();
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("stops an OpenCode execution already active when its conversation is reopened", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-opencode-resume-"));
|
||||
onTestFinished(() => rmSync(workdir, { recursive: true, force: true }));
|
||||
@@ -12388,18 +12345,11 @@ test("authoritative timeline records a daemon-handled submitted prompt before it
|
||||
test("tryRunOutOfBand gives providers the command another agent sent, not its envelope", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-agent-out-of-band-"));
|
||||
const seenPrompts: AgentPromptInput[] = [];
|
||||
const acceptanceOrder: string[] = [];
|
||||
|
||||
class SlashCommandSession extends TestAgentSession {
|
||||
override tryHandleOutOfBand(prompt: AgentPromptInput) {
|
||||
seenPrompts.push(prompt);
|
||||
return prompt === "/handled"
|
||||
? {
|
||||
run: async () => {
|
||||
acceptanceOrder.push("run");
|
||||
},
|
||||
}
|
||||
: null;
|
||||
return prompt === "/handled" ? { run: async () => {} } : null;
|
||||
}
|
||||
}
|
||||
const client = new (class extends TestAgentClient {
|
||||
@@ -12414,22 +12364,12 @@ test("tryRunOutOfBand gives providers the command another agent sent, not its en
|
||||
|
||||
try {
|
||||
const fromAgent = prepareAgentMessage("/handled", { kind: "agent-message", agentId: "sender" });
|
||||
expect(
|
||||
await manager.tryRunOutOfBand(agent.id, fromAgent.prompt, undefined, () => {
|
||||
acceptanceOrder.push("accepted");
|
||||
}),
|
||||
).toBe(true);
|
||||
await vi.waitFor(() => expect(acceptanceOrder).toEqual(["accepted", "run"]));
|
||||
expect(await manager.tryRunOutOfBand(agent.id, fromAgent.prompt)).toBe(true);
|
||||
expect(seenPrompts).toEqual(["/handled"]);
|
||||
|
||||
// A human who pastes an envelope gets it quoted, and it stays a plain prompt.
|
||||
const pasted = prepareAgentMessage(String(fromAgent.prompt));
|
||||
expect(
|
||||
await manager.tryRunOutOfBand(agent.id, pasted.prompt, undefined, () => {
|
||||
acceptanceOrder.push("unexpected");
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(acceptanceOrder).toEqual(["accepted", "run"]);
|
||||
expect(await manager.tryRunOutOfBand(agent.id, pasted.prompt)).toBe(false);
|
||||
expect(seenPrompts.at(-1)).toBe(pasted.prompt);
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
@@ -13592,33 +13532,6 @@ test("the last assistant message is the newest turn's reply, not joined to the p
|
||||
}
|
||||
});
|
||||
|
||||
test("the last assistant message read from rebuilt history is the newest reply, not joined to the one before it", async () => {
|
||||
// Rows replayed from provider history have no turn id. A reply the agent starts on its own,
|
||||
// such as Claude waking after a background subagent, follows the previous reply with no user
|
||||
// message between them; only their message ids tell them apart.
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-history-last-reply-"));
|
||||
const codex = fakeCodexEmitting({
|
||||
historyItems: [
|
||||
{ type: "user_message", text: "Start a background task.", messageId: "user-1" },
|
||||
{ type: "assistant_message", text: "Started it, ", messageId: "message-1" },
|
||||
{ type: "assistant_message", text: "I will report back.", messageId: "message-1" },
|
||||
{ type: "assistant_message", text: "The task finished.", messageId: "message-2" },
|
||||
],
|
||||
});
|
||||
const manager = new AgentManager({ clients: { codex }, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
try {
|
||||
await manager.hydrateTimelineFromProvider(agent.id, { force: true });
|
||||
|
||||
expect(await manager.getLastAssistantMessage(agent.id)).toBe("The task finished.");
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("reads the last durable assistant response without loading a stored-only child", async () => {
|
||||
const store = new RecordingTimelineStore();
|
||||
await store.appendCommitted("stored-child", {
|
||||
@@ -14655,309 +14568,3 @@ test("idle cleanup gives a newly restored runtime a fresh idle window while keep
|
||||
expect((await h.sweep({ now: h.later(61) })).collected).toHaveLength(1);
|
||||
expect(h.closes).toBe(closesBeforeRestore + 1);
|
||||
});
|
||||
|
||||
test.each([
|
||||
["supported", "turn_completed"],
|
||||
["supported", "turn_canceled"],
|
||||
["supported", "turn_failed"],
|
||||
["unsupported", "turn_completed"],
|
||||
["unsupported", "turn_canceled"],
|
||||
["unsupported", "turn_failed"],
|
||||
] as const)(
|
||||
"queued delivery after %s provider %s never steers or interrupts",
|
||||
async (support, ending) => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-queued-terminal-"));
|
||||
const session =
|
||||
support === "supported"
|
||||
? new SteeringTestSession({ provider: "codex", cwd: workdir })
|
||||
: new UnsupportedSteeringSession({ provider: "codex", cwd: workdir });
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})();
|
||||
const manager = new AgentManager({ clients: { codex: client }, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
let tick = () => {};
|
||||
const delivery = createAgentMessageDelivery({
|
||||
isRunning: (id) => manager.hasInFlightRun(id),
|
||||
subscribe: (notify) =>
|
||||
manager.subscribe(
|
||||
(event) => {
|
||||
if (event.type === "agent_state") notify(event.agent.id);
|
||||
},
|
||||
{ replayState: false },
|
||||
),
|
||||
schedule: (_delay, callback) => {
|
||||
tick = callback;
|
||||
return () => {};
|
||||
},
|
||||
dispatch: async (request) =>
|
||||
(
|
||||
await startAgentRun(manager, agent.id, request.prompt, logger, {
|
||||
idleOnly: request.idleOnly,
|
||||
replaceRunning: true,
|
||||
activeTurnBehavior: request.activeTurnBehavior,
|
||||
})
|
||||
).disposition,
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const providerStarted = new Promise<void>((resolve) => {
|
||||
const unsubscribe = session.subscribe((event) => {
|
||||
if (event.type === "turn_started") {
|
||||
unsubscribe();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
try {
|
||||
await startAgentRun(manager, agent.id, "original", logger);
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
const receipt = delivery.enqueue({
|
||||
recipientId: agent.id,
|
||||
prompt: "queued",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
tick();
|
||||
expect(session.startCount).toBe(1);
|
||||
expect(session.interruptCount).toBe(0);
|
||||
const turnId = support === "supported" ? "active-turn-1" : "unsupported-turn-1";
|
||||
await providerStarted;
|
||||
session.pushEvent({
|
||||
type: ending,
|
||||
provider: "codex",
|
||||
turnId,
|
||||
...(ending === "turn_failed" ? { error: "test failure" } : {}),
|
||||
} as AgentStreamEvent);
|
||||
await receipt.dispatched;
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
expect(session.startCount).toBe(2);
|
||||
expect(session.interruptCount).toBe(0);
|
||||
} finally {
|
||||
await delivery.close();
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test.each(["turn_completed", "turn_failed", "turn_canceled"] as const)(
|
||||
"an autonomous %s publishes readiness after settling its run",
|
||||
async (ending) => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-autonomous-delivery-"));
|
||||
const session = new SteeringTestSession({ provider: "codex", cwd: workdir });
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})();
|
||||
const manager = new AgentManager({ clients: { codex: client }, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
let tick = () => {};
|
||||
const settledStates: boolean[] = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
isRunning: (id) => manager.hasInFlightRun(id),
|
||||
subscribe: (notify) =>
|
||||
manager.subscribe(
|
||||
(event) => {
|
||||
if (event.type !== "agent_state") return;
|
||||
if (event.agent.lifecycle !== "running")
|
||||
settledStates.push(manager.hasInFlightRun(agent.id));
|
||||
notify(event.agent.id);
|
||||
},
|
||||
{ agentId: agent.id, replayState: false },
|
||||
),
|
||||
schedule: (_delay, callback) => {
|
||||
tick = callback;
|
||||
return () => {};
|
||||
},
|
||||
dispatch: async (request) =>
|
||||
(
|
||||
await startAgentRun(manager, agent.id, request.prompt, logger, {
|
||||
idleOnly: request.idleOnly,
|
||||
})
|
||||
).disposition,
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
try {
|
||||
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "autonomous" });
|
||||
await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(true));
|
||||
delivery.enqueue({
|
||||
recipientId: agent.id,
|
||||
prompt: "queued report",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
tick();
|
||||
expect(session.startCount).toBe(0);
|
||||
session.pushEvent({
|
||||
type: ending,
|
||||
provider: "codex",
|
||||
turnId: "autonomous",
|
||||
...(ending === "turn_failed" ? { error: "test failure" } : {}),
|
||||
} as AgentStreamEvent);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(settledStates).toEqual([false]);
|
||||
expect(session.startCount).toBe(1);
|
||||
} finally {
|
||||
await delivery.close();
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("an idle-only prompt rejects a busy recipient before changing its mode", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-queued-mode-"));
|
||||
class ModeSession extends SteeringTestSession {
|
||||
mode = "plan";
|
||||
applied: string[] = [];
|
||||
startedModes: string[] = [];
|
||||
override async setMode(mode?: string) {
|
||||
if (!mode) throw new Error("Mode required");
|
||||
this.mode = mode;
|
||||
this.applied.push(mode);
|
||||
}
|
||||
override async getCurrentMode() {
|
||||
return this.mode;
|
||||
}
|
||||
override async startTurn(prompt: AgentPromptInput) {
|
||||
this.startedModes.push(this.mode);
|
||||
return super.startTurn(prompt);
|
||||
}
|
||||
}
|
||||
const session = new ModeSession({ provider: "codex", cwd: workdir });
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})();
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
await manager.setAgentMode(agent.id, "plan");
|
||||
session.applied.length = 0;
|
||||
const providerStarted = new Promise<void>((resolve) => {
|
||||
const unsubscribe = session.subscribe((event) => {
|
||||
if (event.type === "turn_started") {
|
||||
unsubscribe();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
const startOther = async () => {
|
||||
await startAgentRun(manager, agent.id, "other turn", logger);
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
};
|
||||
try {
|
||||
await startOther();
|
||||
await expect(
|
||||
sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "queued follow-up",
|
||||
sessionMode: "full-access",
|
||||
idleOnly: true,
|
||||
logger,
|
||||
}),
|
||||
).rejects.toBeInstanceOf(AgentTurnBusyError);
|
||||
expect(session.mode).toBe("plan");
|
||||
expect(session.applied).toEqual([]);
|
||||
expect(session.startedModes).toEqual(["plan"]);
|
||||
await providerStarted;
|
||||
session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "active-turn-1" });
|
||||
await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(false));
|
||||
await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "queued follow-up",
|
||||
sessionMode: "full-access",
|
||||
idleOnly: true,
|
||||
logger,
|
||||
});
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
expect(session.mode).toBe("full-access");
|
||||
expect(session.applied).toEqual(["full-access"]);
|
||||
expect(session.startedModes).toEqual(["plan", "full-access"]);
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("plugin instructions are recomputed for each launch without changing saved config", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-plugin-prompt-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const client = new TestAgentClient();
|
||||
let additions = ["Plugin one", "Plugin two"];
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: client },
|
||||
registry: storage,
|
||||
logger,
|
||||
appendSystemPrompt: "Daemon",
|
||||
pluginLifecycle: {
|
||||
emit: () => {},
|
||||
before: async (name, request) =>
|
||||
name === "agent.open.before" ? { ...request, appendSystemPrompt: additions } : request,
|
||||
},
|
||||
});
|
||||
const snapshot = await manager.createAgent(
|
||||
{ provider: "codex", cwd: workdir, systemPrompt: "Saved" },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
expect(client.createdConfigs[0]).toMatchObject({
|
||||
systemPrompt: "Saved",
|
||||
daemonAppendSystemPrompt: "Daemon",
|
||||
pluginAppendSystemPrompt: ["Plugin one", "Plugin two"],
|
||||
});
|
||||
expect(snapshot.config.systemPrompt).toBe("Saved");
|
||||
expect((await storage.get(snapshot.id))?.config?.systemPrompt).toBe("Saved");
|
||||
const handle: AgentPersistenceHandle = {
|
||||
provider: "codex",
|
||||
sessionId: "prompt-session",
|
||||
metadata: { provider: "codex", cwd: workdir, systemPrompt: "Saved" },
|
||||
};
|
||||
await manager.closeAgent(snapshot.id);
|
||||
await manager.resumeAgentFromPersistence(
|
||||
handle,
|
||||
{ cwd: workdir, systemPrompt: "Saved" },
|
||||
snapshot.id,
|
||||
);
|
||||
expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual([
|
||||
"Plugin one",
|
||||
"Plugin two",
|
||||
]);
|
||||
additions = ["Changed"];
|
||||
await manager.closeAgent(snapshot.id);
|
||||
await manager.resumeAgentFromPersistence(
|
||||
handle,
|
||||
{ cwd: workdir, systemPrompt: "Saved" },
|
||||
snapshot.id,
|
||||
);
|
||||
expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual(["Changed"]);
|
||||
additions = ["Refreshed"];
|
||||
await manager.reloadAgentSession(snapshot.id);
|
||||
expect(client.resumeOverrides.at(-1)?.pluginAppendSystemPrompt).toEqual(["Refreshed"]);
|
||||
additions = [];
|
||||
await manager.closeAgent(snapshot.id);
|
||||
await manager.resumeAgentFromPersistence(
|
||||
handle,
|
||||
{ cwd: workdir, systemPrompt: "Saved" },
|
||||
snapshot.id,
|
||||
);
|
||||
expect(client.resumeOverrides.at(-1)?.systemPrompt).toBe("Saved");
|
||||
expect(client.resumeOverrides.at(-1)?.daemonAppendSystemPrompt).toBe("Daemon");
|
||||
expect((await storage.get(snapshot.id))?.config?.systemPrompt).toBe("Saved");
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@ import { ProviderOptionsValidationError } from "./provider-options.js";
|
||||
import type { AgentToolResult } from "@getpaseo/plugin/server";
|
||||
import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js";
|
||||
import { AgentNotFoundError, ensureAgentLoaded } from "./agent-loading.js";
|
||||
import { continuesAssistantMessage, projectTimelineRows } from "./timeline-projection.js";
|
||||
import { projectTimelineRows } from "./timeline-projection.js";
|
||||
import type { PluginLifecycle } from "../plugins/lifecycle/index.js";
|
||||
import { describeHookAgent, publishAgentStream } from "../plugins/lifecycle/index.js";
|
||||
import { applyRecordPatch } from "../record-patch.js";
|
||||
@@ -634,12 +634,7 @@ function normalizePersistenceForConfig(
|
||||
if (!handle) {
|
||||
return null;
|
||||
}
|
||||
const {
|
||||
mcpServers: _launchMcpServers,
|
||||
pluginAppendSystemPrompt: _pluginAppendSystemPrompt,
|
||||
daemonAppendSystemPrompt: _daemonAppendSystemPrompt,
|
||||
...metadata
|
||||
} = handle.metadata ?? {};
|
||||
const { mcpServers: _launchMcpServers, ...metadata } = handle.metadata ?? {};
|
||||
return {
|
||||
...handle,
|
||||
metadata: {
|
||||
@@ -1122,10 +1117,6 @@ export class AgentManager {
|
||||
return new Date(nextMs).toISOString();
|
||||
}
|
||||
|
||||
hasPendingPermissions(agentId: string): boolean {
|
||||
return (this.agents.get(agentId)?.pendingPermissions.size ?? 0) > 0;
|
||||
}
|
||||
|
||||
hasInFlightRun(agentId: string): boolean {
|
||||
const agent = this.agents.get(agentId);
|
||||
if (!agent) {
|
||||
@@ -1736,10 +1727,7 @@ export class AgentManager {
|
||||
...(record ? { metadata: record.metadata, attention: extractAttention(record) } : {}),
|
||||
workspaceId,
|
||||
launchEnv,
|
||||
persistence:
|
||||
purpose === "interactive" && session.persistenceUpdatedOnResume
|
||||
? (session.describePersistence() ?? handle)
|
||||
: handle,
|
||||
persistence: handle,
|
||||
restoring: true,
|
||||
});
|
||||
}
|
||||
@@ -3042,7 +3030,6 @@ export class AgentManager {
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
onAccepted?: () => void,
|
||||
): Promise<boolean> {
|
||||
if (this.collectingRuntimes.has(agentId) || !this.agents.has(agentId)) {
|
||||
await this.waitForAgentClose(agentId);
|
||||
@@ -3062,7 +3049,6 @@ export class AgentManager {
|
||||
if (!handler) {
|
||||
return false;
|
||||
}
|
||||
onAccepted?.();
|
||||
this.touchUpdatedAt(agent);
|
||||
if (options?.clientMessageId) {
|
||||
this.recordSubmittedPrompt(agent, prompt, options.clientMessageId, "accepted");
|
||||
@@ -4072,16 +4058,24 @@ export class AgentManager {
|
||||
private getLastAssistantMessageSegmentFromTimeline(
|
||||
timeline: readonly Pick<AgentTimelineRow, "item" | "turnId">[],
|
||||
): { text: string; startsAtBeginning: boolean } | null {
|
||||
// Collect the chunks of the last assistant message (Claude streams chunks). A turn the
|
||||
// provider starts on its own has no user message before its reply.
|
||||
// Collect the last contiguous assistant messages of one turn (Claude streams chunks).
|
||||
// A turn the provider starts on its own has no user message before its reply.
|
||||
const chunks: string[] = [];
|
||||
let replyTurnId: string | undefined;
|
||||
let startsAtBeginning = false;
|
||||
for (let i = timeline.length - 1; i >= 0; i--) {
|
||||
const { item } = timeline[i];
|
||||
if (chunks.length > 0 && !continuesAssistantMessage(timeline[i], timeline[i + 1])) {
|
||||
const { item, turnId } = timeline[i];
|
||||
if (item.type !== "assistant_message") {
|
||||
if (chunks.length) {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (chunks.length === 0) {
|
||||
replyTurnId = turnId;
|
||||
} else if (turnId !== replyTurnId) {
|
||||
break;
|
||||
}
|
||||
if (item.type !== "assistant_message") continue;
|
||||
chunks.push(item.text);
|
||||
startsAtBeginning = i === 0;
|
||||
}
|
||||
@@ -5127,9 +5121,6 @@ export class AgentManager {
|
||||
this.runs.settleTerminalRun(agent.id, eventTurnId);
|
||||
if (isForegroundEvent) {
|
||||
this.finalizeForegroundTurn(agent, eventTurnId);
|
||||
} else if (terminalDisposition !== "stale" && !agent.activeForegroundTurnId) {
|
||||
// Publish autonomous readiness only after the tracked run has settled.
|
||||
this.emitState(agent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5399,6 +5390,7 @@ export class AgentManager {
|
||||
!agent.pendingReplacement
|
||||
) {
|
||||
(agent as ActiveManagedAgent).lifecycle = "idle";
|
||||
this.emitState(agent);
|
||||
}
|
||||
void this.refreshRuntimeInfo(agent);
|
||||
}
|
||||
@@ -5439,6 +5431,9 @@ export class AgentManager {
|
||||
options,
|
||||
);
|
||||
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Turn failed");
|
||||
if (!isForegroundEvent && !agent.activeForegroundTurnId) {
|
||||
this.emitState(agent);
|
||||
}
|
||||
}
|
||||
|
||||
private onStreamTurnCanceled(params: {
|
||||
@@ -5472,6 +5467,9 @@ export class AgentManager {
|
||||
}
|
||||
agent.lastError = undefined;
|
||||
this.resolvePendingPermissionsForAgent(agent, event.provider, options, "Interrupted");
|
||||
if (!isForegroundEvent && !agent.activeForegroundTurnId) {
|
||||
this.emitState(agent);
|
||||
}
|
||||
}
|
||||
|
||||
private onStreamTurnStarted(params: {
|
||||
@@ -6181,7 +6179,6 @@ export class AgentManager {
|
||||
// A plugin changing during this open must still make the resulting session stale.
|
||||
const generation = this.sessionOpenGeneration;
|
||||
this.detachPluginTools(agentId);
|
||||
let appendSystemPrompt: string[] | undefined;
|
||||
let mcpServers: AgentSessionConfig["mcpServers"];
|
||||
let mcpServerOwners: Record<string, string> | undefined;
|
||||
if (this.pluginLifecycle) {
|
||||
@@ -6203,14 +6200,12 @@ export class AgentManager {
|
||||
env = transformed.env;
|
||||
if (request.purpose === "interactive") {
|
||||
this.attachedPluginTools.set(agentId, transformed.tools as AttachedAgentTool[]);
|
||||
appendSystemPrompt = transformed.appendSystemPrompt;
|
||||
mcpServers = transformed.mcpServers;
|
||||
mcpServerOwners = transformed.mcpServerOwners;
|
||||
}
|
||||
}
|
||||
const context: AgentLaunchContext = {
|
||||
agentId,
|
||||
...pluginPromptContext(appendSystemPrompt),
|
||||
mcpServers,
|
||||
mcpServerOwners,
|
||||
env: {
|
||||
@@ -6257,7 +6252,6 @@ export class AgentManager {
|
||||
throw new Error(`MCP server '${name}' from plugin ${owner} collides with ${existingOwner}`);
|
||||
}
|
||||
}
|
||||
launchConfig = { ...launchConfig, pluginAppendSystemPrompt: launchContext.appendSystemPrompt };
|
||||
const merged =
|
||||
Object.keys(launchContext.mcpServers ?? {}).length > 0
|
||||
? {
|
||||
@@ -6395,9 +6389,3 @@ export function commandMayHaveChangedExternalState(command: string): boolean {
|
||||
/\bgit\s+fetch\b/.test(normalized)
|
||||
);
|
||||
}
|
||||
|
||||
function pluginPromptContext(
|
||||
appendSystemPrompt: string[] | undefined,
|
||||
): Pick<AgentLaunchContext, "appendSystemPrompt"> {
|
||||
return appendSystemPrompt?.length ? { appendSystemPrompt } : {};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { AgentTurnBusyError } from "../agent-prompt.js";
|
||||
import { expect, test } from "vitest";
|
||||
import { createAgentMessageDelivery, parseAgentMessages } from "./index.js";
|
||||
import type { AgentPromptInput } from "../agent-sdk-types.js";
|
||||
@@ -118,6 +117,7 @@ test("explicit interrupt and conflicting session modes retain ordered dispatch b
|
||||
const delivery = createAgentMessageDelivery({
|
||||
dispatch: async (request) => {
|
||||
sent.push(request);
|
||||
request.onDispatch("steered");
|
||||
return "steered";
|
||||
},
|
||||
onError: (error) => {
|
||||
@@ -313,555 +313,3 @@ test("runtime safety sees queued messages until provider dispatch settles", asyn
|
||||
await delivery.close();
|
||||
expect(delivery.hasPending("parent")).toBe(false);
|
||||
});
|
||||
|
||||
test("messages wait across quiet windows and batch after the recipient turn ends", async () => {
|
||||
const clock = createClock();
|
||||
let running = true;
|
||||
const sent: Array<readonly string[]> = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => running,
|
||||
dispatch: async (request) => {
|
||||
sent.push(request.messageIds);
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const source = { kind: "agent-message" as const, agentId: "child" };
|
||||
const report = delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
messageId: "report",
|
||||
source,
|
||||
prompt: "report",
|
||||
});
|
||||
clock.advance(2000);
|
||||
await Promise.resolve();
|
||||
expect(sent).toEqual([]);
|
||||
clock.advance(13000);
|
||||
const finish = delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
messageId: "finish",
|
||||
source: { kind: "agent-notification", agentId: "child", event: "finished" },
|
||||
prompt: "finished",
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
clock.advance(2000);
|
||||
await Promise.resolve();
|
||||
expect(sent).toEqual([]);
|
||||
running = false;
|
||||
clock.advance(2000);
|
||||
await Promise.all([report.dispatched, finish.dispatched]);
|
||||
expect(sent).toEqual([["report", "finish"]]);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("a turn starting during dispatch preparation keeps receipts queued and joins later arrivals", async () => {
|
||||
const clock = createClock();
|
||||
let busy = true;
|
||||
const sent: Array<readonly string[]> = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
dispatch: async (request) => {
|
||||
if (busy) throw new AgentTurnBusyError("concurrent turn");
|
||||
sent.push(request.messageIds);
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const message = {
|
||||
recipientId: "parent",
|
||||
source: { kind: "agent-message" as const, agentId: "child" },
|
||||
prompt: "report",
|
||||
};
|
||||
const first = delivery.enqueue({ ...message, messageId: "first" });
|
||||
clock.advance(2000);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(delivery.hasPending("parent")).toBe(true);
|
||||
const second = delivery.enqueue({ ...message, messageId: "second" });
|
||||
busy = false;
|
||||
clock.advance(2000);
|
||||
await Promise.all([first.dispatched, second.dispatched]);
|
||||
expect(sent).toEqual([["first", "second"]]);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("explicit interrupt bypasses a running turn while ordinary messages keep waiting", async () => {
|
||||
const clock = createClock();
|
||||
const sent: Array<readonly string[]> = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => true,
|
||||
dispatch: async (request) => {
|
||||
sent.push(request.messageIds);
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const message = {
|
||||
recipientId: "parent",
|
||||
source: { kind: "agent-message" as const, agentId: "child" },
|
||||
prompt: "report",
|
||||
};
|
||||
delivery.enqueue({ ...message, messageId: "wait" });
|
||||
const interrupt = delivery.enqueue({
|
||||
...message,
|
||||
messageId: "interrupt",
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
clock.advance(2000);
|
||||
await interrupt.dispatched;
|
||||
expect(sent).toEqual([["interrupt"]]);
|
||||
expect(delivery.hasPending("parent")).toBe(true);
|
||||
await delivery.close();
|
||||
expect(sent).toEqual([["interrupt"], ["wait"]]);
|
||||
});
|
||||
|
||||
test("shutdown flushes a dispatch that discovered a concurrent turn during preparation", async () => {
|
||||
const clock = createClock();
|
||||
let release!: () => void;
|
||||
const preparing = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const modes: boolean[] = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
dispatch: async (request) => {
|
||||
modes.push(request.idleOnly);
|
||||
if (request.idleOnly) {
|
||||
await preparing;
|
||||
throw new AgentTurnBusyError("busy");
|
||||
}
|
||||
return "turn_started";
|
||||
},
|
||||
onError: () => {},
|
||||
});
|
||||
const receipt = delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
prompt: "report",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
clock.advance(2000);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
const closing = delivery.close();
|
||||
release();
|
||||
await closing;
|
||||
await expect(receipt.dispatched).resolves.toBe("turn_started");
|
||||
expect(modes).toEqual([true, false]);
|
||||
});
|
||||
|
||||
test("conflicting modes dispatch on separate turn ends without changing the active turn mode", async () => {
|
||||
const clock = createClock();
|
||||
let busy = false;
|
||||
let mode = "initial";
|
||||
let wake!: (recipientId: string) => void;
|
||||
const sent: Array<{ ids: readonly string[]; mode?: string }> = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => busy,
|
||||
subscribe: (listener) => {
|
||||
wake = listener;
|
||||
return () => {};
|
||||
},
|
||||
dispatch: async (request) => {
|
||||
// Mode preparation precedes run admission in the real dispatcher.
|
||||
mode = request.sessionMode ?? mode;
|
||||
if (busy) throw new AgentTurnBusyError("concurrent turn");
|
||||
sent.push({ ids: request.messageIds, mode });
|
||||
busy = true;
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const message = {
|
||||
recipientId: "parent",
|
||||
source: { kind: "agent-message" as const, agentId: "child" },
|
||||
prompt: "message",
|
||||
};
|
||||
const a = delivery.enqueue({ ...message, messageId: "A", sessionMode: "plan" });
|
||||
const b = delivery.enqueue({ ...message, messageId: "B", sessionMode: "default" });
|
||||
clock.advance(2000);
|
||||
await a.dispatched;
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(mode).toBe("plan");
|
||||
expect(sent).toEqual([{ ids: ["A"], mode: "plan" }]);
|
||||
busy = false;
|
||||
wake("parent");
|
||||
await b.dispatched;
|
||||
expect(mode).toBe("default");
|
||||
expect(sent).toEqual([
|
||||
{ ids: ["A"], mode: "plan" },
|
||||
{ ids: ["B"], mode: "default" },
|
||||
]);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("interrupts retain separate mode choices while the recipient is busy", async () => {
|
||||
const clock = createClock();
|
||||
const sent: Array<{ ids: readonly string[]; mode?: string }> = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => true,
|
||||
dispatch: async (request) => {
|
||||
sent.push({ ids: request.messageIds, mode: request.sessionMode });
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const message = {
|
||||
recipientId: "parent",
|
||||
source: { kind: "agent-message" as const, agentId: "child" },
|
||||
prompt: "message",
|
||||
activeTurnBehavior: "interrupt" as const,
|
||||
};
|
||||
const a = delivery.enqueue({ ...message, messageId: "A", sessionMode: "plan" });
|
||||
const b = delivery.enqueue({ ...message, messageId: "B", sessionMode: "default" });
|
||||
clock.advance(2000);
|
||||
await Promise.all([a.dispatched, b.dispatched]);
|
||||
expect(sent).toEqual([
|
||||
{ ids: ["A"], mode: "plan" },
|
||||
{ ids: ["B"], mode: "default" },
|
||||
]);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("a settled-turn event releases a ready batch without waiting for the next timer sample", async () => {
|
||||
const clock = createClock();
|
||||
let running = true;
|
||||
let settled: (id: string) => void = () => {};
|
||||
let subscribed = true;
|
||||
const sent: string[] = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => running,
|
||||
subscribe: (listener) => {
|
||||
settled = listener;
|
||||
return () => {
|
||||
subscribed = false;
|
||||
};
|
||||
},
|
||||
dispatch: async (request) => {
|
||||
sent.push(request.recipientId);
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
prompt: "report",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
clock.advance(2000);
|
||||
expect(sent).toEqual([]);
|
||||
running = false;
|
||||
settled("parent");
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(sent).toEqual(["parent"]);
|
||||
running = true;
|
||||
await delivery.close();
|
||||
expect(subscribed).toBe(false);
|
||||
});
|
||||
|
||||
test.each([false, true])(
|
||||
"completion waits report permission checkpoints without draining messages (initial: %s)",
|
||||
async (initial) => {
|
||||
const clock = createClock();
|
||||
let permission = initial;
|
||||
let changed: (id: string) => void = () => {};
|
||||
let reported = false;
|
||||
let sent = 0;
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => true,
|
||||
hasPendingPermission: () => permission,
|
||||
subscribe: (listener) => {
|
||||
changed = listener;
|
||||
return () => {};
|
||||
},
|
||||
dispatch: async () => {
|
||||
sent++;
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
delivery.enqueue({
|
||||
recipientId: "child",
|
||||
prompt: "follow up",
|
||||
source: { kind: "agent-message", agentId: "parent" },
|
||||
});
|
||||
const wait = delivery.waitForDispatch("child", new AbortController().signal).then(() => {
|
||||
reported = true;
|
||||
return undefined;
|
||||
});
|
||||
permission = true;
|
||||
changed("child");
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(reported).toBe(true);
|
||||
expect(sent).toBe(0);
|
||||
expect(delivery.hasPending("child")).toBe(true);
|
||||
await wait;
|
||||
await delivery.close();
|
||||
},
|
||||
);
|
||||
|
||||
test("a busy admission retry stays ready for the next settled-turn event", async () => {
|
||||
const clock = createClock();
|
||||
let running = false;
|
||||
let raced = true;
|
||||
let notify: (id: string) => void = () => {};
|
||||
const sent: string[] = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => running,
|
||||
subscribe: (listener) => {
|
||||
notify = listener;
|
||||
return () => {};
|
||||
},
|
||||
dispatch: async (request) => {
|
||||
if (raced) {
|
||||
running = true;
|
||||
throw new AgentTurnBusyError("next turn started");
|
||||
}
|
||||
sent.push(request.recipientId);
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
prompt: "report",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
clock.advance(2000);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
raced = false;
|
||||
running = false;
|
||||
notify("parent");
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(sent).toEqual(["parent"]);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("out-of-band acceptance owns callbacks and receipts; a failed attempt does not block waiting messages", async () => {
|
||||
const clock = createClock();
|
||||
let running = true;
|
||||
let wake!: (recipientId: string) => void;
|
||||
const callbacks: string[] = [];
|
||||
const sent: string[] = [];
|
||||
const errors: unknown[] = [];
|
||||
const failure = new Error("recipient could not load");
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => running,
|
||||
subscribe: (listener) => {
|
||||
wake = listener;
|
||||
return () => {};
|
||||
},
|
||||
tryRunOutOfBand: async (request, onAccepted) => {
|
||||
const text = parseAgentMessages(String(request.prompt))[0]!.text;
|
||||
if (text === "failure") throw failure;
|
||||
if (text !== "/handled") return false;
|
||||
onAccepted();
|
||||
callbacks.push("command ran");
|
||||
return true;
|
||||
},
|
||||
dispatch: async (request) => {
|
||||
sent.push(...parseAgentMessages(String(request.prompt)).map((message) => message.text));
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
errors.push(error);
|
||||
},
|
||||
});
|
||||
const message = {
|
||||
recipientId: "parent",
|
||||
source: { kind: "agent-message" as const, agentId: "child" },
|
||||
};
|
||||
const ordinary = delivery.enqueue({
|
||||
...message,
|
||||
prompt: "ordinary",
|
||||
beforeDispatch: () => {
|
||||
callbacks.push("ordinary");
|
||||
},
|
||||
});
|
||||
const failed = delivery.enqueue({
|
||||
...message,
|
||||
prompt: "failure",
|
||||
beforeDispatch: () => {
|
||||
callbacks.push("failure");
|
||||
},
|
||||
});
|
||||
const command = delivery.enqueue({
|
||||
...message,
|
||||
prompt: "/handled",
|
||||
beforeDispatch: () => {
|
||||
callbacks.push("command accepted");
|
||||
},
|
||||
onDispatch: (disposition) => {
|
||||
callbacks.push(disposition);
|
||||
},
|
||||
});
|
||||
clock.advance(2000);
|
||||
await expect(failed.dispatched).rejects.toBe(failure);
|
||||
await expect(command.dispatched).resolves.toBe("out_of_band");
|
||||
expect(errors).toEqual([failure]);
|
||||
expect(callbacks).toEqual(["command accepted", "command ran", "out_of_band"]);
|
||||
expect(sent).toEqual([]);
|
||||
running = false;
|
||||
wake("parent");
|
||||
await ordinary.dispatched;
|
||||
expect(callbacks.at(-1)).toBe("ordinary");
|
||||
expect(sent).toEqual(["ordinary"]);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("shutdown waits for an in-flight out-of-band attempt and drains its unhandled message", async () => {
|
||||
const clock = createClock();
|
||||
let release!: () => void;
|
||||
let attempted!: () => void;
|
||||
const started = new Promise<void>((resolve) => {
|
||||
attempted = resolve;
|
||||
});
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const dispatched: boolean[] = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => true,
|
||||
tryRunOutOfBand: async () => {
|
||||
attempted();
|
||||
await gate;
|
||||
return false;
|
||||
},
|
||||
dispatch: async (request) => {
|
||||
dispatched.push(request.idleOnly);
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const receipt = delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
prompt: "ordinary",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
clock.advance(2000);
|
||||
await started;
|
||||
const closing = delivery.close();
|
||||
release();
|
||||
await closing;
|
||||
await expect(receipt.dispatched).resolves.toBe("turn_started");
|
||||
expect(dispatched).toEqual([false]);
|
||||
});
|
||||
|
||||
test("a declined out-of-band message is offered once across running-turn retries", async () => {
|
||||
const clock = createClock();
|
||||
let running = true;
|
||||
let accepts = false;
|
||||
let offers = 0;
|
||||
let dispatched = 0;
|
||||
let wake!: (recipientId: string) => void;
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => running,
|
||||
subscribe: (listener) => {
|
||||
wake = listener;
|
||||
return () => {};
|
||||
},
|
||||
tryRunOutOfBand: async (_request, onAccepted) => {
|
||||
offers++;
|
||||
if (accepts) onAccepted();
|
||||
return accepts;
|
||||
},
|
||||
dispatch: async () => {
|
||||
dispatched++;
|
||||
return "turn_started";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const receipt = delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
prompt: "message",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
clock.advance(2000);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(offers).toBe(1);
|
||||
// A later provider state change does not reinterpret a declined message.
|
||||
accepts = true;
|
||||
for (let retry = 0; retry < 3; retry++) {
|
||||
clock.advance(2000);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
}
|
||||
expect(offers).toBe(1);
|
||||
expect(dispatched).toBe(0);
|
||||
running = false;
|
||||
wake("parent");
|
||||
await receipt.dispatched;
|
||||
expect(dispatched).toBe(1);
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
test("a command with an explicit mode waits for turn end without an out-of-band offer", async () => {
|
||||
const clock = createClock();
|
||||
let running = true;
|
||||
let offers = 0;
|
||||
let wake!: (recipientId: string) => void;
|
||||
const dispatched: Array<{ prompt: AgentPromptInput; sessionMode?: string }> = [];
|
||||
const delivery = createAgentMessageDelivery({
|
||||
schedule: clock.schedule,
|
||||
isRunning: () => running,
|
||||
subscribe: (listener) => {
|
||||
wake = listener;
|
||||
return () => {};
|
||||
},
|
||||
tryRunOutOfBand: async (_request, onAccepted) => {
|
||||
offers++;
|
||||
onAccepted();
|
||||
return true;
|
||||
},
|
||||
dispatch: async (request) => {
|
||||
dispatched.push(request);
|
||||
return "out_of_band";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const receipt = delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
prompt: "/handled",
|
||||
sessionMode: "plan",
|
||||
source: { kind: "agent-message", agentId: "child" },
|
||||
});
|
||||
clock.advance(2000);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(offers).toBe(0);
|
||||
expect(dispatched).toEqual([]);
|
||||
running = false;
|
||||
wake("parent");
|
||||
await receipt.dispatched;
|
||||
expect(dispatched).toHaveLength(1);
|
||||
expect(dispatched[0]!.sessionMode).toBe("plan");
|
||||
expect(parseAgentMessages(String(dispatched[0]!.prompt))![0]!.text).toBe("/handled");
|
||||
await delivery.close();
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AgentTurnBusyError, type PromptDispatchDisposition } from "../agent-prompt.js";
|
||||
import type { PromptDispatchDisposition } from "../agent-prompt.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { AgentPromptInput, AgentPromptContentBlock } from "../agent-sdk-types.js";
|
||||
import { prepareAgentMessage, type AgentPromptSource } from "./envelope.js";
|
||||
@@ -21,8 +21,6 @@ interface Receipt {
|
||||
dispatched: Promise<PromptDispatchDisposition>;
|
||||
}
|
||||
interface Admitted extends Message {
|
||||
sequence: number;
|
||||
outOfBandDeclined: boolean;
|
||||
receipt: Receipt;
|
||||
resolve(disposition: PromptDispatchDisposition): void;
|
||||
reject(error: unknown): void;
|
||||
@@ -32,18 +30,12 @@ interface DispatchRequest {
|
||||
messageIds: readonly string[];
|
||||
prompt: AgentPromptInput;
|
||||
activeTurnBehavior: "steer" | "interrupt";
|
||||
idleOnly: boolean;
|
||||
sessionMode?: string;
|
||||
clearPendingPermissions: boolean;
|
||||
unarchive: boolean;
|
||||
onDispatch(disposition: PromptDispatchDisposition): void;
|
||||
}
|
||||
interface Dependencies {
|
||||
/** Includes admitted starts and provider turns, including compaction. */
|
||||
isRunning?: (recipientId: string) => boolean;
|
||||
hasPendingPermission?: (recipientId: string) => boolean;
|
||||
/** Notify when recipient state changes; admission still checks whether it is idle. */
|
||||
subscribe?: (listener: (recipientId: string) => void) => () => void;
|
||||
tryRunOutOfBand?(request: DispatchRequest, onAccepted: () => void): Promise<boolean>;
|
||||
dispatch(request: DispatchRequest): Promise<PromptDispatchDisposition>;
|
||||
onError(error: unknown, request: DispatchRequest): void;
|
||||
/** Return a cancellation function. Production uses the daemon's event loop. */
|
||||
@@ -55,7 +47,7 @@ export interface AgentMessageDelivery {
|
||||
hasPending(recipientId: string): boolean;
|
||||
/** Stop admission, flush pending messages, and await provider dispatch acknowledgments. */
|
||||
close(): Promise<void>;
|
||||
/** Completion waits include admitted messages, but return at permission checkpoints. */
|
||||
/** Existing completion waits include agent messages admitted before the wait. */
|
||||
waitForDispatch(recipientId: string, signal: AbortSignal): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -67,14 +59,12 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
const timer = setTimeout(callback, delayMs);
|
||||
return () => clearTimeout(timer);
|
||||
});
|
||||
const pending = new Map<string, { messages: Admitted[]; ready: boolean; cancel(): void }>();
|
||||
const pending = new Map<string, { messages: Admitted[]; cancel(): void }>();
|
||||
const dispatching = new Map<string, Promise<void>>();
|
||||
const receipts = new Map<string, Set<Receipt>>();
|
||||
let sequence = 0;
|
||||
let closed = false;
|
||||
let closing: Promise<void> | undefined;
|
||||
|
||||
function requestFor(recipientId: string, messages: Admitted[]): DispatchRequest {
|
||||
function dispatch(recipientId: string, messages: Admitted[]): void {
|
||||
const prompts = messages.map(
|
||||
(message) =>
|
||||
prepareAgentMessage(message.prompt, message.source, message.receipt.messageId).prompt,
|
||||
@@ -84,55 +74,39 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
: prompts.flatMap((entry): AgentPromptContentBlock[] =>
|
||||
typeof entry === "string" ? [{ type: "text", text: entry }] : entry,
|
||||
);
|
||||
return {
|
||||
const request: DispatchRequest = {
|
||||
recipientId,
|
||||
idleOnly: !closed && messages[0]!.activeTurnBehavior !== "interrupt",
|
||||
messageIds: messages.map((message) => message.receipt.messageId),
|
||||
prompt,
|
||||
activeTurnBehavior: messages[0]!.activeTurnBehavior ?? "steer",
|
||||
sessionMode: messages.find((message) => message.sessionMode)?.sessionMode,
|
||||
clearPendingPermissions: messages.some((message) => message.clearPendingPermissions),
|
||||
unarchive: messages.some((message) => message.unarchive !== false),
|
||||
};
|
||||
}
|
||||
|
||||
function dispatch(recipientId: string, messages: Admitted[]): void {
|
||||
const request = requestFor(recipientId, messages);
|
||||
queueDispatch(recipientId, async () => {
|
||||
try {
|
||||
for (const message of messages) message.beforeDispatch?.();
|
||||
let disposition: PromptDispatchDisposition;
|
||||
try {
|
||||
disposition = await dependencies.dispatch(request);
|
||||
} catch (error) {
|
||||
if (!(error instanceof AgentTurnBusyError) || !closed) throw error;
|
||||
// Shutdown drains admitted messages before closing the recipients.
|
||||
disposition = await dependencies.dispatch({ ...request, idleOnly: false });
|
||||
}
|
||||
onDispatch: (disposition) => {
|
||||
for (const message of messages) {
|
||||
try {
|
||||
message.onDispatch?.(disposition);
|
||||
} catch (error) {
|
||||
dependencies.onError(error, request);
|
||||
}
|
||||
message.resolve(disposition);
|
||||
}
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
if (error instanceof AgentTurnBusyError && !closed) {
|
||||
requeue(recipientId, messages);
|
||||
return;
|
||||
}
|
||||
for (const message of messages) message.reject(error);
|
||||
dependencies.onError(error, request);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function queueDispatch(recipientId: string, operation: () => Promise<void>): void {
|
||||
},
|
||||
};
|
||||
const previous = dispatching.get(recipientId) ?? Promise.resolve();
|
||||
const dispatched = previous.catch(() => undefined).then(operation);
|
||||
const dispatched = previous
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
try {
|
||||
for (const message of messages) message.beforeDispatch?.();
|
||||
const disposition = await dependencies.dispatch(request);
|
||||
for (const message of messages) message.resolve(disposition);
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
for (const message of messages) message.reject(error);
|
||||
dependencies.onError(error, request);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
dispatching.set(recipientId, dispatched);
|
||||
void dispatched
|
||||
.finally(() => {
|
||||
@@ -141,121 +115,30 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
function requeue(recipientId: string, messages: Admitted[]): void {
|
||||
const entry = pending.get(recipientId) ?? {
|
||||
messages: [],
|
||||
ready: true,
|
||||
cancel: () => {},
|
||||
};
|
||||
entry.cancel();
|
||||
entry.messages.push(...messages);
|
||||
entry.messages.sort((a, b) => a.sequence - b.sequence);
|
||||
entry.cancel = schedule(2000, () => flush(recipientId));
|
||||
pending.set(recipientId, entry);
|
||||
}
|
||||
|
||||
function flush(recipientId: string): void {
|
||||
const entry = pending.get(recipientId);
|
||||
if (!entry) return;
|
||||
entry.ready = true;
|
||||
entry.cancel();
|
||||
if (!closed && dependencies.isRunning?.(recipientId)) {
|
||||
const interrupts = entry.messages.filter(
|
||||
(message) => message.activeTurnBehavior === "interrupt",
|
||||
);
|
||||
entry.messages = entry.messages.filter(
|
||||
(message) => message.activeTurnBehavior !== "interrupt",
|
||||
);
|
||||
if (interrupts.length) dispatchGroups(recipientId, interrupts);
|
||||
if (entry.messages.length && dependencies.tryRunOutOfBand) {
|
||||
pending.delete(recipientId);
|
||||
offerOutOfBand(recipientId, entry.messages);
|
||||
} else if (entry.messages.length) {
|
||||
entry.cancel = schedule(2000, () => flush(recipientId));
|
||||
} else {
|
||||
pending.delete(recipientId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
pending.delete(recipientId);
|
||||
dispatchGroups(recipientId, entry.messages);
|
||||
}
|
||||
|
||||
function offerOutOfBand(recipientId: string, messages: Admitted[]): void {
|
||||
queueDispatch(recipientId, async () => {
|
||||
const waiting: Admitted[] = [];
|
||||
for (const message of messages) {
|
||||
if (
|
||||
message.outOfBandDeclined ||
|
||||
message.sessionMode !== undefined ||
|
||||
closed ||
|
||||
!dependencies.isRunning?.(recipientId)
|
||||
) {
|
||||
waiting.push(message);
|
||||
continue;
|
||||
}
|
||||
const request = requestFor(recipientId, [message]);
|
||||
try {
|
||||
const accepted = await dependencies.tryRunOutOfBand!(request, () =>
|
||||
message.beforeDispatch?.(),
|
||||
);
|
||||
if (!accepted) {
|
||||
message.outOfBandDeclined = true;
|
||||
waiting.push(message);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
message.onDispatch?.("out_of_band");
|
||||
} catch (error) {
|
||||
dependencies.onError(error, request);
|
||||
}
|
||||
message.resolve("out_of_band");
|
||||
} catch (error) {
|
||||
message.reject(error);
|
||||
dependencies.onError(error, request);
|
||||
}
|
||||
}
|
||||
if (waiting.length) requeue(recipientId, waiting);
|
||||
if (closed || (pending.get(recipientId)?.ready && !dependencies.isRunning?.(recipientId)))
|
||||
flush(recipientId);
|
||||
});
|
||||
}
|
||||
|
||||
function dispatchGroups(recipientId: string, messages: Admitted[]): void {
|
||||
const groups: Admitted[][] = [];
|
||||
entry.cancel();
|
||||
let group: Admitted[] = [];
|
||||
let mode: string | undefined;
|
||||
for (const message of messages) {
|
||||
for (const message of entry.messages) {
|
||||
// Explicitly conflicting send options require separate, ordered dispatches.
|
||||
if (
|
||||
group.length &&
|
||||
((message.activeTurnBehavior ?? "steer") !== (group[0]!.activeTurnBehavior ?? "steer") ||
|
||||
(mode && message.sessionMode && mode !== message.sessionMode))
|
||||
) {
|
||||
groups.push(group);
|
||||
dispatch(recipientId, group);
|
||||
group = [];
|
||||
mode = undefined;
|
||||
}
|
||||
group.push(message);
|
||||
mode ??= message.sessionMode;
|
||||
}
|
||||
if (group.length) groups.push(group);
|
||||
let started = false;
|
||||
for (const batch of groups) {
|
||||
if (!closed && started && batch[0]!.activeTurnBehavior !== "interrupt") {
|
||||
requeue(recipientId, batch);
|
||||
} else {
|
||||
dispatch(recipientId, batch);
|
||||
started = true;
|
||||
}
|
||||
}
|
||||
if (group.length) dispatch(recipientId, group);
|
||||
}
|
||||
|
||||
const unsubscribe = dependencies.subscribe?.((recipientId) => {
|
||||
if (pending.get(recipientId)?.ready && !dependencies.isRunning?.(recipientId))
|
||||
flush(recipientId);
|
||||
});
|
||||
|
||||
return {
|
||||
hasPending: (recipientId) => pending.has(recipientId) || dispatching.has(recipientId),
|
||||
enqueue(message) {
|
||||
@@ -272,47 +155,17 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
messageId: message.messageId ?? randomUUID(),
|
||||
dispatched,
|
||||
};
|
||||
const owned = receipts.get(message.recipientId) ?? new Set<Receipt>();
|
||||
owned.add(receipt);
|
||||
receipts.set(message.recipientId, owned);
|
||||
void dispatched
|
||||
.finally(() => {
|
||||
owned.delete(receipt);
|
||||
if (!owned.size) receipts.delete(message.recipientId);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
const entry = pending.get(message.recipientId) ?? {
|
||||
messages: [],
|
||||
ready: false,
|
||||
cancel: () => {},
|
||||
};
|
||||
const entry = pending.get(message.recipientId) ?? { messages: [], cancel: () => {} };
|
||||
entry.cancel();
|
||||
entry.ready = false;
|
||||
entry.messages.push({
|
||||
...message,
|
||||
receipt,
|
||||
resolve,
|
||||
reject,
|
||||
sequence: sequence++,
|
||||
outOfBandDeclined: false,
|
||||
});
|
||||
entry.messages.push({ ...message, receipt, resolve, reject });
|
||||
entry.cancel = schedule(2000, () => flush(message.recipientId));
|
||||
pending.set(message.recipientId, entry);
|
||||
return receipt;
|
||||
},
|
||||
async waitForDispatch(recipientId, signal) {
|
||||
signal.throwIfAborted();
|
||||
const admitted = Array.from(receipts.get(recipientId) ?? [], (receipt) => receipt.dispatched);
|
||||
let unsubscribePermission: (() => void) | undefined;
|
||||
const permission = new Promise<void>((resolve) => {
|
||||
const check = () => {
|
||||
if (dependencies.hasPendingPermission?.(recipientId)) resolve();
|
||||
};
|
||||
unsubscribePermission = dependencies.subscribe?.((agentId) => {
|
||||
if (agentId === recipientId) check();
|
||||
});
|
||||
check();
|
||||
});
|
||||
const admitted =
|
||||
pending.get(recipientId)?.messages.map((message) => message.receipt.dispatched) ?? [];
|
||||
let aborted!: () => void;
|
||||
const cancellation = new Promise<never>((_resolve, reject) => {
|
||||
aborted = () => reject(new DOMException("Wait aborted", "AbortError"));
|
||||
@@ -322,22 +175,17 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
await Promise.race([
|
||||
Promise.all([dispatching.get(recipientId), ...admitted]),
|
||||
cancellation,
|
||||
permission,
|
||||
]);
|
||||
} finally {
|
||||
signal.removeEventListener("abort", aborted);
|
||||
unsubscribePermission?.();
|
||||
}
|
||||
},
|
||||
close() {
|
||||
if (closing) return closing;
|
||||
closed = true;
|
||||
unsubscribe?.();
|
||||
for (const recipientId of pending.keys()) flush(recipientId);
|
||||
// Each failure is reported and rejects its receipts; shutdown still drains other recipients.
|
||||
closing = Promise.allSettled(
|
||||
[...receipts.values()].flatMap((owned) => [...owned].map((receipt) => receipt.dispatched)),
|
||||
).then(() => undefined);
|
||||
closing = Promise.allSettled(dispatching.values()).then(() => undefined);
|
||||
return closing;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -337,7 +337,6 @@ describe("toAgentPayload", () => {
|
||||
nativeHandle: { id: "native" } as unknown,
|
||||
metadata: {
|
||||
restored: new Date("2025-03-01T00:00:00.000Z"),
|
||||
paseoInstructionReceipt: { threadId: "persist-99", digest: "internal-digest" },
|
||||
empty: {},
|
||||
mcpServers: {
|
||||
hub: {
|
||||
@@ -388,8 +387,6 @@ describe("toAgentPayload", () => {
|
||||
sessionId: "persist-stored",
|
||||
metadata: {
|
||||
conversationId: "conversation-stored",
|
||||
pluginAppendSystemPrompt: ["plugin instruction"],
|
||||
daemonAppendSystemPrompt: "daemon instruction",
|
||||
mcpServers: {
|
||||
hub: {
|
||||
type: "http",
|
||||
@@ -405,8 +402,6 @@ describe("toAgentPayload", () => {
|
||||
|
||||
expect(record.persistence?.metadata).toEqual({
|
||||
conversationId: "conversation-stored",
|
||||
pluginAppendSystemPrompt: ["plugin instruction"],
|
||||
daemonAppendSystemPrompt: "daemon instruction",
|
||||
mcpServers: {
|
||||
hub: {
|
||||
type: "http",
|
||||
|
||||
@@ -495,9 +495,6 @@ function projectPersistenceHandleForWire(
|
||||
return projected;
|
||||
}
|
||||
delete projected.metadata.mcpServers;
|
||||
delete projected.metadata.pluginAppendSystemPrompt;
|
||||
delete projected.metadata.daemonAppendSystemPrompt;
|
||||
delete projected.metadata.paseoInstructionReceipt;
|
||||
if (Object.keys(projected.metadata).length === 0) {
|
||||
delete projected.metadata;
|
||||
}
|
||||
|
||||
@@ -23,10 +23,7 @@ export type AgentRunController = Pick<
|
||||
reloadAgentSession(agentId: string): Promise<unknown>;
|
||||
};
|
||||
|
||||
export class AgentTurnBusyError extends Error {}
|
||||
|
||||
export interface StartAgentRunOptions {
|
||||
idleOnly?: boolean;
|
||||
/** Called after selecting the run, before consuming its events. */
|
||||
onDispatch?: (disposition: PromptDispatchDisposition) => void;
|
||||
replaceRunning?: boolean;
|
||||
@@ -139,12 +136,7 @@ async function startAgentRunInner(
|
||||
options?: StartAgentRunOptions,
|
||||
): Promise<{ disposition: PromptDispatchDisposition }> {
|
||||
const snapshot = agentManager.getAgent(agentId);
|
||||
const steered = options?.idleOnly
|
||||
? null
|
||||
: await steerOrReplaceActiveRun(agentManager, agentId, prompt, options);
|
||||
if (options?.idleOnly && agentManager.hasInFlightRun(agentId)) {
|
||||
throw new AgentTurnBusyError(`Agent ${agentId} is running`);
|
||||
}
|
||||
const steered = await steerOrReplaceActiveRun(agentManager, agentId, prompt, options);
|
||||
if (steered?.disposition === "steered") {
|
||||
options?.onDispatch?.("steered");
|
||||
return steered;
|
||||
@@ -218,7 +210,6 @@ export async function unarchiveAgentState(
|
||||
}
|
||||
|
||||
export interface SendPromptToAgentParams {
|
||||
idleOnly?: boolean;
|
||||
/** Awaited after the agent is loaded and its mode is set, before the prompt is handed to a run. */
|
||||
beforeDispatch?: () => Promise<void>;
|
||||
onDispatch?: StartAgentRunOptions["onDispatch"];
|
||||
@@ -364,17 +355,13 @@ export async function sendPreparedPromptToAgent(
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (params.idleOnly && params.agentManager.hasInFlightRun(params.agentId)) {
|
||||
throw new AgentTurnBusyError(`Agent ${params.agentId} is running`);
|
||||
}
|
||||
if (params.sessionMode) {
|
||||
await params.agentManager.setAgentMode(params.agentId, params.sessionMode);
|
||||
}
|
||||
|
||||
await params.beforeDispatch?.();
|
||||
return await startAgentRun(params.agentManager, params.agentId, params.prompt, params.logger, {
|
||||
replaceRunning: !params.idleOnly,
|
||||
idleOnly: params.idleOnly,
|
||||
replaceRunning: true,
|
||||
onDispatch: params.onDispatch,
|
||||
activeTurnBehavior: params.activeTurnBehavior,
|
||||
clearPendingPermissions: params.clearPendingPermissions,
|
||||
|
||||
@@ -621,8 +621,6 @@ export interface AgentSessionConfig {
|
||||
* persisted into agent config so daemon setting changes apply cleanly.
|
||||
*/
|
||||
daemonAppendSystemPrompt?: string;
|
||||
/** Plugin instructions for this launch; never persisted. */
|
||||
pluginAppendSystemPrompt?: string[];
|
||||
modeId?: string;
|
||||
model?: string;
|
||||
thinkingOptionId?: string;
|
||||
@@ -638,8 +636,6 @@ export interface AgentSessionConfig {
|
||||
}
|
||||
|
||||
export interface AgentLaunchContext {
|
||||
/** Launch-only instructions contributed by plugins. */
|
||||
appendSystemPrompt?: string[];
|
||||
/** Launch-only plugin MCP servers and their owners; never persisted. */
|
||||
mcpServers?: Record<string, McpServerConfig>;
|
||||
mcpServerOwners?: Record<string, string>;
|
||||
@@ -692,8 +688,6 @@ export interface AgentUsageSession {
|
||||
}
|
||||
|
||||
export interface AgentSession {
|
||||
/** Persist the session's current handle immediately after an interactive resume. */
|
||||
readonly persistenceUpdatedOnResume?: boolean;
|
||||
usageSession?(): AgentUsageSession | null;
|
||||
readonly provider: AgentProvider;
|
||||
readonly id: string | null;
|
||||
|
||||
@@ -498,26 +498,3 @@ test("finish recovery protects callers before durable intent has loaded", async
|
||||
expect(recovered.hasPendingForCaller("parent")).toBe(true);
|
||||
expect(recovered.hasPendingForCaller("unrelated")).toBe(false);
|
||||
});
|
||||
|
||||
test("an undispatched follow-up does not block the running child's permission notification", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register(intent);
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
await state.service.register(intent, true);
|
||||
const result = outcome("running");
|
||||
result.status = "permission";
|
||||
result.final!.pendingPermissions = [
|
||||
{
|
||||
id: "approval",
|
||||
provider: "codex",
|
||||
name: "Bash",
|
||||
kind: "tool",
|
||||
input: { command: "run tests" },
|
||||
} as NonNullable<typeof result.final>["pendingPermissions"][number],
|
||||
];
|
||||
state.observation.waits[0]!.result.resolve(result);
|
||||
await until(() => state.delivery.prompts.length === 1);
|
||||
expect(state.delivery.prompts[0]).toContain("needs permission");
|
||||
expect(state.delivery.prompts[0]).toContain("approval");
|
||||
expect(await state.store.list()).toHaveLength(2);
|
||||
});
|
||||
|
||||
@@ -267,9 +267,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
continue;
|
||||
}
|
||||
if (signal.aborted) return;
|
||||
// A queued follow-up cannot start until the current permission is answered.
|
||||
// Its pending registration must not hold the running turn's checkpoint.
|
||||
if (pending.status !== "permission" || watch.pending) await decisions(group);
|
||||
await decisions(group);
|
||||
if (signal.aborted) return;
|
||||
if (await suppressed(record, pending)) {
|
||||
await remove(watch);
|
||||
|
||||
@@ -298,7 +298,7 @@ export function createHostResolver(input: {
|
||||
status: agent.status,
|
||||
guidance:
|
||||
receipt.deliveryStatus === "queued"
|
||||
? "Queued for delivery after two quiet seconds and the current turn ends, unless interrupt was requested. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false."
|
||||
? "Queued for delivery after two quiet seconds. You will get notified when the prompted agent finishes, errors, or needs permission unless notifyOnFinish is false."
|
||||
: "Dispatch acknowledged. Observe completion using get_agent_status/get_agent_activity or SDK/RPC subscriptions and wait APIs.",
|
||||
});
|
||||
},
|
||||
|
||||
@@ -172,12 +172,11 @@ function registeredTool(
|
||||
async function invokeToolWithParsedInput(
|
||||
tool: RegisteredMcpToolWithHandler,
|
||||
input: Record<string, unknown>,
|
||||
awaitDispatch = true,
|
||||
) {
|
||||
const parsed = await tool.inputSchema.safeParseAsync(input);
|
||||
expect(parsed.success).toBe(true);
|
||||
const response = await tool.handler(parsed.data);
|
||||
if (awaitDispatch && response.structuredContent.deliveryStatus === "queued") {
|
||||
if (response.structuredContent.deliveryStatus === "queued") {
|
||||
await toolDeliveries
|
||||
.get(tool)!
|
||||
.waitForDispatch(input.agentId as string, new AbortController().signal);
|
||||
@@ -275,7 +274,6 @@ function buildAgentManagerSpies() {
|
||||
effectiveOptionsFor: (_provider: string, own?: Record<string, unknown>) => own ?? {},
|
||||
reloadStalePluginSession: async () => {},
|
||||
hasInFlightRun: vi.fn().mockReturnValue(false),
|
||||
hasPendingPermissions: () => false,
|
||||
steerOrReplaceActiveTurn: async () => ({ status: "inactive" as const }),
|
||||
tryRunOutOfBand: vi.fn().mockReturnValue(false),
|
||||
subscribe: vi.fn().mockReturnValue(() => {}),
|
||||
@@ -625,12 +623,6 @@ class FakeBrowserToolsBroker {
|
||||
}
|
||||
|
||||
class BoundaryAgentManagerFake {
|
||||
subscribe() {
|
||||
return () => {};
|
||||
}
|
||||
hasPendingPermissions() {
|
||||
return false;
|
||||
}
|
||||
public getPluginTools(): [] {
|
||||
return [];
|
||||
}
|
||||
@@ -885,9 +877,8 @@ function createPaseoWorktreeForMcpTest(options: {
|
||||
async function createAgentMcpServer(
|
||||
options: Parameters<typeof createAgentMcpServerWithDependencies>[0],
|
||||
subscriptionStore?: FinishSubscriptionStore,
|
||||
schedule?: (delayMs: number, callback: () => void) => () => void,
|
||||
) {
|
||||
const messages = createTestAgentMessages({ ...options, schedule });
|
||||
const messages = createTestAgentMessages(options);
|
||||
const records = new Map<string, FinishSubscription>();
|
||||
const subscriptions = createFinishSubscriptions({
|
||||
store: subscriptionStore ?? {
|
||||
@@ -3686,15 +3677,15 @@ class HeldTurnAgentClient implements AgentClient {
|
||||
|
||||
describe("send_agent_prompt MCP tool", () => {
|
||||
it.each([
|
||||
{ agentScoped: true, behavior: undefined, available: true },
|
||||
{ agentScoped: true, behavior: "interrupt", available: true },
|
||||
{ agentScoped: true, behavior: "steer", available: true },
|
||||
{ agentScoped: false, behavior: undefined, available: true },
|
||||
{ agentScoped: false, behavior: "steer", available: true },
|
||||
{ agentScoped: true, behavior: undefined, available: false },
|
||||
{ agentScoped: true, behavior: undefined, available: true, steered: true },
|
||||
{ agentScoped: true, behavior: "interrupt", available: true, steered: false },
|
||||
{ agentScoped: true, behavior: "steer", available: true, steered: true },
|
||||
{ agentScoped: false, behavior: undefined, available: true, steered: false },
|
||||
{ agentScoped: false, behavior: "steer", available: true, steered: true },
|
||||
{ agentScoped: true, behavior: undefined, available: false, steered: false },
|
||||
] as const)(
|
||||
"dispatches behavior $behavior for agent-scoped=$agentScoped, steering available=$available",
|
||||
async ({ agentScoped, behavior, available }) => {
|
||||
async ({ agentScoped, behavior, available, steered }) => {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const client = new HeldTurnAgentClient("codex", true, {
|
||||
@@ -3726,33 +3717,18 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
notifyOnFinish: false,
|
||||
});
|
||||
const originalTurn = manager.getAgent(child.id)!.activeTurnId;
|
||||
const queued = agentScoped && behavior !== "interrupt";
|
||||
const steered = !agentScoped && behavior === "steer";
|
||||
const response = await invokeToolWithParsedInput(
|
||||
tool,
|
||||
{
|
||||
agentId: child.id,
|
||||
prompt: "New message",
|
||||
notifyOnFinish: false,
|
||||
...(behavior ? { activeTurnBehavior: behavior } : {}),
|
||||
},
|
||||
!queued,
|
||||
);
|
||||
const response = await invokeToolWithParsedInput(tool, {
|
||||
agentId: child.id,
|
||||
prompt: "New message",
|
||||
notifyOnFinish: false,
|
||||
...(behavior ? { activeTurnBehavior: behavior } : {}),
|
||||
});
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
...(agentScoped
|
||||
? { deliveryStatus: "queued" }
|
||||
: { disposition: steered ? "steered" : "turn_started" }),
|
||||
});
|
||||
if (queued) {
|
||||
expect(client.sessions[1]!.prompts).toHaveLength(1);
|
||||
expect(client.sessions[1]!.steeredPrompts).toEqual([]);
|
||||
expect(manager.getAgent(child.id)!.activeTurnId).toBe(originalTurn);
|
||||
client.sessions[1]!.finishTurn();
|
||||
await serverDeliveries
|
||||
.get(server)!
|
||||
.waitForDispatch(child.id, new AbortController().signal);
|
||||
}
|
||||
expect(client.sessions[1]!.prompts).toHaveLength(steered ? 1 : 2);
|
||||
expect(client.sessions[1]!.steeredPrompts).toHaveLength(steered ? 1 : 0);
|
||||
expect(manager.getAgent(child.id)!.activeTurnId === originalTurn).toBe(steered);
|
||||
@@ -3764,16 +3740,18 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
|
||||
it.each([
|
||||
{ rejected: false, priorNotification: false },
|
||||
{ rejected: false, priorNotification: true },
|
||||
{ rejected: true, priorNotification: false },
|
||||
{ rejected: true, priorNotification: true },
|
||||
{ rejected: false, priorNotification: true },
|
||||
])(
|
||||
"keeps completion tied to queued dispatch acknowledgement (rejected: $rejected, prior notification: $priorNotification)",
|
||||
"buffers completion until steer acknowledgement (rejected: $rejected, prior notification: $priorNotification)",
|
||||
async ({ rejected, priorNotification }) => {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-queued-ack-"));
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const options: HeldTurnOptions = {};
|
||||
const client = new HeldTurnAgentClient("codex", true, options);
|
||||
const client = new HeldTurnAgentClient("codex", true, {
|
||||
steerResult: "accepted",
|
||||
finishDuringSteer: true,
|
||||
rejectSteer: rejected,
|
||||
});
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
let mcpClient: Client | undefined;
|
||||
try {
|
||||
@@ -3795,47 +3773,104 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
logger,
|
||||
});
|
||||
mcpClient = await connectInMemoryMcpClient(server);
|
||||
await sendMcpAndAwaitDispatch(mcpClient, server, {
|
||||
const send = (input: Record<string, unknown>) =>
|
||||
sendMcpAndAwaitDispatch(mcpClient!, server, input);
|
||||
await send({
|
||||
agentId: child.id,
|
||||
prompt: "Original work",
|
||||
notifyOnFinish: priorNotification,
|
||||
});
|
||||
const session = client.sessions[1]!;
|
||||
const release = session.holdTurnStart();
|
||||
options.finishTurnsDuringStart = true;
|
||||
if (rejected) session.rejectNextTurnStart(new Error("Start rejected"));
|
||||
const response = await mcpClient.callTool({
|
||||
name: "send_agent_prompt",
|
||||
arguments: { agentId: child.id, prompt: "New message", notifyOnFinish: true },
|
||||
const sending = send({
|
||||
agentId: child.id,
|
||||
prompt: "New message",
|
||||
notifyOnFinish: true,
|
||||
});
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
deliveryStatus: "queued",
|
||||
});
|
||||
const dispatch = serverDeliveries
|
||||
.get(server)!
|
||||
.waitForDispatch(child.id, new AbortController().signal);
|
||||
const rejectedDispatch = rejected
|
||||
? expect(dispatch).rejects.toThrow("Start rejected")
|
||||
: null;
|
||||
expect(client.sessions[0]!.prompts).toHaveLength(0);
|
||||
session.finishTurn();
|
||||
await vi.waitFor(() => expect(session.prompts).toHaveLength(2));
|
||||
expect(client.sessions[0]!.prompts).toHaveLength(0);
|
||||
release();
|
||||
if (rejectedDispatch) await rejectedDispatch;
|
||||
else await dispatch;
|
||||
if (!rejected || priorNotification) {
|
||||
await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1), {
|
||||
timeout: 5000,
|
||||
});
|
||||
expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({
|
||||
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
|
||||
});
|
||||
} else {
|
||||
await serverSubscriptions.get(server)!.close();
|
||||
if (rejected) {
|
||||
await expect(sending).rejects.toThrow("Steer rejected");
|
||||
// Flush asynchronous notification work before checking that a rejected
|
||||
// dispatch did not notify. Then prove a later successful send still can.
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
expect(client.sessions[0]!.prompts).toHaveLength(0);
|
||||
await send({
|
||||
agentId: child.id,
|
||||
prompt: "Retry after rejection",
|
||||
});
|
||||
client.sessions[1]!.finishTurn();
|
||||
} else {
|
||||
const response = await sending;
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
deliveryStatus: "queued",
|
||||
});
|
||||
}
|
||||
await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1));
|
||||
expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({
|
||||
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
|
||||
});
|
||||
} finally {
|
||||
await mcpClient?.close();
|
||||
await removeAgentStateDir(manager, storage, workdir);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([false, true])(
|
||||
"preserves the original notification after rejection (completion during send: %s)",
|
||||
async (finishDuringSteer) => {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-send-behavior-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const client = new HeldTurnAgentClient("codex", true, {
|
||||
steerResult: "accepted",
|
||||
finishDuringSteer,
|
||||
rejectSteer: true,
|
||||
});
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
let mcpClient: Client | undefined;
|
||||
try {
|
||||
const parent = await manager.createAgent(
|
||||
{ provider: "codex", cwd: existingCwd },
|
||||
undefined,
|
||||
{
|
||||
workspaceId: "wks_parent",
|
||||
},
|
||||
);
|
||||
const child = await manager.createAgent(
|
||||
{ provider: "codex", cwd: existingCwd },
|
||||
undefined,
|
||||
{
|
||||
workspaceId: "wks_parent",
|
||||
},
|
||||
);
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
callerAgentId: parent.id,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
});
|
||||
mcpClient = await connectInMemoryMcpClient(server);
|
||||
const send = (input: Record<string, unknown>) =>
|
||||
sendMcpAndAwaitDispatch(mcpClient!, server, input);
|
||||
await send({
|
||||
agentId: child.id,
|
||||
prompt: "Original work",
|
||||
notifyOnFinish: true,
|
||||
});
|
||||
const sending = send({
|
||||
agentId: child.id,
|
||||
prompt: "New message",
|
||||
notifyOnFinish: true,
|
||||
});
|
||||
await expect(sending).rejects.toThrow("Steer rejected");
|
||||
if (!finishDuringSteer) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
expect(client.sessions[0]!.prompts).toHaveLength(0);
|
||||
client.sessions[1]!.finishTurn();
|
||||
}
|
||||
await vi.waitFor(() => expect(client.sessions[0]!.prompts).toHaveLength(1));
|
||||
expect(parseAgentMessage(client.sessions[0]!.prompts[0])).toMatchObject({
|
||||
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
|
||||
});
|
||||
} finally {
|
||||
await mcpClient?.close();
|
||||
await removeAgentStateDir(manager, storage, workdir);
|
||||
@@ -3977,7 +4012,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
const response = await tool.handler(parsed.data as Record<string, unknown>);
|
||||
|
||||
expect(response.structuredContent).toMatchObject({ deliveryStatus: "queued" });
|
||||
expect(serverSubscriptionRecords.get(server)!.size).toBe(1);
|
||||
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
|
||||
await serverDeliveries
|
||||
.get(server)!
|
||||
.waitForDispatch("child-agent", new AbortController().signal);
|
||||
@@ -4018,7 +4053,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
|
||||
await tool.handler(parsed.data as Record<string, unknown>);
|
||||
|
||||
expect(serverSubscriptionRecords.get(server)!.size).toBe(0);
|
||||
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
|
||||
expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -4061,7 +4096,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
notifyOnFinish: false,
|
||||
});
|
||||
|
||||
expect(serverSubscriptionRecords.get(server)!.size).toBe(0);
|
||||
expect(spies.agentManager.subscribe).not.toHaveBeenCalled();
|
||||
expect(spies.agentManager.waitForAgentEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -4185,15 +4220,11 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
notifyOnFinish: false,
|
||||
});
|
||||
if (scenario !== "startup_failure") {
|
||||
const response = await invokeToolWithParsedInput(
|
||||
tool,
|
||||
{
|
||||
agentId: child.id,
|
||||
prompt: "/side-command",
|
||||
activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "steer",
|
||||
},
|
||||
scenario !== "out_of_band",
|
||||
);
|
||||
const response = await invokeToolWithParsedInput(tool, {
|
||||
agentId: child.id,
|
||||
prompt: "/side-command",
|
||||
activeTurnBehavior: scenario === "out_of_band_interrupt" ? "interrupt" : "steer",
|
||||
});
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
deliveryStatus: "queued",
|
||||
@@ -4205,9 +4236,6 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
});
|
||||
expect(parentClient.sessions[0]!.prompts).toHaveLength(0);
|
||||
childClient.sessions[0]!.finishTurn("Ongoing task done");
|
||||
await serverDeliveries
|
||||
.get(server)!
|
||||
.waitForDispatch(child.id, new AbortController().signal);
|
||||
await vi.waitFor(() => {
|
||||
expect(parentClient.sessions[0]!.prompts).toHaveLength(1);
|
||||
expect(parentClient.sessions[0]!.prompts[0]).toContain("finished.");
|
||||
@@ -4215,11 +4243,7 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
} else {
|
||||
childClient.sessions[0]!.rejectNextTurnStart(new Error("Requested turn could not start"));
|
||||
await expect(
|
||||
invokeToolWithParsedInput(tool, {
|
||||
agentId: child.id,
|
||||
prompt: "Replacement task",
|
||||
activeTurnBehavior: "interrupt",
|
||||
}),
|
||||
invokeToolWithParsedInput(tool, { agentId: child.id, prompt: "Replacement task" }),
|
||||
).rejects.toThrow("Requested turn could not start");
|
||||
// A later real turn must not inherit a subscription from the rejected dispatch.
|
||||
await invokeToolWithParsedInput(tool, {
|
||||
@@ -4330,7 +4354,6 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
const sent = await invokeToolWithParsedInput(registeredTool(server, "send_agent_prompt"), {
|
||||
agentId: childId,
|
||||
prompt: "Stop and reply instead",
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
expect(sent.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
@@ -4494,7 +4517,7 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
|
||||
const logger = createTestLogger();
|
||||
const existingCwd = process.cwd();
|
||||
|
||||
async function setupOmpChild(schedule?: (delayMs: number, callback: () => void) => () => void) {
|
||||
async function setupOmpChild() {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-omp-child-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const parentClient = new HeldTurnAgentClient("claude", false);
|
||||
@@ -4522,17 +4545,13 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
|
||||
undefined,
|
||||
{ workspaceId: "wks_parent" },
|
||||
);
|
||||
const server = await createAgentMcpServer(
|
||||
{
|
||||
agentManager,
|
||||
agentStorage: storage,
|
||||
callerAgentId: parent.id,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
},
|
||||
undefined,
|
||||
schedule,
|
||||
);
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager,
|
||||
agentStorage: storage,
|
||||
callerAgentId: parent.id,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
});
|
||||
return {
|
||||
agentManager,
|
||||
storage,
|
||||
@@ -4562,63 +4581,37 @@ describe("send_agent_prompt MCP tool to an OMP child", () => {
|
||||
{ command: "follow-up", streamingBehavior: "followUp" },
|
||||
{ command: "steer", streamingBehavior: "steer" },
|
||||
] as const)(
|
||||
"delivers /$command to a running OMP child while ordinary messages in the same quiet window wait",
|
||||
"delivers /$command into a turn OMP started on its own, without aborting it",
|
||||
async ({ command, streamingBehavior }) => {
|
||||
let flush!: () => void;
|
||||
const { agentManager, storage, workdir, ompSession, childId, tool } = await setupOmpChild(
|
||||
(_delay, callback) => {
|
||||
flush = callback;
|
||||
return () => {};
|
||||
},
|
||||
);
|
||||
const { agentManager, storage, workdir, parentClient, ompSession, childId, tool } =
|
||||
await setupOmpChild();
|
||||
try {
|
||||
ompSession.beginTurn();
|
||||
ompSession.streamAssistantText("background job finished, working on it");
|
||||
await vi.waitFor(() => {
|
||||
expect(agentManager.getAgent(childId)?.activeTurnId).toMatch(/^autonomous-/);
|
||||
});
|
||||
const activeTurnId = agentManager.getAgent(childId)?.activeTurnId;
|
||||
const delivery = toolDeliveries.get(tool)!;
|
||||
let ordinaryBeforeDispatch = 0;
|
||||
const ordinary = delivery.enqueue({
|
||||
recipientId: childId,
|
||||
source: { kind: "agent-message", agentId: "parent" },
|
||||
prompt: "ordinary follow-up",
|
||||
beforeDispatch: () => {
|
||||
ordinaryBeforeDispatch++;
|
||||
},
|
||||
|
||||
const response = await invokeToolWithParsedInput(tool, {
|
||||
agentId: childId,
|
||||
prompt: `/${command} then summarize the logs`,
|
||||
});
|
||||
const response = await invokeToolWithParsedInput(
|
||||
tool,
|
||||
{
|
||||
agentId: childId,
|
||||
prompt: `/${command} then summarize the logs`,
|
||||
},
|
||||
false,
|
||||
);
|
||||
flush();
|
||||
await vi.waitFor(() => {
|
||||
expect(ompSession.prompts).toEqual([
|
||||
{ message: "then summarize the logs", imageCount: 0, streamingBehavior },
|
||||
]);
|
||||
});
|
||||
expect(ordinaryBeforeDispatch).toBe(0);
|
||||
expect(agentManager.getAgent(childId)?.activeTurnId).toBe(activeTurnId);
|
||||
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
deliveryStatus: "queued",
|
||||
status: "running",
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(ompSession.prompts).toEqual([
|
||||
{ message: "then summarize the logs", imageCount: 0, streamingBehavior },
|
||||
]);
|
||||
});
|
||||
expect(ompSession.abortRequested).toBe(false);
|
||||
expect(agentManager.getAgent(childId)?.lifecycle).toBe("running");
|
||||
|
||||
ompSession.finishTurn();
|
||||
await ordinary.dispatched;
|
||||
expect(ordinaryBeforeDispatch).toBe(1);
|
||||
expect(ompSession.prompts).toHaveLength(2);
|
||||
expect(ompSession.prompts[1]!.message).toContain("ordinary follow-up");
|
||||
ompSession.beginTurn();
|
||||
ompSession.finishTurn();
|
||||
await expectOneFinishNotification(agentManager, parentClient, childId);
|
||||
} finally {
|
||||
await removeAgentStateDir(agentManager, storage, workdir);
|
||||
}
|
||||
|
||||
@@ -1949,11 +1949,7 @@ function mapSessionConfig(
|
||||
return {
|
||||
cwd: config.cwd,
|
||||
env: createProviderEnv({ baseEnv: {}, overlays: [launchContext?.env] }),
|
||||
systemPrompt: combineSystemPrompts(
|
||||
config.systemPrompt,
|
||||
config.daemonAppendSystemPrompt,
|
||||
...(config.pluginAppendSystemPrompt ?? []),
|
||||
),
|
||||
systemPrompt: combineSystemPrompts(config.systemPrompt, config.daemonAppendSystemPrompt),
|
||||
mcpServers: { ...config.mcpServers },
|
||||
toolPolicy: config.toolPolicy
|
||||
? { preapproved: config.toolPolicy.preapproved.map((grant) => ({ ...grant })) }
|
||||
@@ -1972,9 +1968,8 @@ function mapSessionConfig(
|
||||
function combineSystemPrompts(
|
||||
systemPrompt: string | undefined,
|
||||
daemonPrompt: string | undefined,
|
||||
...pluginPrompts: string[]
|
||||
): string | undefined {
|
||||
const parts = [systemPrompt, daemonPrompt, ...pluginPrompts].filter(
|
||||
const parts = [systemPrompt, daemonPrompt].filter(
|
||||
(value): value is string => typeof value === "string" && value.trim().length > 0,
|
||||
);
|
||||
return parts.length > 0 ? parts.join("\n\n") : undefined;
|
||||
|
||||
@@ -448,9 +448,6 @@ export function wrapSessionProvider(provider: AgentProvider, inner: AgentSession
|
||||
get initialTimeline() {
|
||||
return inner.initialTimeline;
|
||||
},
|
||||
get persistenceUpdatedOnResume() {
|
||||
return inner.persistenceUpdatedOnResume;
|
||||
},
|
||||
get controls() {
|
||||
return inner.controls;
|
||||
},
|
||||
|
||||
@@ -51,6 +51,7 @@ import {
|
||||
} from "./copilot-acp-agent.js";
|
||||
import { GenericACPAgentClient } from "./generic-acp-agent.js";
|
||||
import { parseKiroExtensionCommands } from "./kiro-acp-agent.js";
|
||||
import { transformPiModels } from "./pi/agent.js";
|
||||
import type { AgentStreamEvent } from "../agent-sdk-types.js";
|
||||
import type {
|
||||
AgentCapabilityFlags,
|
||||
@@ -2259,12 +2260,7 @@ describe("ACPAgentClient modelTransformer", () => {
|
||||
provider: "pi",
|
||||
logger: createTestLogger(),
|
||||
defaultCommand: ["test-acp"],
|
||||
modelTransformer: (models) =>
|
||||
models.map((model) => ({
|
||||
...model,
|
||||
label: model.label.split("/").at(-1) ?? model.label,
|
||||
description: model.id,
|
||||
})),
|
||||
modelTransformer: transformPiModels,
|
||||
});
|
||||
|
||||
await expect(
|
||||
@@ -2918,6 +2914,60 @@ describe("ACP providers advertise session listing", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("transformPiModels", () => {
|
||||
test("keeps slash-free labels unchanged", () => {
|
||||
expect(
|
||||
transformPiModels([
|
||||
{
|
||||
provider: "pi",
|
||||
id: "gpt-4.1-mini",
|
||||
label: "GPT 4.1 Mini",
|
||||
description: "Fast",
|
||||
},
|
||||
]),
|
||||
).toEqual([
|
||||
{
|
||||
provider: "pi",
|
||||
id: "gpt-4.1-mini",
|
||||
label: "GPT 4.1 Mini",
|
||||
description: "Fast",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("uses the last path segment as label and preserves existing descriptions", () => {
|
||||
expect(
|
||||
transformPiModels([
|
||||
{
|
||||
provider: "pi",
|
||||
id: "openrouter/openai/gpt-4.1-mini",
|
||||
label: "openrouter/openai/gpt-4.1-mini",
|
||||
description: undefined,
|
||||
},
|
||||
{
|
||||
provider: "pi",
|
||||
id: "anthropic/claude-sonnet-4",
|
||||
label: "anthropic/claude-sonnet-4",
|
||||
description: "Balanced",
|
||||
},
|
||||
]),
|
||||
).toEqual([
|
||||
{
|
||||
provider: "pi",
|
||||
id: "openrouter/openai/gpt-4.1-mini",
|
||||
label: "gpt-4.1-mini",
|
||||
description: "openrouter/openai/gpt-4.1-mini",
|
||||
},
|
||||
{
|
||||
provider: "pi",
|
||||
id: "anthropic/claude-sonnet-4",
|
||||
label: "claude-sonnet-4",
|
||||
description: "Balanced",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ACPAgentSession slash commands", () => {
|
||||
test("returns immediately for ACP sessions that do not wait for async command discovery", async () => {
|
||||
const session = new ACPAgentSession(
|
||||
|
||||
@@ -153,56 +153,6 @@ describe("Claude SDK env", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("resume uses current plugin instructions and excludes them from persistence", async () => {
|
||||
const prompts: unknown[] = [];
|
||||
const queryFactory = ({ options }: ClaudeQueryInput) => {
|
||||
prompts.push(options.systemPrompt);
|
||||
return createQueryMock([
|
||||
{
|
||||
type: "system",
|
||||
subtype: "init",
|
||||
session_id: "persisted-session",
|
||||
permissionMode: "default",
|
||||
model: "opus",
|
||||
},
|
||||
{ type: "assistant", message: { content: "done" } },
|
||||
{
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
usage: { input_tokens: 1, cache_read_input_tokens: 0, output_tokens: 1 },
|
||||
total_cost_usd: 0,
|
||||
},
|
||||
]);
|
||||
};
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
queryFactory,
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
});
|
||||
const first = await client.createSession({
|
||||
provider: "claude",
|
||||
cwd: process.cwd(),
|
||||
pluginAppendSystemPrompt: ["Plugin instructions"],
|
||||
});
|
||||
await first.run("first");
|
||||
const handle = first.describePersistence()!;
|
||||
expect(handle.metadata).not.toHaveProperty("pluginAppendSystemPrompt");
|
||||
await first.close();
|
||||
const resumed = await client.resumeSession(handle, {
|
||||
cwd: process.cwd(),
|
||||
pluginAppendSystemPrompt: undefined,
|
||||
});
|
||||
try {
|
||||
await resumed.run("after disable");
|
||||
expect(prompts).toEqual([
|
||||
{ type: "preset", preset: "claude_code", append: "Plugin instructions" },
|
||||
{ type: "preset", preset: "claude_code", append: "" },
|
||||
]);
|
||||
} finally {
|
||||
await resumed.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("forwards launch-context env through Claude resume env", async () => {
|
||||
let capturedEnv: Record<string, string | undefined> | undefined;
|
||||
const launchContext: AgentLaunchContext = {
|
||||
|
||||
@@ -83,7 +83,7 @@ import {
|
||||
type ClaudeProviderOptions,
|
||||
} from "./options.js";
|
||||
import { renderPromptAttachmentAsText } from "../../prompt-attachments.js";
|
||||
import { discoverClaudeModels, killExitingClaudeModelDiscoveries } from "./model-discovery.js";
|
||||
import { discoverClaudeModels } from "./model-discovery.js";
|
||||
import { claudeQuery, type ClaudeOptions, type ClaudeQueryFactory } from "./query.js";
|
||||
import {
|
||||
findSteeredMessageParent,
|
||||
@@ -1751,10 +1751,6 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
};
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
await killExitingClaudeModelDiscoveries();
|
||||
}
|
||||
|
||||
async resolveDefaultModeId({ env: launchEnv }: ResolveAgentDefaultModeInput): Promise<string> {
|
||||
return claudeModeCatalog(this.buildProviderEnv(launchEnv)).defaultModeId;
|
||||
}
|
||||
@@ -3048,11 +3044,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
if (!this.claudeSessionId) {
|
||||
return null;
|
||||
}
|
||||
const {
|
||||
providerOptions: _providerOptions,
|
||||
pluginAppendSystemPrompt: _pluginAppendSystemPrompt,
|
||||
...persistedConfig
|
||||
} = this.config;
|
||||
const { providerOptions: _providerOptions, ...persistedConfig } = this.config;
|
||||
this.persistence = {
|
||||
provider: "claude",
|
||||
sessionId: this.claudeSessionId,
|
||||
@@ -3720,11 +3712,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
|
||||
private buildAppendedSystemPrompt(): string {
|
||||
return (
|
||||
composeSystemPromptParts(
|
||||
this.config.systemPrompt,
|
||||
this.config.daemonAppendSystemPrompt,
|
||||
...(this.config.pluginAppendSystemPrompt ?? []),
|
||||
) ?? ""
|
||||
composeSystemPromptParts(this.config.systemPrompt, this.config.daemonAppendSystemPrompt) ?? ""
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,10 +6,6 @@ import type { ProviderRuntimeSettings } from "../../provider-launch-config.js";
|
||||
import { terminateWithTreeKill } from "../../../../utils/tree-kill.js";
|
||||
import { claudeQuery, type ClaudeQueryInput, type ClaudeQueryContext } from "./query.js";
|
||||
|
||||
const DISCOVERY_WAIT_MS = 5_000;
|
||||
// Long enough for the CLI to finish an OAuth token refresh it started before the wait ended.
|
||||
const DISCOVERY_EXIT_GRACE_MS = 60_000;
|
||||
|
||||
interface ClaudeModelDiscoveryOptions {
|
||||
resolveBinary: () => Promise<string>;
|
||||
runtimeSettings?: ProviderRuntimeSettings;
|
||||
@@ -22,24 +18,19 @@ type OpenDiscoveryQuery = (
|
||||
context: ClaudeQueryContext,
|
||||
) => Pick<Query, "supportedModels" | "close">;
|
||||
|
||||
type DiscoveryQuery = ReturnType<OpenDiscoveryQuery>;
|
||||
|
||||
// Discovery processes left to exit on their own after their caller stopped waiting.
|
||||
const exitingDiscoveries = new Map<ChildProcess, () => Promise<void>>();
|
||||
|
||||
// The curated catalog survives a failed or slow probe. This process never receives
|
||||
// a prompt and must not persist a session or launch user MCP servers/hooks.
|
||||
export async function discoverClaudeModels(
|
||||
options: ClaudeModelDiscoveryOptions,
|
||||
openQuery: OpenDiscoveryQuery = claudeQuery,
|
||||
): Promise<ModelInfo[]> {
|
||||
const waitController = new AbortController();
|
||||
const controller = new AbortController();
|
||||
const signal = options.signal
|
||||
? AbortSignal.any([options.signal, waitController.signal])
|
||||
: waitController.signal;
|
||||
? AbortSignal.any([options.signal, controller.signal])
|
||||
: controller.signal;
|
||||
const timer = setTimeout(
|
||||
() => waitController.abort(new Error("Claude model discovery timed out")),
|
||||
DISCOVERY_WAIT_MS,
|
||||
() => controller.abort(new Error("Claude model discovery timed out")),
|
||||
5_000,
|
||||
);
|
||||
let endInput!: () => void;
|
||||
const ended = new Promise<void>((resolve) => {
|
||||
@@ -55,7 +46,7 @@ export async function discoverClaudeModels(
|
||||
};
|
||||
},
|
||||
};
|
||||
let query: DiscoveryQuery | undefined;
|
||||
let query: ReturnType<OpenDiscoveryQuery> | undefined;
|
||||
let child: ChildProcess | undefined;
|
||||
try {
|
||||
signal.throwIfAborted();
|
||||
@@ -73,8 +64,7 @@ export async function discoverClaudeModels(
|
||||
strictMcpConfig: true,
|
||||
settingSources: ["user"],
|
||||
settings: { disableAllHooks: true },
|
||||
// No abortController: the SDK kills the process when it aborts, and the end of
|
||||
// the wait must not.
|
||||
abortController: controller,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -88,56 +78,12 @@ export async function discoverClaudeModels(
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
endInput();
|
||||
if (query && child && !hasExited(child)) {
|
||||
// The CLI may be refreshing an expired OAuth token, even after it has answered.
|
||||
// Claude Code rotates the refresh token before saving the new pair, so killing it now
|
||||
// leaves a revoked token on disk and logs the user out (#9314). With its input ended
|
||||
// it exits once that work is done; the grace period and daemon shutdown bound the wait.
|
||||
letDiscoveryExit(query, child);
|
||||
} else {
|
||||
await retireDiscovery(query, child);
|
||||
try {
|
||||
query?.close();
|
||||
} finally {
|
||||
if (child) {
|
||||
await terminateWithTreeKill(child, { gracefulTimeoutMs: 200, forceTimeoutMs: 200 });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Kills discovery processes still exiting after their wait ended. Called on daemon shutdown. */
|
||||
export async function killExitingClaudeModelDiscoveries(): Promise<void> {
|
||||
await Promise.all(Array.from(exitingDiscoveries.values(), (kill) => kill()));
|
||||
}
|
||||
|
||||
function letDiscoveryExit(query: DiscoveryQuery, child: ChildProcess): void {
|
||||
function forget(): void {
|
||||
clearTimeout(graceTimer);
|
||||
child.off("exit", onExit);
|
||||
exitingDiscoveries.delete(child);
|
||||
}
|
||||
function onExit(): void {
|
||||
forget();
|
||||
query.close();
|
||||
}
|
||||
async function kill(): Promise<void> {
|
||||
forget();
|
||||
await retireDiscovery(query, child);
|
||||
}
|
||||
const graceTimer = setTimeout(() => void kill(), DISCOVERY_EXIT_GRACE_MS);
|
||||
graceTimer.unref();
|
||||
child.once("exit", onExit);
|
||||
exitingDiscoveries.set(child, kill);
|
||||
}
|
||||
|
||||
async function retireDiscovery(
|
||||
query: DiscoveryQuery | undefined,
|
||||
child: ChildProcess | undefined,
|
||||
): Promise<void> {
|
||||
try {
|
||||
query?.close();
|
||||
} finally {
|
||||
if (child) {
|
||||
await terminateWithTreeKill(child, { gracefulTimeoutMs: 200, forceTimeoutMs: 200 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function hasExited(child: ChildProcess): boolean {
|
||||
return child.exitCode !== null || child.signalCode !== null;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { ChildProcess } from "node:child_process";
|
||||
import * as fs from "node:fs/promises";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
@@ -1174,127 +1173,4 @@ describe("Claude model discovery process", () => {
|
||||
await expect(result).rejects.toBe(failure);
|
||||
expect(closed).toBe(true);
|
||||
});
|
||||
|
||||
describe("when the CLI is still starting up at the deadline", () => {
|
||||
// Without a pid, terminateWithTreeKill signals the child directly instead of a real tree.
|
||||
class StartingClaudeProcess extends ChildProcess {
|
||||
readonly signals: string[] = [];
|
||||
override kill(signal?: NodeJS.Signals | number): boolean {
|
||||
this.signals.push(String(signal));
|
||||
this.emit("exit", null, signal);
|
||||
return true;
|
||||
}
|
||||
exitOnItsOwn(): void {
|
||||
this.emit("exit", 0, null);
|
||||
}
|
||||
}
|
||||
|
||||
interface StalledDiscoveryState {
|
||||
closed: boolean;
|
||||
inputEnded: boolean;
|
||||
}
|
||||
|
||||
async function recordInputEnd(
|
||||
prompt: AsyncIterable<unknown>,
|
||||
state: StalledDiscoveryState,
|
||||
): Promise<void> {
|
||||
await prompt[Symbol.asyncIterator]().next();
|
||||
state.inputEnded = true;
|
||||
}
|
||||
|
||||
// By default the CLI never answers: an expired OAuth token is refreshed first.
|
||||
function startStalledDiscovery(
|
||||
supportedModels: () => Promise<ModelInfo[]> = () => new Promise<ModelInfo[]>(() => {}),
|
||||
) {
|
||||
const child = new StartingClaudeProcess();
|
||||
const state: StalledDiscoveryState = { closed: false, inputEnded: false };
|
||||
const result = discoverClaudeModels(
|
||||
{ resolveBinary: async () => "/claude", env: {} },
|
||||
(input, context) => {
|
||||
if (typeof input.prompt === "string") throw new Error("unexpected inference prompt");
|
||||
void recordInputEnd(input.prompt, state);
|
||||
context.onChildProcess?.(child);
|
||||
return {
|
||||
supportedModels,
|
||||
close: () => {
|
||||
state.closed = true;
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
return { child, state, result };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("stops waiting at the limit but lets the CLI finish instead of killing it", async () => {
|
||||
vi.useFakeTimers();
|
||||
const { child, state, result } = startStalledDiscovery();
|
||||
const settled = expect(result).rejects.toThrow("Claude model discovery timed out");
|
||||
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
await settled;
|
||||
expect(state.inputEnded).toBe(true);
|
||||
expect(child.signals).toEqual([]);
|
||||
expect(state.closed).toBe(false);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(59_999);
|
||||
expect(child.signals).toEqual([]);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(child.signals).toEqual(["SIGTERM"]);
|
||||
expect(state.closed).toBe(true);
|
||||
});
|
||||
|
||||
async function answerAtOnce(): Promise<ModelInfo[]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
it("lets the CLI finish after it answers instead of killing it", async () => {
|
||||
// The CLI answers supportedModels() before its startup token refresh has saved the
|
||||
// rotated refresh token, so a kill right after the answer also logs the user out.
|
||||
vi.useFakeTimers();
|
||||
const { child, state, result } = startStalledDiscovery(answerAtOnce);
|
||||
await expect(result).resolves.toEqual([]);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(state.inputEnded).toBe(true);
|
||||
expect(child.signals).toEqual([]);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
child.exitOnItsOwn();
|
||||
expect(state.closed).toBe(true);
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
expect(child.signals).toEqual([]);
|
||||
});
|
||||
|
||||
it("never signals a CLI that exits on its own during the grace period", async () => {
|
||||
vi.useFakeTimers();
|
||||
const { child, state, result } = startStalledDiscovery();
|
||||
const settled = expect(result).rejects.toThrow("Claude model discovery timed out");
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
await settled;
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2_000);
|
||||
child.exitOnItsOwn();
|
||||
expect(state.closed).toBe(true);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
expect(child.signals).toEqual([]);
|
||||
});
|
||||
|
||||
it("tree-kills a still-running CLI when the daemon shuts down", async () => {
|
||||
vi.useFakeTimers();
|
||||
const { child, state, result } = startStalledDiscovery();
|
||||
const settled = expect(result).rejects.toThrow("Claude model discovery timed out");
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
await settled;
|
||||
expect(child.signals).toEqual([]);
|
||||
|
||||
await new ClaudeAgentClient({ logger: createTestLogger() }).shutdown();
|
||||
expect(child.signals).toEqual(["SIGTERM"]);
|
||||
expect(state.closed).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+1
-92
@@ -22,18 +22,6 @@ function isCodexInstalled(): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function supportsInstructionSnapshots(): boolean {
|
||||
try {
|
||||
const match = execFileSync("codex", ["--version"], { encoding: "utf8" }).match(
|
||||
/(\d+)\.(\d+)\.(\d+)/,
|
||||
);
|
||||
if (!match) return false;
|
||||
return Number(match[1]) > 0 || Number(match[2]) >= 121;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function sse(events: unknown[]): string {
|
||||
return events
|
||||
.map((event) => {
|
||||
@@ -145,7 +133,7 @@ async function startMockResponsesServer(sequence: string[]): Promise<{
|
||||
}> {
|
||||
const requestBodies: string[] = [];
|
||||
let index = 0;
|
||||
const server = createServer({ maxHeaderSize: 1024 * 1024 }, (req, res) => {
|
||||
const server = createServer((req, res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
req.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
|
||||
req.on("end", () => {
|
||||
@@ -233,85 +221,6 @@ function waitForEvent<TEvent extends AgentStreamEvent>(params: {
|
||||
}
|
||||
|
||||
describe("Codex app-server provider (local e2e)", () => {
|
||||
test.runIf(supportsInstructionSnapshots())(
|
||||
"delivers changed and removed instructions to the model across process restarts",
|
||||
async () => {
|
||||
const artifactDir = path.resolve(process.cwd(), "../../.artifacts");
|
||||
mkdirSync(artifactDir, { recursive: true });
|
||||
const cwd = mkdtempSync(path.join(artifactDir, "codex-snapshot-cwd-"));
|
||||
const codexHome = mkdtempSync(path.join(artifactDir, "codex-snapshot-home-"));
|
||||
const server = await startMockResponsesServer([]);
|
||||
const client = new CodexAppServerAgentClient(createTestLogger());
|
||||
const base = { provider: "codex" as const, cwd, modeId: "auto", model: "mock-model" };
|
||||
const launch = { env: { CODEX_HOME: codexHome } };
|
||||
const run = async (session: Awaited<ReturnType<typeof client.createSession>>) => {
|
||||
const finished = waitForEvent({
|
||||
session,
|
||||
timeoutMs: 20_000,
|
||||
label: "turn completion",
|
||||
predicate: (
|
||||
event,
|
||||
): event is Extract<
|
||||
AgentStreamEvent,
|
||||
{ type: "turn_completed" | "turn_failed" | "turn_canceled" }
|
||||
> =>
|
||||
event.type === "turn_completed" ||
|
||||
event.type === "turn_failed" ||
|
||||
event.type === "turn_canceled",
|
||||
});
|
||||
await session.startTurn("continue");
|
||||
const result = await finished;
|
||||
if (result.type !== "turn_completed") throw new Error(JSON.stringify(result));
|
||||
const handle = session.describePersistence();
|
||||
if (!handle) throw new Error("Expected persisted Codex thread");
|
||||
await session.close();
|
||||
return handle;
|
||||
};
|
||||
try {
|
||||
writeMockCodexConfig(codexHome, server.url);
|
||||
let handle = await run(
|
||||
await client.createSession(
|
||||
{ ...base, pluginAppendSystemPrompt: ["old snapshot"] },
|
||||
launch,
|
||||
),
|
||||
);
|
||||
expect(server.requestBodies.at(-1)).toContain("old snapshot");
|
||||
expect(server.requestBodies.at(-1)).not.toContain("paseo_instruction_snapshot");
|
||||
handle = await run(
|
||||
await client.resumeSession(
|
||||
handle,
|
||||
{ ...base, pluginAppendSystemPrompt: ["new snapshot"] },
|
||||
launch,
|
||||
),
|
||||
);
|
||||
expect(server.requestBodies.at(-1)).toContain("new snapshot");
|
||||
expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(2);
|
||||
handle = await run(
|
||||
await client.resumeSession(
|
||||
handle,
|
||||
{ ...base, pluginAppendSystemPrompt: ["new snapshot"] },
|
||||
launch,
|
||||
),
|
||||
);
|
||||
expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(2);
|
||||
await run(
|
||||
await client.resumeSession(
|
||||
handle,
|
||||
{ ...base, pluginAppendSystemPrompt: undefined },
|
||||
launch,
|
||||
),
|
||||
);
|
||||
expect(server.requestBodies.at(-1)).toContain('\\"instructions\\":\\"\\"');
|
||||
expect(server.requestBodies.at(-1)?.match(/paseo_instruction_snapshot/g)).toHaveLength(4);
|
||||
} finally {
|
||||
await server.close();
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
rmSync(codexHome, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
|
||||
test.runIf(isCodexInstalled())(
|
||||
"concurrent import scans initialize successfully in a fresh shared Codex home",
|
||||
async () => {
|
||||
|
||||
@@ -7,7 +7,6 @@ import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { PassThrough } from "node:stream";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { CodexInstructionSnapshot } from "./codex/instruction-snapshot.js";
|
||||
|
||||
import type {
|
||||
AgentClient,
|
||||
@@ -101,7 +100,6 @@ import {
|
||||
import { createTestLogger } from "../../../test-utils/test-logger.js";
|
||||
import { asInternals as castInternals, createStub } from "../../test-utils/class-mocks.js";
|
||||
import { AgentManager } from "../agent-manager.js";
|
||||
import { AgentStorage } from "../agent-storage.js";
|
||||
import { buildProviderRegistry } from "../provider-registry.js";
|
||||
|
||||
interface CollaborationModeRecord {
|
||||
@@ -175,9 +173,6 @@ function createSession(
|
||||
) as CodexTestSession;
|
||||
session.connectionState = "connected";
|
||||
session.currentThreadId = "test-thread";
|
||||
castInternals<{ instructionSnapshot: { recordNewThread(id: string): void } }>(
|
||||
session,
|
||||
).instructionSnapshot.recordNewThread("test-thread");
|
||||
session.activeForegroundTurnId = "test-turn";
|
||||
return session;
|
||||
}
|
||||
@@ -688,7 +683,7 @@ function codexAgentItem(text: string) {
|
||||
|
||||
// An AgentManager over a real Codex provider whose every spawn gets a fresh fake
|
||||
// app-server serving `threads` from thread/read.
|
||||
function createReopenableCodexAgent(threads: Record<string, unknown[]>, registry?: AgentStorage) {
|
||||
function createReopenableCodexAgent(threads: Record<string, unknown[]>) {
|
||||
const appServers: FakeCodexAppServer[] = [];
|
||||
const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, {
|
||||
appServerProcess: createFakeCodexAppServerProcess(() => {
|
||||
@@ -720,11 +715,7 @@ function createReopenableCodexAgent(threads: Record<string, unknown[]>, registry
|
||||
},
|
||||
resumeSession: (...args) => provider.resumeSession(...args),
|
||||
};
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: client },
|
||||
registry,
|
||||
logger: createTestLogger(),
|
||||
});
|
||||
const manager = new AgentManager({ clients: { codex: client }, logger: createTestLogger() });
|
||||
const agentId = "00000000-0000-4000-8000-000000000001";
|
||||
const handle = { provider: "codex", sessionId: "saved-thread" };
|
||||
const config = createConfig({ cwd: process.cwd() });
|
||||
@@ -737,9 +728,6 @@ function createReopenableCodexAgent(threads: Record<string, unknown[]>, registry
|
||||
return {
|
||||
manager,
|
||||
agentId,
|
||||
handle,
|
||||
config,
|
||||
appServers,
|
||||
latestAppServer: () => appServers[appServers.length - 1],
|
||||
threadMethods: (index: number) =>
|
||||
appServers[index]
|
||||
@@ -1418,216 +1406,6 @@ describe("Codex app-server provider", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("reopening drops disabled plugin instructions and starts with fresh collaboration settings", async () => {
|
||||
const modes = {
|
||||
data: [
|
||||
{
|
||||
name: "Code",
|
||||
mode: "default",
|
||||
model: null,
|
||||
reasoning_effort: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
const firstServer = createFakeCodexAppServer({ "collaborationMode/list": () => modes });
|
||||
const first = await createProviderWithFakeAppServer(firstServer).createSession(
|
||||
createConfig({ pluginAppendSystemPrompt: ["Plugin instructions"] }),
|
||||
);
|
||||
await first.startTurn("first");
|
||||
const firstTurn = await firstServer.waitForTurnStart();
|
||||
expect(
|
||||
firstServer.requests().find((request) => request.method === "thread/start")?.params,
|
||||
).toMatchObject({ developerInstructions: "Plugin instructions" });
|
||||
expect(firstTurn).toMatchObject({
|
||||
collaborationMode: {
|
||||
settings: { developer_instructions: null },
|
||||
},
|
||||
});
|
||||
const started = waitForNextEvent(first, "thread_started");
|
||||
firstServer.startsTurn({ threadId: "thread-1" });
|
||||
await started;
|
||||
const handle = first.describePersistence()!;
|
||||
expect(handle.metadata).not.toHaveProperty("pluginAppendSystemPrompt");
|
||||
await first.close();
|
||||
|
||||
const secondServer = createFakeCodexAppServer({ "collaborationMode/list": () => modes });
|
||||
const resumed = await createProviderWithFakeAppServer(secondServer).resumeSession(handle, {
|
||||
pluginAppendSystemPrompt: undefined,
|
||||
});
|
||||
try {
|
||||
const resume = secondServer.requests().find((request) => request.method === "thread/resume");
|
||||
expect(resume?.params).not.toHaveProperty("developerInstructions");
|
||||
await resumed.startTurn("after disable");
|
||||
const secondTurn = await secondServer.waitForTurnStart();
|
||||
expect(secondTurn).not.toHaveProperty("developerInstructions");
|
||||
expect(secondTurn).toMatchObject({
|
||||
collaborationMode: { settings: { developer_instructions: null } },
|
||||
});
|
||||
firstServer.assertNoErrors();
|
||||
secondServer.assertNoErrors();
|
||||
} finally {
|
||||
await resumed.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("reopen injects current instructions once, including an explicit empty snapshot", async () => {
|
||||
const handlers = {
|
||||
initialize: () => ({ userAgent: "codex/0.165.0" }),
|
||||
"thread/inject_items": () => ({}),
|
||||
};
|
||||
const firstServer = createFakeCodexAppServer(handlers);
|
||||
const first = await createProviderWithFakeAppServer(firstServer).createSession(
|
||||
createConfig({ pluginAppendSystemPrompt: ["Old plugin"] }),
|
||||
);
|
||||
await first.startTurn("first");
|
||||
const started = waitForNextEvent(first, "thread_started");
|
||||
firstServer.startsTurn({ threadId: "thread-1" });
|
||||
await started;
|
||||
expect(
|
||||
firstServer.requests().filter((request) => request.method === "thread/inject_items"),
|
||||
).toEqual([]);
|
||||
const original = first.describePersistence()!;
|
||||
expect(original.metadata).toHaveProperty("paseoInstructionReceipt");
|
||||
await first.close();
|
||||
|
||||
const changedServer = createFakeCodexAppServer(handlers);
|
||||
const changed = await createProviderWithFakeAppServer(changedServer).resumeSession(original, {
|
||||
pluginAppendSystemPrompt: ["New plugin"],
|
||||
});
|
||||
const injected = changedServer
|
||||
.requests()
|
||||
.filter((request) => request.method === "thread/inject_items");
|
||||
expect(injected).toHaveLength(1);
|
||||
expect(JSON.stringify(injected[0]?.params)).toContain("New plugin");
|
||||
const changedHandle = changed.describePersistence()!;
|
||||
expect(changedHandle.metadata?.paseoInstructionReceipt).not.toEqual(
|
||||
original.metadata?.paseoInstructionReceipt,
|
||||
);
|
||||
await changed.close();
|
||||
|
||||
const sameServer = createFakeCodexAppServer(handlers);
|
||||
const same = await createProviderWithFakeAppServer(sameServer).resumeSession(changedHandle, {
|
||||
pluginAppendSystemPrompt: ["New plugin"],
|
||||
});
|
||||
expect(
|
||||
sameServer.requests().filter((request) => request.method === "thread/inject_items"),
|
||||
).toEqual([]);
|
||||
await same.close();
|
||||
|
||||
const emptyServer = createFakeCodexAppServer(handlers);
|
||||
const empty = await createProviderWithFakeAppServer(emptyServer).resumeSession(changedHandle, {
|
||||
pluginAppendSystemPrompt: undefined,
|
||||
});
|
||||
const removal = emptyServer
|
||||
.requests()
|
||||
.filter((request) => request.method === "thread/inject_items");
|
||||
expect(removal).toHaveLength(1);
|
||||
expect(JSON.stringify(removal[0]?.params)).toContain('\\"instructions\\":\\"\\"');
|
||||
await empty.close();
|
||||
});
|
||||
|
||||
test("requires a compatible Codex version before creating a thread with plugin instructions", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
initialize: () => ({ userAgent: "codex/0.120.0" }),
|
||||
});
|
||||
await expect(
|
||||
createProviderWithFakeAppServer(appServer).createSession(
|
||||
createConfig({ pluginAppendSystemPrompt: ["Plugin instructions"] }),
|
||||
),
|
||||
).rejects.toThrow("Update Codex to 0.121.0 or newer");
|
||||
});
|
||||
|
||||
test("retries an instruction snapshot when injection fails", async () => {
|
||||
const snapshot = new CodexInstructionSnapshot("current", undefined);
|
||||
const request = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error("connection lost"))
|
||||
.mockResolvedValue({});
|
||||
await expect(snapshot.apply("thread-1", request, true)).rejects.toThrow("connection lost");
|
||||
expect(snapshot.describe("thread-1")).toBeUndefined();
|
||||
await snapshot.apply("thread-1", request, true);
|
||||
expect(snapshot.describe("thread-1")).toEqual({
|
||||
threadId: "thread-1",
|
||||
digest: expect.any(String),
|
||||
});
|
||||
await snapshot.apply("thread-1", request, true);
|
||||
expect(request).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("keeps built-in Plan instructions while sending plugin instructions to the thread", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"collaborationMode/list": () => ({
|
||||
data: [
|
||||
{ name: "Plan", mode: "plan", model: null, reasoning_effort: "medium" },
|
||||
{ name: "Default", mode: "default", model: null, reasoning_effort: null },
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = await createProviderWithFakeAppServer(appServer).createSession(
|
||||
createConfig({
|
||||
pluginAppendSystemPrompt: ["Plugin instructions"],
|
||||
providerOptions: { plan_mode: true },
|
||||
}),
|
||||
);
|
||||
try {
|
||||
await session.startTurn("make a plan");
|
||||
const start = appServer.requests().find((request) => request.method === "thread/start");
|
||||
expect(start?.params).toMatchObject({ developerInstructions: "Plugin instructions" });
|
||||
expect(await appServer.waitForTurnStart()).toMatchObject({
|
||||
collaborationMode: { mode: "plan", settings: { developer_instructions: null } },
|
||||
});
|
||||
expect(
|
||||
appServer.requests().find((request) => request.method === "turn/start")?.params,
|
||||
).not.toHaveProperty("developerInstructions");
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ instructions: undefined, expected: undefined },
|
||||
{ instructions: ["Current plugin"], expected: "Current plugin" },
|
||||
])(
|
||||
"rebuilds restored instructions with an unavailable collaboration catalog: $expected",
|
||||
async ({ instructions, expected }) => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"collaborationMode/list": () => ({ data: [] }),
|
||||
"thread/resume": () => ({
|
||||
thread: { id: "saved-thread" },
|
||||
collaborationMode: {
|
||||
mode: "default",
|
||||
settings: {
|
||||
model: "gpt-5.4",
|
||||
reasoning_effort: "medium",
|
||||
developer_instructions: "Old plugin",
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
const session = await createProviderWithFakeAppServer(appServer).resumeSession(
|
||||
{ sessionId: "saved-thread" },
|
||||
{ pluginAppendSystemPrompt: instructions },
|
||||
);
|
||||
try {
|
||||
const resume = appServer.requests().find((request) => request.method === "thread/resume");
|
||||
if (expected) expect(resume?.params).toMatchObject({ developerInstructions: expected });
|
||||
else expect(resume?.params).not.toHaveProperty("developerInstructions");
|
||||
await session.startTurn("after reopen");
|
||||
const turn = await appServer.waitForTurnStart();
|
||||
expect(turn).toMatchObject({
|
||||
collaborationMode: {
|
||||
mode: "default",
|
||||
settings: { model: "gpt-5.4", developer_instructions: null },
|
||||
},
|
||||
});
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("keeps the default effort when a session without one is resumed after a restart", async () => {
|
||||
const beforeRestart = createFakeCodexAppServer();
|
||||
const firstSession = await createProviderWithFakeAppServer(beforeRestart).createSession(
|
||||
@@ -2437,36 +2215,6 @@ describe("Codex app-server provider", () => {
|
||||
appServer.assertNoErrors();
|
||||
});
|
||||
|
||||
test("lets idle cleanup release a session opened only to read its history", async () => {
|
||||
let spawns = 0;
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"thread/resume": () =>
|
||||
Promise.reject(new Error(archivedThreadErrorMessage("archived-thread-id"))),
|
||||
"thread/read": () => ({ thread: { turns: [] } }),
|
||||
});
|
||||
const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, {
|
||||
appServerProcess: createFakeCodexAppServerProcess(() => {
|
||||
spawns += 1;
|
||||
return appServer.child;
|
||||
}),
|
||||
});
|
||||
const internals = castInternals<{
|
||||
goalsEnabledPromise: Promise<boolean> | null;
|
||||
autoReviewEnabledPromise: Promise<boolean> | null;
|
||||
}>(provider);
|
||||
internals.goalsEnabledPromise = Promise.resolve(false);
|
||||
internals.autoReviewEnabledPromise = Promise.resolve(false);
|
||||
|
||||
const session = await provider.resumeSession(archivedThreadHandle(), undefined, undefined, {
|
||||
purpose: "history",
|
||||
});
|
||||
|
||||
expect(await session.canStopRuntime!()).toBe(true);
|
||||
expect(spawns).toBe(1);
|
||||
await session.close();
|
||||
appServer.assertNoErrors();
|
||||
});
|
||||
|
||||
test("unarchives Codex when an active Paseo agent resumes an archived thread", async () => {
|
||||
const threadRequests: string[] = [];
|
||||
let resumeAttempts = 0;
|
||||
@@ -2537,12 +2285,7 @@ describe("Codex app-server provider", () => {
|
||||
]);
|
||||
// Background terminal observation is independent of conversation history loading.
|
||||
const historyMethods = (index: number) =>
|
||||
codex
|
||||
.threadMethods(index)
|
||||
.filter(
|
||||
(method) =>
|
||||
method !== "thread/backgroundTerminals/list" && method !== "thread/inject_items",
|
||||
);
|
||||
codex.threadMethods(index).filter((method) => method !== "thread/backgroundTerminals/list");
|
||||
expect(historyMethods(0)).toEqual([
|
||||
"thread/loaded/list",
|
||||
"thread/resume",
|
||||
@@ -2556,34 +2299,6 @@ describe("Codex app-server provider", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("persists an acknowledged instruction snapshot before a turn on repeated opens", async () => {
|
||||
const artifactDir = path.resolve(process.cwd(), "../../.artifacts");
|
||||
mkdirSync(artifactDir, { recursive: true });
|
||||
const dir = await mkdtemp(path.join(artifactDir, "codex-receipt-"));
|
||||
const storage = new AgentStorage(dir, createTestLogger());
|
||||
const codex = createReopenableCodexAgent({}, storage);
|
||||
try {
|
||||
let handle = codex.handle;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await codex.manager.resumeAgentFromPersistence(handle, codex.config, codex.agentId);
|
||||
await storage.flush();
|
||||
const saved = await storage.get(codex.agentId);
|
||||
expect(saved?.persistence?.metadata?.paseoInstructionReceipt).toEqual(expect.any(Object));
|
||||
handle = saved!.persistence!;
|
||||
await codex.manager.closeAgent(codex.agentId);
|
||||
}
|
||||
expect(
|
||||
codex.appServers
|
||||
.flatMap((server) => server.requests())
|
||||
.filter((request) => request.method === "thread/inject_items"),
|
||||
).toHaveLength(1);
|
||||
} finally {
|
||||
if (codex.manager.getAgent(codex.agentId)) await codex.manager.closeAgent(codex.agentId);
|
||||
await storage.flush();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("rewinds an agent reopened without reading its Codex history", async () => {
|
||||
const firstTurn = {
|
||||
id: "turn-1",
|
||||
@@ -3103,9 +2818,6 @@ describe("Codex app-server provider", () => {
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({
|
||||
cwd: "/workspace/project",
|
||||
systemPrompt: "Agent instructions",
|
||||
daemonAppendSystemPrompt: "Daemon instructions",
|
||||
pluginAppendSystemPrompt: ["Plugin instructions"],
|
||||
mcpServers: {
|
||||
paseo: { type: "http", url: "http://127.0.0.1:6767/mcp/agents?callerAgentId=agent-1" },
|
||||
},
|
||||
@@ -3137,24 +2849,6 @@ describe("Codex app-server provider", () => {
|
||||
|
||||
await session.revertConversation({ messageId: "codex-first" });
|
||||
|
||||
const forkRequest = appServer.requests().find((request) => request.method === "thread/fork");
|
||||
expect(forkRequest?.params).toMatchObject({
|
||||
developerInstructions: "Agent instructions\n\nDaemon instructions\n\nPlugin instructions",
|
||||
});
|
||||
const rewindRequests = appServer
|
||||
.requests()
|
||||
.filter((request) =>
|
||||
["thread/fork", "thread/rollback", "thread/inject_items"].includes(
|
||||
String(request.method),
|
||||
),
|
||||
);
|
||||
expect(rewindRequests.map((request) => request.method)).toEqual(
|
||||
historyMode === "legacy"
|
||||
? ["thread/fork", "thread/rollback", "thread/inject_items"]
|
||||
: ["thread/fork", "thread/inject_items"],
|
||||
);
|
||||
expect(rewindRequests.at(-1)?.params).toMatchObject({ threadId: "forked-thread" });
|
||||
expect(JSON.stringify(rewindRequests.at(-1)?.params)).toContain("Plugin instructions");
|
||||
const forkConfigs = appServer
|
||||
.requests()
|
||||
.filter((request) => request.method === "thread/fork")
|
||||
|
||||
@@ -55,8 +55,7 @@ import path from "node:path";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { z } from "zod";
|
||||
import { renderPromptAttachmentAsText } from "../prompt-attachments.js";
|
||||
import { composeAgentSystemPrompt } from "../system-prompt.js";
|
||||
import { CodexInstructionSnapshot } from "./codex/instruction-snapshot.js";
|
||||
import { composeSystemPromptParts } from "../system-prompt.js";
|
||||
import { CodexAsyncQuestions, codexAsyncQuestionToTimeline } from "./codex/async-questions.js";
|
||||
import {
|
||||
fileChangesToPreview,
|
||||
@@ -3592,12 +3591,9 @@ interface ConsumedRootCompaction {
|
||||
export class CodexAppServerAgentSession implements AgentSession {
|
||||
readonly provider = CODEX_PROVIDER;
|
||||
readonly capabilities = CODEX_APP_SERVER_CAPABILITIES;
|
||||
readonly persistenceUpdatedOnResume = true;
|
||||
|
||||
private readonly logger: Logger;
|
||||
private readonly config: AgentSessionConfig;
|
||||
private readonly instructionSnapshot: CodexInstructionSnapshot;
|
||||
private supportsInstructionSnapshots = false;
|
||||
private readonly asyncQuestions: CodexAsyncQuestions;
|
||||
private readonly codexHome: string;
|
||||
private currentMode: string;
|
||||
@@ -3710,13 +3706,6 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
reasoning_effort?: string | null;
|
||||
developer_instructions?: string | null;
|
||||
}> = [];
|
||||
private restoredCollaborationMode: {
|
||||
name: string;
|
||||
mode: string;
|
||||
model: string;
|
||||
reasoning_effort: string | null;
|
||||
developer_instructions?: never;
|
||||
} | null = null;
|
||||
private resolvedCollaborationMode: {
|
||||
mode: string;
|
||||
settings: Record<string, unknown>;
|
||||
@@ -3762,10 +3751,6 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
this.providerOptions =
|
||||
validateProviderOptions("codex", CodexProviderOptionsSchema, config.providerOptions) ?? {};
|
||||
this.config = config;
|
||||
this.instructionSnapshot = new CodexInstructionSnapshot(
|
||||
composeAgentSystemPrompt(config),
|
||||
resumeHandle?.metadata?.paseoInstructionReceipt,
|
||||
);
|
||||
this.harnessEnvironment = deps.environment ?? buildCodexAppServerEnv();
|
||||
this.asyncQuestions = new CodexAsyncQuestions(resumeHandle?.metadata?.asyncQuestions);
|
||||
this.codexHome = deps.codexHome ?? resolveCodexHomeDir(process.env);
|
||||
@@ -3852,17 +3837,9 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
this.registerRequestHandlers();
|
||||
|
||||
try {
|
||||
const userAgent = toObjectRecord(initialized)?.userAgent;
|
||||
this.threadRollbackAvailable = codexServerHasThreadRollback(userAgent);
|
||||
this.supportsInstructionSnapshots =
|
||||
typeof userAgent === "string" && codexVersionAtLeast(userAgent, [0, 121, 0]);
|
||||
if (
|
||||
!this.currentThreadId &&
|
||||
this.config.pluginAppendSystemPrompt?.length &&
|
||||
!this.supportsInstructionSnapshots
|
||||
) {
|
||||
throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates.");
|
||||
}
|
||||
this.threadRollbackAvailable = codexServerHasThreadRollback(
|
||||
toObjectRecord(initialized)?.userAgent,
|
||||
);
|
||||
|
||||
this.speedModels =
|
||||
CodexModelListResponseSchema.parse(await client.request("model/list", {})).data ?? [];
|
||||
@@ -4060,17 +4037,18 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
settings: Record<string, unknown>;
|
||||
name: string;
|
||||
} | null {
|
||||
const match =
|
||||
this.findCollaborationMode(this.planModeEnabled ? "plan" : "code") ??
|
||||
this.restoredCollaborationMode;
|
||||
const match = this.findCollaborationMode(this.planModeEnabled ? "plan" : "code");
|
||||
if (!match) return null;
|
||||
|
||||
const settings: Record<string, unknown> = {};
|
||||
if (match.model) settings.model = match.model;
|
||||
if (match.reasoning_effort) settings.reasoning_effort = match.reasoning_effort;
|
||||
// Codex applies thread instructions separately. Null asks it to supply the
|
||||
// built-in collaboration mode instructions instead of replacing them.
|
||||
settings.developer_instructions = match.developer_instructions ?? null;
|
||||
const developerInstructions = composeSystemPromptParts(
|
||||
match.developer_instructions,
|
||||
this.config.systemPrompt,
|
||||
this.config.daemonAppendSystemPrompt,
|
||||
);
|
||||
if (developerInstructions) settings.developer_instructions = developerInstructions;
|
||||
if (this.config.model) settings.model = this.config.model;
|
||||
const thinkingOptionId = normalizeCodexThinkingOptionId(this.config.thinkingOptionId);
|
||||
if (thinkingOptionId) settings.reasoning_effort = thinkingOptionId;
|
||||
@@ -4330,7 +4308,10 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
// the unnamespaced key emitted by earlier Paseo versions.
|
||||
params.modelProvider = this.deps.customCodexConfig.model_provider;
|
||||
}
|
||||
const developerInstructions = composeAgentSystemPrompt(this.config);
|
||||
const developerInstructions = composeSystemPromptParts(
|
||||
this.config.systemPrompt,
|
||||
this.config.daemonAppendSystemPrompt,
|
||||
);
|
||||
if (developerInstructions) {
|
||||
params.developerInstructions = developerInstructions;
|
||||
}
|
||||
@@ -4341,11 +4322,11 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
try {
|
||||
const loaded = toObjectRecord(await this.client.request("thread/loaded/list", {}));
|
||||
const ids = Array.isArray(loaded?.data) ? loaded.data : [];
|
||||
if (!ids.includes(this.currentThreadId)) {
|
||||
const response = await this.client.request("thread/resume", params);
|
||||
this.rememberResolvedSandboxPolicy(response);
|
||||
this.rememberRestoredCollaborationMode(response);
|
||||
if (ids.includes(this.currentThreadId)) {
|
||||
return;
|
||||
}
|
||||
const response = await this.client.request("thread/resume", params);
|
||||
this.rememberResolvedSandboxPolicy(response);
|
||||
} catch (error) {
|
||||
const threadId = this.currentThreadId;
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
@@ -4359,34 +4340,12 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
}
|
||||
const response = await this.client.request("thread/resume", params);
|
||||
this.rememberResolvedSandboxPolicy(response);
|
||||
this.rememberRestoredCollaborationMode(response);
|
||||
this.logger.info({ threadId }, "Unarchived Codex thread to restore active Paseo agent");
|
||||
} else {
|
||||
this.logger.warn({ error, threadId }, "Failed to resume persisted Codex thread");
|
||||
throw new Error(`Failed to resume Codex thread ${threadId}: ${message}`, { cause: error });
|
||||
return;
|
||||
}
|
||||
this.logger.warn({ error, threadId }, "Failed to resume persisted Codex thread");
|
||||
throw new Error(`Failed to resume Codex thread ${threadId}: ${message}`, { cause: error });
|
||||
}
|
||||
await this.instructionSnapshot.apply(
|
||||
this.currentThreadId,
|
||||
this.client.request.bind(this.client),
|
||||
this.supportsInstructionSnapshots,
|
||||
);
|
||||
}
|
||||
|
||||
private rememberRestoredCollaborationMode(response: unknown): void {
|
||||
const mode = toObjectRecord(toObjectRecord(response)?.collaborationMode);
|
||||
const settings = toObjectRecord(mode?.settings);
|
||||
if (typeof mode?.mode !== "string" || typeof settings?.model !== "string") return;
|
||||
// The resumed mode can contain instructions from a previous launch. Keep its
|
||||
// identity and model, and let Codex restore the built-in mode instructions.
|
||||
this.restoredCollaborationMode = {
|
||||
name: mode.mode,
|
||||
mode: mode.mode,
|
||||
model: settings.model,
|
||||
reasoning_effort:
|
||||
typeof settings.reasoning_effort === "string" ? settings.reasoning_effort : null,
|
||||
};
|
||||
this.refreshResolvedCollaborationMode();
|
||||
}
|
||||
|
||||
private parseSlashCommandInput(text: string): { commandName: string; args?: string } | null {
|
||||
@@ -4502,7 +4461,13 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
if (options?.outputSchema) {
|
||||
params.outputSchema = normalizeCodexOutputSchema(options.outputSchema);
|
||||
}
|
||||
const developerInstructions = composeAgentSystemPrompt(this.config);
|
||||
const developerInstructions = composeSystemPromptParts(
|
||||
this.config.systemPrompt,
|
||||
this.config.daemonAppendSystemPrompt,
|
||||
);
|
||||
if (developerInstructions) {
|
||||
params.developerInstructions = developerInstructions;
|
||||
}
|
||||
const codexConfig = this.buildCodexInnerConfig();
|
||||
if (codexConfig) {
|
||||
params.config = codexConfig;
|
||||
@@ -5261,9 +5226,6 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
systemPrompt: this.config.systemPrompt,
|
||||
mcpServers: this.config.mcpServers,
|
||||
asyncQuestions: this.asyncQuestions.serialize(),
|
||||
...(this.instructionSnapshot.describe(threadId)
|
||||
? { paseoInstructionReceipt: this.instructionSnapshot.describe(threadId) }
|
||||
: {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -5294,15 +5256,9 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
model: this.config.model ?? null,
|
||||
serviceTier: this.serviceTier,
|
||||
config: this.buildCodexInnerConfig(),
|
||||
developerInstructions: composeAgentSystemPrompt(this.config),
|
||||
userMessageTurns: this.codexUserMessageTurns(),
|
||||
threadRollbackAvailable: this.threadRollbackAvailable,
|
||||
setThreadId: async (threadId) => {
|
||||
await this.instructionSnapshot.apply(
|
||||
threadId,
|
||||
this.client!.request.bind(this.client),
|
||||
this.supportsInstructionSnapshots,
|
||||
);
|
||||
this.currentThreadId = threadId;
|
||||
// Codex writes a forked thread's rollout when it forks it, even before any turn.
|
||||
this.savedThreadId = threadId;
|
||||
@@ -5385,8 +5341,6 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
}
|
||||
|
||||
async canStopRuntime(): Promise<boolean> {
|
||||
// A history session released its app-server once it read the thread, so nothing runs.
|
||||
if (this.connectionState === "history-ready") return true;
|
||||
if (
|
||||
!this.client ||
|
||||
this.client.hasPendingRequests() ||
|
||||
@@ -5838,7 +5792,6 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
this.cachedRuntimeInfo = null;
|
||||
}
|
||||
this.currentThreadId = threadId;
|
||||
this.instructionSnapshot.recordNewThread(threadId);
|
||||
}
|
||||
|
||||
private buildThreadStartRequest(model: string): {
|
||||
@@ -5850,7 +5803,10 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
const approvalPolicy = this.hasWorkflowModeOverride ? preset.approvalPolicy : undefined;
|
||||
const sandbox = this.hasWorkflowModeOverride ? preset.sandbox : undefined;
|
||||
const innerConfig = this.buildCodexInnerConfig();
|
||||
const developerInstructions = composeAgentSystemPrompt(this.config);
|
||||
const developerInstructions = composeSystemPromptParts(
|
||||
this.config.systemPrompt,
|
||||
this.config.daemonAppendSystemPrompt,
|
||||
);
|
||||
const params: Record<string, unknown> = {
|
||||
model,
|
||||
cwd: this.config.cwd ?? null,
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { CodexAppServerRpcError } from "./app-server-transport.js";
|
||||
|
||||
/** The receipt records only which snapshot was delivered to a particular native thread. */
|
||||
interface InstructionReceipt {
|
||||
threadId: string;
|
||||
digest: string;
|
||||
}
|
||||
|
||||
function readReceipt(value: unknown): InstructionReceipt | null {
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const receipt = value as Record<string, unknown>;
|
||||
if (typeof receipt.threadId !== "string" || typeof receipt.digest !== "string") return null;
|
||||
if (!/^[a-f0-9]{64}$/.test(receipt.digest)) return null;
|
||||
return { threadId: receipt.threadId, digest: receipt.digest };
|
||||
}
|
||||
|
||||
export class CodexInstructionSnapshot {
|
||||
private receipt: InstructionReceipt | null;
|
||||
private readonly digest: string;
|
||||
|
||||
constructor(
|
||||
private readonly instructions: string | undefined,
|
||||
receipt: unknown,
|
||||
) {
|
||||
this.receipt = readReceipt(receipt);
|
||||
this.digest = createHash("sha256")
|
||||
.update(JSON.stringify({ version: 1, instructions: instructions ?? "" }))
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
/** A new thread receives its first snapshot through thread/start. */
|
||||
recordNewThread(threadId: string): void {
|
||||
this.receipt = { threadId, digest: this.digest };
|
||||
}
|
||||
|
||||
describe(threadId: string): InstructionReceipt | undefined {
|
||||
return this.receipt?.threadId === threadId ? { ...this.receipt } : undefined;
|
||||
}
|
||||
|
||||
async apply(
|
||||
threadId: string,
|
||||
request: (method: string, params: unknown) => Promise<unknown>,
|
||||
supported: boolean,
|
||||
): Promise<void> {
|
||||
if (this.receipt?.threadId === threadId && this.receipt.digest === this.digest) return;
|
||||
if (!supported)
|
||||
throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates.");
|
||||
const snapshot = JSON.stringify({ version: 1, instructions: this.instructions ?? "" });
|
||||
const text =
|
||||
"This is the complete current set of Paseo-supplied instructions. It supersedes all earlier Paseo-supplied instructions in the conversation, including earlier snapshots. An empty instruction string means there are no current Paseo-supplied instructions. Provider and collaboration instructions remain in effect.\n\n<paseo_instruction_snapshot>" +
|
||||
snapshot +
|
||||
"</paseo_instruction_snapshot>";
|
||||
try {
|
||||
await request("thread/inject_items", {
|
||||
threadId,
|
||||
items: [{ type: "message", role: "developer", content: [{ type: "input_text", text }] }],
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof CodexAppServerRpcError && error.code === -32601) {
|
||||
throw new Error("Update Codex to 0.121.0 or newer to apply agent instruction updates.", {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
this.receipt = { threadId, digest: this.digest };
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,6 @@ export async function revertCodexConversation(input: {
|
||||
model?: string | null;
|
||||
serviceTier?: string | null;
|
||||
config?: Record<string, unknown> | null;
|
||||
developerInstructions?: string;
|
||||
userMessageTurns: CodexUserMessageTurnIndex;
|
||||
threadRollbackAvailable: boolean;
|
||||
setThreadId: (threadId: string) => void | Promise<void>;
|
||||
@@ -77,7 +76,6 @@ export async function revertCodexConversation(input: {
|
||||
model: input.model ?? null,
|
||||
serviceTier: input.serviceTier ?? null,
|
||||
...(input.config ? { config: input.config } : {}),
|
||||
...(input.developerInstructions ? { developerInstructions: input.developerInstructions } : {}),
|
||||
// Paseo re-reads the rewound thread through paged history, not the fork reply.
|
||||
excludeTurns: true,
|
||||
persistExtendedHistory: true,
|
||||
|
||||
@@ -171,7 +171,7 @@ export function createFakeCodexAppServer(
|
||||
const child = createCodexAppServerChildProcess();
|
||||
const recordedRollbacks: JsonObject[] = [];
|
||||
const responseHandlers: Record<string, FakeCodexAppServerHandler> = {
|
||||
initialize: () => ({ userAgent: "codex/0.150.0" }),
|
||||
initialize: () => ({}),
|
||||
"collaborationMode/list": () => ({ data: [] }),
|
||||
"config/read": () => ({ config: {} }),
|
||||
getUserSavedConfig: () => ({ config: {} }),
|
||||
@@ -189,7 +189,6 @@ export function createFakeCodexAppServer(
|
||||
"thread/loaded/list": () => ({ data: [] }),
|
||||
"thread/backgroundTerminals/list": () => ({ data: [], nextCursor: null }),
|
||||
"thread/resume": () => ({}),
|
||||
"thread/inject_items": () => ({}),
|
||||
"turn/start": () => ({}),
|
||||
"thread/fork": (params) => ({
|
||||
thread: {
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
// Drops an upstream "Vendor: " prefix ("OpenAI: GPT-5.5"). A colon inside parentheses or after a
|
||||
// comma belongs to the model name ("DeepSeek V4 (ctx: 128k)"), so it is kept.
|
||||
function stripVendorPrefix(label: string): string {
|
||||
const vendorSeparatorIndex = label.indexOf(": ");
|
||||
if (vendorSeparatorIndex === -1 || /[(),]/.test(label.slice(0, vendorSeparatorIndex))) {
|
||||
return label;
|
||||
}
|
||||
return label.slice(vendorSeparatorIndex + 2).trim();
|
||||
}
|
||||
|
||||
// The label Pi and OMP show for a model from their catalogs. A model name is either a path
|
||||
// ("google/gemini_2.5-flash", as OpenRouter reports it) or free text that can contain slashes
|
||||
// and underscores ("IQ3_S ... 52/56"). Only paths are shortened.
|
||||
export function modelDisplayLabel(model: { id: string; name?: string }): string {
|
||||
const text = model.name?.trim().replace(/\s+/g, " ") || model.id.trim();
|
||||
if (/\s/.test(text)) {
|
||||
return stripVendorPrefix(text);
|
||||
}
|
||||
const lastSegment = text.split("/").findLast((segment) => segment.length > 0) ?? text;
|
||||
return stripVendorPrefix(lastSegment.replace(/_+/g, " "));
|
||||
}
|
||||
@@ -1855,69 +1855,3 @@ test("closing OMP during image conversion rejects its pending start", async () =
|
||||
await session.close();
|
||||
await rejected;
|
||||
});
|
||||
|
||||
describe("OMP catalog model labels", () => {
|
||||
test.each([
|
||||
{
|
||||
name: "keeps slashes and underscores inside a free-text model name",
|
||||
model: {
|
||||
provider: "llama-swap",
|
||||
id: "s-q3fn(p-t)",
|
||||
name: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)",
|
||||
},
|
||||
label: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)",
|
||||
},
|
||||
{
|
||||
name: "keeps a free-text name that ends in a slash-separated word",
|
||||
model: {
|
||||
provider: "llama-swap",
|
||||
id: "ds-strata-6",
|
||||
name: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)",
|
||||
},
|
||||
label: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)",
|
||||
},
|
||||
{
|
||||
name: "keeps a colon inside a free-text model name",
|
||||
model: {
|
||||
provider: "llama-swap",
|
||||
id: "qwen3-tail",
|
||||
name: "Qwen3 IQ3_S (tail skip: on, 52/56)",
|
||||
},
|
||||
label: "Qwen3 IQ3_S (tail skip: on, 52/56)",
|
||||
},
|
||||
{
|
||||
name: "keeps an OMP catalog name as it is",
|
||||
model: {
|
||||
provider: "openrouter",
|
||||
id: "anthropic/claude-opus-4.1:batch",
|
||||
name: "Claude Opus 4.1 (batch)",
|
||||
},
|
||||
label: "Claude Opus 4.1 (batch)",
|
||||
},
|
||||
{
|
||||
name: "drops the vendor prefix from an upstream model name",
|
||||
model: { provider: "openrouter", id: "openai/gpt-5.5", name: "OpenAI: GPT-5.5" },
|
||||
label: "GPT-5.5",
|
||||
},
|
||||
{
|
||||
name: "falls back to the last segment of a path-like id",
|
||||
model: { provider: "pioneer", id: "canada-quant/glm_5.2" },
|
||||
label: "glm 5.2",
|
||||
},
|
||||
])("$name", async ({ model, label }) => {
|
||||
const runtime = new FakeOmp();
|
||||
runtime.queueSessionSetup((session) => {
|
||||
session.models = [model];
|
||||
});
|
||||
const client = new OmpAgentClient({ logger: createTestLogger(), runtime });
|
||||
|
||||
const catalog = await client.fetchCatalog({
|
||||
scope: "workspace",
|
||||
cwd: "/workspace/project",
|
||||
force: false,
|
||||
});
|
||||
|
||||
expect(catalog.models.map((entry) => entry.label)).toEqual([label]);
|
||||
expect(catalog.models[0]?.id).toBe(`${model.provider}/${model.id}`);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
type AgentLaunchContext,
|
||||
type AgentMetadata,
|
||||
type AgentMode,
|
||||
type AgentModelDefinition,
|
||||
type AgentPermissionRequest,
|
||||
type AgentPermissionResponse,
|
||||
type AgentProviderNotice,
|
||||
@@ -251,6 +252,36 @@ interface OmpSlashCommandInvocation {
|
||||
|
||||
type AutoCompactMode = boolean | "toggle" | "unknown";
|
||||
|
||||
function normalizeOmpModelLabel(label: string): string {
|
||||
const normalizedLabel = label.trim().replace(/[_\s]+/g, " ");
|
||||
const vendorSeparatorIndex = normalizedLabel.indexOf(": ");
|
||||
if (vendorSeparatorIndex === -1) {
|
||||
return normalizedLabel;
|
||||
}
|
||||
|
||||
return normalizedLabel.slice(vendorSeparatorIndex + 2).trim();
|
||||
}
|
||||
|
||||
export function transformOmpModels(models: AgentModelDefinition[]): AgentModelDefinition[] {
|
||||
return models.map((model) => {
|
||||
if (!model.label.includes("/")) {
|
||||
return model;
|
||||
}
|
||||
|
||||
const segments = model.label.split("/").filter((segment) => segment.length > 0);
|
||||
const rawLabel = segments.at(-1);
|
||||
if (!rawLabel) {
|
||||
return model;
|
||||
}
|
||||
|
||||
return {
|
||||
...model,
|
||||
label: normalizeOmpModelLabel(rawLabel),
|
||||
description: model.description ?? model.label,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function isOmpThinkingLevel(value: string | null | undefined): value is OmpThinkingLevel {
|
||||
return (
|
||||
value === "off" ||
|
||||
@@ -435,7 +466,6 @@ function buildResumeStartInput(input: {
|
||||
systemPrompt: composeSystemPromptParts(
|
||||
input.resumeConfig.config.systemPrompt,
|
||||
input.resumeConfig.config.daemonAppendSystemPrompt,
|
||||
...(input.resumeConfig.config.pluginAppendSystemPrompt ?? []),
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -2340,11 +2370,7 @@ export class OmpAgentClient implements AgentClient {
|
||||
noSession: config.internal === true,
|
||||
modeId: launchMode.modeId,
|
||||
extraArgs: launchMode.extraArgs,
|
||||
systemPrompt: composeSystemPromptParts(
|
||||
config.systemPrompt,
|
||||
config.daemonAppendSystemPrompt,
|
||||
...(config.pluginAppendSystemPrompt ?? []),
|
||||
),
|
||||
systemPrompt: composeSystemPromptParts(config.systemPrompt, config.daemonAppendSystemPrompt),
|
||||
env: launchContext?.env,
|
||||
};
|
||||
const runtimeSession = await this.resolveRuntime(config.providerOptions).startSession(
|
||||
@@ -2545,11 +2571,13 @@ export class OmpAgentClient implements AgentClient {
|
||||
});
|
||||
if (!runtimeSession) throw new Error("OMP catalog runtime did not start");
|
||||
const catalogSession = runtimeSession;
|
||||
const models = (
|
||||
await runProviderRefreshActivity(context, "get_available_models", () =>
|
||||
catalogSession.getAvailableModels(null),
|
||||
)
|
||||
).map((model) => mapOmpModel(model, this.provider));
|
||||
const models = transformOmpModels(
|
||||
(
|
||||
await runProviderRefreshActivity(context, "get_available_models", () =>
|
||||
catalogSession.getAvailableModels(null),
|
||||
)
|
||||
).map((model) => mapOmpModel(model, this.provider)),
|
||||
);
|
||||
return { models, modes: [...OMP_MODES] };
|
||||
} finally {
|
||||
context?.signal.removeEventListener("abort", handleAbort);
|
||||
|
||||
@@ -164,7 +164,7 @@ describe("mapOmpModel thinking options", () => {
|
||||
|
||||
expect(result.provider).toBe("omp");
|
||||
expect(result.id).toBe("pioneer/canada-quant/glm-5.2");
|
||||
expect(result.label).toBe("GLM-5.2");
|
||||
expect(result.label).toBe("pioneer/GLM-5.2");
|
||||
expect(result.metadata).toEqual({ provider: "pioneer", modelId: "canada-quant/glm-5.2" });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,6 @@ import type {
|
||||
AgentProvider,
|
||||
AgentSelectOption,
|
||||
} from "../../agent-sdk-types.js";
|
||||
import { modelDisplayLabel } from "../model-label.js";
|
||||
import type { OmpModel, OmpThinkingLevel } from "./rpc-types.js";
|
||||
|
||||
export const DEFAULT_OMP_THINKING_LEVEL: OmpThinkingLevel = "medium";
|
||||
@@ -44,7 +43,7 @@ export function mapOmpModel(model: OmpModel, provider: AgentProvider): AgentMode
|
||||
return {
|
||||
provider,
|
||||
id: `${model.provider}/${model.id}`,
|
||||
label: modelDisplayLabel(model),
|
||||
label: `${model.provider}/${model.name ?? model.id}`,
|
||||
description: `${model.provider}/${model.id}`,
|
||||
metadata: {
|
||||
provider: model.provider,
|
||||
|
||||
@@ -30,7 +30,6 @@ import {
|
||||
type AgentDraftControls,
|
||||
type AgentOptionControl,
|
||||
type AgentLaunchContext,
|
||||
type AgentResumeSessionOptions,
|
||||
type AgentMode,
|
||||
type AgentModelDefinition,
|
||||
type AgentPermissionAction,
|
||||
@@ -1522,7 +1521,6 @@ export class OpenCodeAgentClient implements AgentClient {
|
||||
handle: AgentPersistenceHandle,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
launchContext?: AgentLaunchContext,
|
||||
_options?: AgentResumeSessionOptions,
|
||||
): Promise<AgentSession> {
|
||||
const metadata = (handle.metadata ?? {}) as Partial<AgentSessionConfig>;
|
||||
const cwd = overrides?.cwd ?? metadata.cwd;
|
||||
@@ -3694,7 +3692,6 @@ class OpenCodeAgentSession implements AgentSession {
|
||||
const systemPrompt = composeSystemPromptParts(
|
||||
this.config.systemPrompt,
|
||||
this.config.daemonAppendSystemPrompt,
|
||||
...(this.config.pluginAppendSystemPrompt ?? []),
|
||||
);
|
||||
const model = this.parseModel(this.config.model);
|
||||
const effectiveMode = resolveOpenCodeRuntimeAgentId(this.currentMode);
|
||||
@@ -4032,7 +4029,6 @@ class OpenCodeAgentSession implements AgentSession {
|
||||
const systemPrompt = composeSystemPromptParts(
|
||||
this.config.systemPrompt,
|
||||
this.config.daemonAppendSystemPrompt,
|
||||
...(this.config.pluginAppendSystemPrompt ?? []),
|
||||
);
|
||||
const promptResponse = await this.client.session.promptAsync({
|
||||
sessionID: this.sessionId,
|
||||
|
||||
@@ -4,7 +4,6 @@ import type {
|
||||
AgentSessionConfig,
|
||||
AgentLaunchContext,
|
||||
AgentCreateSessionOptions,
|
||||
AgentResumeSessionOptions,
|
||||
AgentPersistenceHandle,
|
||||
FetchCatalogOptions,
|
||||
ProviderRefreshContext,
|
||||
@@ -150,10 +149,9 @@ export class OpenCodeRuntimeClient implements AgentClient {
|
||||
handle: AgentPersistenceHandle,
|
||||
config?: Partial<AgentSessionConfig>,
|
||||
launch?: AgentLaunchContext,
|
||||
options?: AgentResumeSessionOptions,
|
||||
) {
|
||||
const client = await this.client();
|
||||
const session = await client.resumeSession(handle, config, launch, options);
|
||||
const session = await client.resumeSession(handle, config, launch);
|
||||
return client === this.legacy ? session : withOpenCodeRuntimeNotice(session, 2, handle);
|
||||
}
|
||||
async fetchCatalog(options: FetchCatalogOptions, context?: ProviderRefreshContext) {
|
||||
|
||||
@@ -28,7 +28,6 @@ export class V2Harness {
|
||||
readonly prompts: string[] = [];
|
||||
readonly environments: Array<{ sessionID: string; variables: Record<string, string> }> = [];
|
||||
readonly mcpAdds: string[] = [];
|
||||
readonly instructions = new Map<string, string>();
|
||||
releases = 0;
|
||||
active = false;
|
||||
activeReads = 0;
|
||||
@@ -154,17 +153,7 @@ export class V2Harness {
|
||||
environment: async (input) => {
|
||||
this.environments.push(input);
|
||||
},
|
||||
instructions: {
|
||||
entry: {
|
||||
list: async () => [...this.instructions].map(([key, value]) => ({ key, value })),
|
||||
put: async ({ key, value }) => {
|
||||
this.instructions.set(key, String(value));
|
||||
},
|
||||
remove: async ({ key }) => {
|
||||
this.instructions.delete(key);
|
||||
},
|
||||
},
|
||||
},
|
||||
instructions: { entry: { list: unexpected, put: unexpected, remove: unexpected } },
|
||||
prompt: async (input, options) => {
|
||||
const before = this.executions.length;
|
||||
await this.prompt(input, options);
|
||||
|
||||
@@ -17,54 +17,6 @@ function terminalEvents(events: AgentStreamEvent[]) {
|
||||
}
|
||||
|
||||
describe("OpenCode v2 session lifecycle", () => {
|
||||
test("reopening replaces and removes plugin instructions", async () => {
|
||||
const harness = new V2Harness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: harness.runtime,
|
||||
});
|
||||
const created = await client.createSession({
|
||||
provider: "opencode",
|
||||
cwd: "/tmp/project",
|
||||
pluginAppendSystemPrompt: ["first"],
|
||||
});
|
||||
expect(harness.instructions.get("paseo")).toBe("first");
|
||||
const handle = created.describePersistence()!;
|
||||
await created.close();
|
||||
const resumed = await client.resumeSession(handle, {
|
||||
cwd: "/tmp/project",
|
||||
pluginAppendSystemPrompt: ["changed"],
|
||||
});
|
||||
expect(harness.instructions.get("paseo")).toBe("changed");
|
||||
await resumed.close();
|
||||
const cleared = await client.resumeSession(handle, {
|
||||
cwd: "/tmp/project",
|
||||
pluginAppendSystemPrompt: undefined,
|
||||
});
|
||||
expect(harness.instructions.has("paseo")).toBe(false);
|
||||
await cleared.close();
|
||||
});
|
||||
|
||||
test("opening history does not change an existing session instruction", async () => {
|
||||
const harness = new V2Harness();
|
||||
harness.instructions.set("paseo", "Existing plugin instruction");
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: harness.runtime,
|
||||
});
|
||||
const session = await client.resumeSession(
|
||||
{ provider: "opencode", sessionId: "session", metadata: { cwd: "/tmp/project" } },
|
||||
{ cwd: "/tmp/project" },
|
||||
undefined,
|
||||
{ purpose: "history" },
|
||||
);
|
||||
try {
|
||||
expect(harness.instructions.get("paseo")).toBe("Existing plugin instruction");
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("refreshes the existing location before reading a forced catalog", async () => {
|
||||
const harness = new V2Harness();
|
||||
const refreshed: string[] = [];
|
||||
|
||||
@@ -17,7 +17,6 @@ import type {
|
||||
AgentCapabilityFlags,
|
||||
AgentClient,
|
||||
AgentCreateSessionOptions,
|
||||
AgentResumeSessionOptions,
|
||||
AgentDraftControls,
|
||||
AgentLaunchContext,
|
||||
AgentPersistenceHandle,
|
||||
@@ -132,7 +131,6 @@ export class OpenCodeV2AgentClient implements AgentClient {
|
||||
handle: AgentPersistenceHandle,
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
launch?: AgentLaunchContext,
|
||||
options?: AgentResumeSessionOptions,
|
||||
): Promise<AgentSession> {
|
||||
const cwd = overrides?.cwd ?? handle.metadata?.cwd;
|
||||
if (typeof cwd !== "string")
|
||||
@@ -153,14 +151,7 @@ export class OpenCodeV2AgentClient implements AgentClient {
|
||||
sessionID: handle.nativeHandle ?? handle.sessionId,
|
||||
});
|
||||
await applyResumeOverrides(connection.client, info, overrides);
|
||||
return await this.attach(
|
||||
connection,
|
||||
info,
|
||||
config,
|
||||
launch,
|
||||
true,
|
||||
options?.purpose === "history",
|
||||
);
|
||||
return await this.attach(connection, info, config, launch, true);
|
||||
} catch (error) {
|
||||
await connection.release();
|
||||
throw error;
|
||||
@@ -172,7 +163,6 @@ export class OpenCodeV2AgentClient implements AgentClient {
|
||||
config: AgentSessionConfig,
|
||||
launch: AgentLaunchContext | undefined,
|
||||
persist: boolean,
|
||||
historyOnly = false,
|
||||
) {
|
||||
const acquire = () =>
|
||||
this.runtime.acquire(
|
||||
@@ -219,7 +209,6 @@ export class OpenCodeV2AgentClient implements AgentClient {
|
||||
bindChild,
|
||||
acquire,
|
||||
moved,
|
||||
historyOnly,
|
||||
);
|
||||
try {
|
||||
await session.initialize(
|
||||
|
||||
@@ -75,7 +75,6 @@ export class OpenCodeV2Session implements AgentSession {
|
||||
bindChild?: (id: string) => void,
|
||||
private readonly acquire?: () => Promise<V2Connection>,
|
||||
private readonly moved?: (connection: V2Connection) => void,
|
||||
private readonly historyOnly = false,
|
||||
) {
|
||||
this.background = new OpenCodeBackgroundInventory({
|
||||
id: info.id,
|
||||
@@ -194,24 +193,16 @@ export class OpenCodeV2Session implements AgentSession {
|
||||
});
|
||||
await this.awaitMcp(server);
|
||||
}
|
||||
if (this.historyOnly) return;
|
||||
const system = composeSystemPromptParts(
|
||||
this.config.systemPrompt,
|
||||
this.config.daemonAppendSystemPrompt,
|
||||
...(this.config.pluginAppendSystemPrompt ?? []),
|
||||
);
|
||||
if (system) {
|
||||
if (system)
|
||||
await this.client.session.instructions.entry.put({
|
||||
sessionID: this.id,
|
||||
key: "paseo",
|
||||
value: system,
|
||||
});
|
||||
} else {
|
||||
const entries = await this.client.session.instructions.entry.list({ sessionID: this.id });
|
||||
if (entries.some((entry) => entry.key === "paseo")) {
|
||||
await this.client.session.instructions.entry.remove({ sessionID: this.id, key: "paseo" });
|
||||
}
|
||||
}
|
||||
}
|
||||
private async startStream() {
|
||||
let ready!: () => void;
|
||||
|
||||
@@ -19,7 +19,12 @@ import { pathToFileURL } from "node:url";
|
||||
import { describe, expect, onTestFinished, test } from "vitest";
|
||||
|
||||
import type { AgentSession, AgentSessionConfig, AgentStreamEvent } from "../../agent-sdk-types.js";
|
||||
import { PiProviderOptionsSchema, PiRpcAgentClient, PiRpcAgentSession } from "./agent.js";
|
||||
import {
|
||||
PiProviderOptionsSchema,
|
||||
PiRpcAgentClient,
|
||||
PiRpcAgentSession,
|
||||
transformPiModels,
|
||||
} from "./agent.js";
|
||||
import { PiCliRuntime } from "./cli-runtime.js";
|
||||
import { FakePi } from "./test-utils/fake-pi.js";
|
||||
import { createPiExtensionHost } from "./extensions/index.js";
|
||||
@@ -1887,7 +1892,6 @@ describe("PiRpcAgentSession", () => {
|
||||
createConfig({
|
||||
systemPrompt: "Agent prompt",
|
||||
daemonAppendSystemPrompt: "Daemon prompt",
|
||||
pluginAppendSystemPrompt: ["Plugin one", "Plugin two"],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1906,9 +1910,7 @@ describe("PiRpcAgentSession", () => {
|
||||
|
||||
await expect(
|
||||
applyPaseoExtensionSystemPrompt(actualLaunch.extensionPaths[0]!, "Pi project prompt"),
|
||||
).resolves.toBe(
|
||||
"Pi project prompt\n\nAgent prompt\n\nDaemon prompt\n\nPlugin one\n\nPlugin two",
|
||||
);
|
||||
).resolves.toBe("Pi project prompt\n\nAgent prompt\n\nDaemon prompt");
|
||||
|
||||
await session.close();
|
||||
});
|
||||
@@ -1931,7 +1933,6 @@ describe("PiRpcAgentSession", () => {
|
||||
},
|
||||
{
|
||||
daemonAppendSystemPrompt: "Daemon prompt",
|
||||
pluginAppendSystemPrompt: ["Plugin one", "Plugin two"],
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1955,9 +1956,7 @@ describe("PiRpcAgentSession", () => {
|
||||
]);
|
||||
await expect(
|
||||
applyPaseoExtensionSystemPrompt(actualLaunch.extensionPaths[0]!, "Pi project prompt"),
|
||||
).resolves.toBe(
|
||||
"Pi project prompt\n\nAgent prompt\n\nDaemon prompt\n\nPlugin one\n\nPlugin two",
|
||||
);
|
||||
).resolves.toBe("Pi project prompt\n\nAgent prompt\n\nDaemon prompt");
|
||||
});
|
||||
|
||||
test("updates model and thinking through Pi runtime commands", async () => {
|
||||
@@ -3971,73 +3970,35 @@ readline.createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Pi catalog model labels", () => {
|
||||
test.each([
|
||||
{
|
||||
name: "keeps slashes and underscores inside a free-text model name",
|
||||
model: {
|
||||
provider: "llama-swap",
|
||||
id: "s-q3fn(p-t)",
|
||||
name: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)",
|
||||
describe("transformPiModels", () => {
|
||||
test("normalizes labels that include the upstream provider prefix", () => {
|
||||
expect(
|
||||
transformPiModels([
|
||||
{
|
||||
provider: "pi",
|
||||
id: "openrouter/google/gemini-2.5-flash-lite",
|
||||
label: "openrouter/google/gemini_2.5 flash lite",
|
||||
},
|
||||
{
|
||||
provider: "pi",
|
||||
id: "openrouter/openai/gpt-5.5",
|
||||
label: "openrouter/OpenAI: GPT-5.5",
|
||||
},
|
||||
]),
|
||||
).toEqual([
|
||||
{
|
||||
provider: "pi",
|
||||
id: "openrouter/google/gemini-2.5-flash-lite",
|
||||
label: "gemini 2.5 flash lite",
|
||||
description: "openrouter/google/gemini_2.5 flash lite",
|
||||
},
|
||||
label: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)",
|
||||
},
|
||||
{
|
||||
name: "keeps a free-text name that ends in a slash-separated word",
|
||||
model: {
|
||||
provider: "llama-swap",
|
||||
id: "ds-strata-6",
|
||||
name: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)",
|
||||
{
|
||||
provider: "pi",
|
||||
id: "openrouter/openai/gpt-5.5",
|
||||
label: "GPT-5.5",
|
||||
description: "openrouter/OpenAI: GPT-5.5",
|
||||
},
|
||||
label: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)",
|
||||
},
|
||||
{
|
||||
name: "keeps a colon inside a free-text model name",
|
||||
model: {
|
||||
provider: "llama-swap",
|
||||
id: "qwen3-tail",
|
||||
name: "Qwen3 IQ3_S (tail skip: on, 52/56)",
|
||||
},
|
||||
label: "Qwen3 IQ3_S (tail skip: on, 52/56)",
|
||||
},
|
||||
{
|
||||
name: "drops the vendor prefix from an upstream model name",
|
||||
model: { provider: "openrouter", id: "openai/gpt-5.5", name: "OpenAI: GPT-5.5" },
|
||||
label: "GPT-5.5",
|
||||
},
|
||||
{
|
||||
name: "shortens a path-like name to its last segment",
|
||||
model: {
|
||||
provider: "openrouter",
|
||||
id: "google/gemini-2.5-flash-lite",
|
||||
name: "google/gemini-2.5-flash-lite",
|
||||
},
|
||||
label: "gemini-2.5-flash-lite",
|
||||
},
|
||||
{
|
||||
name: "falls back to the last segment of a path-like id",
|
||||
model: { provider: "openrouter", id: "google/gemini_2.5-flash-lite" },
|
||||
label: "gemini 2.5-flash-lite",
|
||||
},
|
||||
{
|
||||
name: "falls back to an id with spaces when the name is blank",
|
||||
model: { provider: "local", id: "DeepSeek-V4.1-Flash 2.25bpw (Strata)", name: " " },
|
||||
label: "DeepSeek-V4.1-Flash 2.25bpw (Strata)",
|
||||
},
|
||||
])("$name", async ({ model, label }) => {
|
||||
const pi = new FakePi();
|
||||
pi.queueSessionSetup((session) => {
|
||||
session.models = [model];
|
||||
});
|
||||
|
||||
const catalog = await createClient(pi).fetchCatalog({
|
||||
scope: "workspace",
|
||||
cwd: "/workspace/project",
|
||||
force: false,
|
||||
});
|
||||
|
||||
expect(catalog.models.map((entry) => entry.label)).toEqual([label]);
|
||||
expect(catalog.models[0]?.id).toBe(`${model.provider}/${model.id}`);
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ import {
|
||||
type ResolvedProviderLaunch,
|
||||
} from "../../provider-launch-config.js";
|
||||
import { renderPromptAttachmentAsText } from "../../prompt-attachments.js";
|
||||
import { composeAgentSystemPrompt } from "../../system-prompt.js";
|
||||
import { composeSystemPromptParts } from "../../system-prompt.js";
|
||||
import {
|
||||
buildBinaryDiagnosticRows,
|
||||
buildCommandResolutionDiagnosticRows,
|
||||
@@ -83,7 +83,6 @@ import {
|
||||
listPiImportableSessions,
|
||||
readPiImportSessionConfig,
|
||||
} from "./session-descriptor.js";
|
||||
import { modelDisplayLabel } from "../model-label.js";
|
||||
import type { PiRuntime, PiRuntimeSession, PiStartSessionInput } from "./runtime.js";
|
||||
import type {
|
||||
PiAgentSessionEvent,
|
||||
@@ -314,6 +313,36 @@ interface PiSlashCommandInvocation {
|
||||
|
||||
type AutoCompactMode = boolean | "toggle" | "unknown";
|
||||
|
||||
function normalizePiModelLabel(label: string): string {
|
||||
const normalizedLabel = label.trim().replace(/[_\s]+/g, " ");
|
||||
const vendorSeparatorIndex = normalizedLabel.indexOf(": ");
|
||||
if (vendorSeparatorIndex === -1) {
|
||||
return normalizedLabel;
|
||||
}
|
||||
|
||||
return normalizedLabel.slice(vendorSeparatorIndex + 2).trim();
|
||||
}
|
||||
|
||||
export function transformPiModels(models: AgentModelDefinition[]): AgentModelDefinition[] {
|
||||
return models.map((model) => {
|
||||
if (!model.label.includes("/")) {
|
||||
return model;
|
||||
}
|
||||
|
||||
const segments = model.label.split("/").filter((segment) => segment.length > 0);
|
||||
const rawLabel = segments.at(-1);
|
||||
if (!rawLabel) {
|
||||
return model;
|
||||
}
|
||||
|
||||
return {
|
||||
...model,
|
||||
label: normalizePiModelLabel(rawLabel),
|
||||
description: model.description ?? model.label,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function isPiThinkingLevel(value: string | null | undefined): value is PiThinkingLevel {
|
||||
return (
|
||||
value === "off" ||
|
||||
@@ -1137,7 +1166,7 @@ function mapPiModel(model: PiModel, provider: AgentProvider): AgentModelDefiniti
|
||||
return {
|
||||
provider,
|
||||
id: `${model.provider}/${model.id}`,
|
||||
label: modelDisplayLabel(model),
|
||||
label: `${model.provider}/${model.name ?? model.id}`,
|
||||
description: `${model.provider}/${model.id}`,
|
||||
metadata: {
|
||||
provider: model.provider,
|
||||
@@ -2601,7 +2630,7 @@ export class PiRpcAgentClient implements AgentClient {
|
||||
const mcp = await this.prepareMcpInjection(config.cwd, config.mcpServers, mcpEnv, runtime);
|
||||
const mcpConfigFile = mcp?.kind === "adapter" ? mcp.configFile : null;
|
||||
const paseoExtension = createPiPaseoExtensionFile({
|
||||
systemPrompt: composeAgentSystemPrompt(config),
|
||||
systemPrompt: composeSystemPromptParts(config.systemPrompt, config.daemonAppendSystemPrompt),
|
||||
mcpServers: mcp?.kind === "builtin" ? mcp.servers : undefined,
|
||||
});
|
||||
let runtimeSession: PiRuntimeSession;
|
||||
@@ -2670,7 +2699,10 @@ export class PiRpcAgentClient implements AgentClient {
|
||||
);
|
||||
const mcpConfigFile = mcp?.kind === "adapter" ? mcp.configFile : null;
|
||||
const paseoExtension = createPiPaseoExtensionFile({
|
||||
systemPrompt: composeAgentSystemPrompt(resumeConfig.config),
|
||||
systemPrompt: composeSystemPromptParts(
|
||||
resumeConfig.config.systemPrompt,
|
||||
resumeConfig.config.daemonAppendSystemPrompt,
|
||||
),
|
||||
mcpServers: mcp?.kind === "builtin" ? mcp.servers : undefined,
|
||||
});
|
||||
const tempFiles = mcpConfigFile ? [mcpConfigFile, paseoExtension] : [paseoExtension];
|
||||
@@ -2785,13 +2817,15 @@ export class PiRpcAgentClient implements AgentClient {
|
||||
"get_state",
|
||||
() => catalogSession.getState(),
|
||||
);
|
||||
const models = piModels.map((model) => {
|
||||
const mapped = mapPiModel(model, PI_PROVIDER);
|
||||
const isConfigured =
|
||||
model.provider === configuredModel?.provider && model.id === configuredModel?.id;
|
||||
if (isConfigured) mapped.isDefault = true;
|
||||
return mapped;
|
||||
});
|
||||
const models = transformPiModels(
|
||||
piModels.map((model) => {
|
||||
const mapped = mapPiModel(model, PI_PROVIDER);
|
||||
const isConfigured =
|
||||
model.provider === configuredModel?.provider && model.id === configuredModel?.id;
|
||||
if (isConfigured) mapped.isDefault = true;
|
||||
return mapped;
|
||||
}),
|
||||
);
|
||||
return { models, modes: [] };
|
||||
} finally {
|
||||
context?.signal.removeEventListener("abort", handleAbort);
|
||||
|
||||
@@ -8,15 +8,3 @@ export function composeSystemPromptParts(
|
||||
|
||||
return prompt.length > 0 ? prompt : undefined;
|
||||
}
|
||||
|
||||
export function composeAgentSystemPrompt(config: {
|
||||
systemPrompt?: string;
|
||||
daemonAppendSystemPrompt?: string;
|
||||
pluginAppendSystemPrompt?: string[];
|
||||
}): string | undefined {
|
||||
return composeSystemPromptParts(
|
||||
config.systemPrompt,
|
||||
config.daemonAppendSystemPrompt,
|
||||
...(config.pluginAppendSystemPrompt ?? []),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -241,23 +241,6 @@ function mergeReasoningChunks(entries: readonly WorkingEntry[]): WorkingEntry[]
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `next`, the row right after `previous`, is another chunk of the same assistant
|
||||
* message. A turn id or message id change starts a new message, which matters where rows
|
||||
* replayed from provider history carry no turn id.
|
||||
*/
|
||||
export function continuesAssistantMessage(
|
||||
previous: Pick<AgentTimelineRow, "item" | "turnId">,
|
||||
next: Pick<AgentTimelineRow, "item" | "turnId">,
|
||||
): boolean {
|
||||
return (
|
||||
previous.item.type === "assistant_message" &&
|
||||
next.item.type === "assistant_message" &&
|
||||
previous.turnId === next.turnId &&
|
||||
(next.item.messageId === undefined || next.item.messageId === previous.item.messageId)
|
||||
);
|
||||
}
|
||||
|
||||
function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[] {
|
||||
const output: WorkingEntry[] = [];
|
||||
|
||||
@@ -265,8 +248,10 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[]
|
||||
const previous = output[output.length - 1];
|
||||
const shouldMerge =
|
||||
previous &&
|
||||
previous.item.type === "assistant_message" &&
|
||||
entry.item.type === "assistant_message" &&
|
||||
previous.seqEnd + 1 === entry.seqStart &&
|
||||
continuesAssistantMessage(previous, entry);
|
||||
previous.turnId === entry.turnId;
|
||||
|
||||
if (!shouldMerge || !previous) {
|
||||
output.push(entry);
|
||||
@@ -277,6 +262,13 @@ function mergeAssistantChunks(entries: readonly WorkingEntry[]): WorkingEntry[]
|
||||
{ type: "assistant_message" }
|
||||
>;
|
||||
const entryAssistant = entry.item as Extract<AgentTimelineItem, { type: "assistant_message" }>;
|
||||
if (
|
||||
entryAssistant.messageId !== undefined &&
|
||||
previousAssistant.messageId !== entryAssistant.messageId
|
||||
) {
|
||||
output.push(entry);
|
||||
continue;
|
||||
}
|
||||
|
||||
const collapsedKinds = new Set<TimelineProjectionKind>([
|
||||
...previous.collapsed,
|
||||
|
||||
@@ -1281,7 +1281,7 @@ function createToolCatalog(
|
||||
.strict();
|
||||
const commonSendAgentPromptInputSchema = {
|
||||
activeTurnBehavior: ActiveTurnBehaviorSchema.optional().describe(
|
||||
'Agent callers: "steer" (default) waits until the current turn ends; "interrupt" replaces it. Human callers: "steer" joins the turn, falling back to interrupt; default is interrupt.',
|
||||
'How to send into a running turn: "steer" joins it, falling back to interrupt when unavailable; "interrupt" replaces it. Defaults to steer for agent callers and interrupt otherwise.',
|
||||
),
|
||||
agentId: z.string(),
|
||||
prompt: z.string(),
|
||||
@@ -1968,7 +1968,7 @@ function createToolCatalog(
|
||||
{
|
||||
title: "Send agent prompt",
|
||||
description:
|
||||
"Send a task. Agent callers receive an immediate queued receipt; delivery follows after two quiet seconds per recipient and waits for the current turn to end unless interrupt is requested. Completion reports include the target’s last response by default. Paseo supplies caller identity.",
|
||||
"Send a task. Agent callers receive an immediate queued receipt; delivery follows after two quiet seconds per recipient. Completion reports include the target’s last response by default. Paseo supplies caller identity.",
|
||||
inputSchema: sendAgentPromptInputSchema,
|
||||
outputSchema: {
|
||||
success: z.boolean(),
|
||||
@@ -2045,8 +2045,8 @@ function createToolCatalog(
|
||||
messageId: receipt.messageId,
|
||||
status: agentManager.getAgent(agentId)?.lifecycle ?? "idle",
|
||||
guidance: notifying
|
||||
? `Queued for delivery after two quiet seconds and the current turn ends. ${PROMPTED_AGENT_NOTIFICATION_GUIDANCE}`
|
||||
: "Queued for delivery after two quiet seconds and the current turn ends; provider dispatch has not occurred.",
|
||||
? `Queued for delivery after two quiet seconds. ${PROMPTED_AGENT_NOTIFICATION_GUIDANCE}`
|
||||
: "Queued for delivery after two quiet seconds; provider dispatch has not occurred.",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ test("an agent-sourced steer leaves the question pending and answerable", async
|
||||
await client.sendAgentMessage(recipient.id, "Peer status check", {
|
||||
sourceAgentId: sender.id,
|
||||
});
|
||||
// Permission checkpoints are reported while the peer message waits for turn end.
|
||||
// The public wait includes admitted message delivery before reporting permission status.
|
||||
const waiting = await client.waitForFinish(recipient.id);
|
||||
expect(waiting.status).toBe("permission");
|
||||
expect(waiting.final?.pendingPermissions).toMatchObject([
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtemp, writeFile, rm, readFile, lstat, utimes } from "node:fs/promises";
|
||||
import { mkdtemp, writeFile, rm, readFile, lstat } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { expect, test } from "vitest";
|
||||
@@ -107,67 +107,6 @@ test("supports empty trees, unborn HEAD, staged and unstaged comparisons", async
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ name: "index to working tree", base: { kind: "index" } as const },
|
||||
{
|
||||
name: "commit to working tree with a file removed from the index",
|
||||
base: { kind: "rev", rev: "HEAD" } as const,
|
||||
},
|
||||
])("$name sees a same-size edit saved in the timestamp tick it was staged", async ({ base }) => {
|
||||
const cwd = await mkdtemp(join(tmpdir(), "diff-racy-index-"));
|
||||
const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
|
||||
const file = join(cwd, "x.ts");
|
||||
const indexPath = join(cwd, ".git", "index");
|
||||
const tick = new Date("2026-01-01T00:00:00Z");
|
||||
try {
|
||||
git("init", "-b", "main");
|
||||
git("config", "user.email", "test@example.com");
|
||||
git("config", "user.name", "Test");
|
||||
// Only mtime, size, and inode tell this edit apart; ctime always moves.
|
||||
git("config", "core.trustctime", "false");
|
||||
await writeFile(file, "const value = 1;\n");
|
||||
await writeFile(join(cwd, "y.ts"), "const kept = 1;\n");
|
||||
git("add", ".");
|
||||
git("-c", "commit.gpgsign=false", "commit", "-m", "base");
|
||||
await writeFile(file, "const value = 2;\n");
|
||||
await utimes(file, tick, tick);
|
||||
git("add", "x.ts");
|
||||
if (base.kind === "rev") {
|
||||
git("-c", "commit.gpgsign=false", "commit", "-m", "staged");
|
||||
// A file on disk and in the base commit but absent from the index
|
||||
// selects the private index for commit to working tree comparisons.
|
||||
git("rm", "--cached", "y.ts");
|
||||
}
|
||||
// The index is written in the tick the file was staged, and the file is
|
||||
// saved again with the same size within that tick.
|
||||
await utimes(indexPath, tick, tick);
|
||||
await writeFile(file, "const value = 3;\n");
|
||||
await utimes(file, tick, tick);
|
||||
expect(git("diff", "--name-only")).toBe("x.ts");
|
||||
const originalIndex = await readFile(indexPath);
|
||||
const originalMtime = (await lstat(indexPath, { bigint: true })).mtimeNs;
|
||||
|
||||
const comparison = await listComparison({
|
||||
cwd,
|
||||
base,
|
||||
head: { kind: "worktree" },
|
||||
highlight: false,
|
||||
});
|
||||
expect(comparison.files.map((entry) => entry.entry.path)).toEqual(["x.ts"]);
|
||||
const record = await readBody(comparison);
|
||||
expect(record.body.hunks[0].lines).toEqual([
|
||||
{ type: "header", content: "@@ -1 +1 @@" },
|
||||
{ type: "remove", content: "const value = 2;" },
|
||||
{ type: "add", content: "const value = 3;" },
|
||||
]);
|
||||
await comparison.close();
|
||||
expect(await readFile(indexPath)).toEqual(originalIndex);
|
||||
expect((await lstat(indexPath, { bigint: true })).mtimeNs).toBe(originalMtime);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("lists oversized untracked files without treating their truncated contents as additions", async () => {
|
||||
const cwd = await mkdtemp(join(tmpdir(), "diff-large-file-"));
|
||||
const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
|
||||
|
||||
@@ -327,39 +327,6 @@ test("unsubscribe cancels reconciliation queued by a write burst", async () => {
|
||||
expect(callback).toHaveBeenCalledTimes(callsAtClose);
|
||||
}, 20_000);
|
||||
|
||||
test("aborting a pending subscription stops its startup scan and rejects", async () => {
|
||||
const root = await createRoot();
|
||||
// More directories than the Linux backend watches: a scan that keeps walking after the abort
|
||||
// fails on the directory limit instead of rejecting with the abort reason.
|
||||
await Promise.all(
|
||||
Array.from({ length: 80 }, (_, outer) =>
|
||||
Promise.all(
|
||||
Array.from({ length: 70 }, (__, inner) =>
|
||||
mkdir(join(root, `dir-${outer}`, `nested-${inner}`), { recursive: true }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const observer = createObserver();
|
||||
const controller = new AbortController();
|
||||
const reason = new Error("setup deadline passed");
|
||||
const callback = vi.fn();
|
||||
|
||||
const subscription = observer.subscribe(root, callback, { signal: controller.signal });
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
controller.abort(reason);
|
||||
|
||||
await expect(subscription).rejects.toBe(reason);
|
||||
expect(observer.getDiagnostics()).toMatchObject({
|
||||
activeObservationCount: 0,
|
||||
nativeHandleCount: 0,
|
||||
pendingReconciliationWorkCount: 0,
|
||||
});
|
||||
await writeFile(join(root, "dir-0", "after-abort.txt"), "late");
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
expect(callback).not.toHaveBeenCalled();
|
||||
}, 20_000);
|
||||
|
||||
test("aggregate diagnostics return to their lifecycle baseline", async () => {
|
||||
const root = await createRoot();
|
||||
const observer = createObserver();
|
||||
|
||||
@@ -14,8 +14,6 @@ export interface FileChange {
|
||||
|
||||
export interface FileObserverOptions {
|
||||
ignore?: string[];
|
||||
// Aborting before `subscribe()` resolves stops the startup scan and rejects with the reason.
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export type FileObserverCallback = (error: Error | null, events: FileChange[]) => void;
|
||||
@@ -107,19 +105,7 @@ class FileObserverService implements FileObserver {
|
||||
createBackend: this.createBackend,
|
||||
onClosed: () => state.observations.delete(observation),
|
||||
});
|
||||
const { signal } = options;
|
||||
signal?.throwIfAborted();
|
||||
const abort = () => void observation.close();
|
||||
signal?.addEventListener("abort", abort, { once: true });
|
||||
try {
|
||||
await observation.start();
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", abort);
|
||||
}
|
||||
if (signal?.aborted) {
|
||||
await observation.close();
|
||||
throw signal.reason;
|
||||
}
|
||||
await observation.start();
|
||||
if (this.closePromise) {
|
||||
await observation.close();
|
||||
throw new Error("File observer is closed");
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, test } from "vitest";
|
||||
import { createFileObserver } from "../index.js";
|
||||
import { createNativeRecursiveBackend } from "./native-recursive.js";
|
||||
import { createManagedObservation } from "./observation.js";
|
||||
import { createObserverPaths } from "./paths.js";
|
||||
|
||||
// Aborting a subscription closes its observation while start() may still be
|
||||
// reading the root, before the backend has started.
|
||||
test("closing an observation before its backend starts leaves no native watcher open", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "observation-close-"));
|
||||
const paths = createObserverPaths(process.platform);
|
||||
let openWatchers = 0;
|
||||
const observation = createManagedObservation({
|
||||
root,
|
||||
callback: () => {},
|
||||
options: {},
|
||||
paths,
|
||||
metrics: createFileObserver().getDiagnostics(),
|
||||
createBackend: (host) =>
|
||||
createNativeRecursiveBackend(host, paths, () => {
|
||||
openWatchers += 1;
|
||||
let open = true;
|
||||
return {
|
||||
close: () => {
|
||||
if (open) openWatchers -= 1;
|
||||
open = false;
|
||||
},
|
||||
on: () => {},
|
||||
};
|
||||
}),
|
||||
onClosed: () => {},
|
||||
});
|
||||
try {
|
||||
const started = observation.start();
|
||||
const closed = observation.close();
|
||||
await started;
|
||||
await closed;
|
||||
|
||||
expect(openWatchers).toBe(0);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -69,9 +69,6 @@ class Observation implements ManagedObservation, ObservationHost {
|
||||
if (!rootStats.isDirectory()) {
|
||||
throw new Error(`File observation requires a directory: ${this.root}`);
|
||||
}
|
||||
// An aborted subscription can close the observation while the root is being read; the backend
|
||||
// must not start after its close has already finished.
|
||||
if (!this.isActive()) return;
|
||||
try {
|
||||
await this.backend.start();
|
||||
} catch (error) {
|
||||
|
||||
@@ -527,25 +527,13 @@ test("agent creation hooks change the provider and environment before the sessio
|
||||
});
|
||||
server.addHook("agent.open.before", async ({ request }) => {
|
||||
console.log(JSON.stringify({ hook: "agent.open.before", request }));
|
||||
return { ...request, appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "Plugin instructions"], env: { ...request.env, HOOK_OPEN: "opened" } };
|
||||
return { ...request, env: { ...request.env, HOOK_OPEN: "opened" } };
|
||||
});
|
||||
server.addHook("agent.create.after", async (event) => {
|
||||
console.log(JSON.stringify({ hook: "agent.create.after", event }));
|
||||
});`,
|
||||
reportOpen: true,
|
||||
});
|
||||
const extraPlugin = path.join(directory, "extra-plugin");
|
||||
await mkdir(extraPlugin);
|
||||
await writeFile(
|
||||
path.join(extraPlugin, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: "a-prompt", requirements: { paseo: ">=0.8.0" } }),
|
||||
);
|
||||
const writePrompt = (prompt: string) =>
|
||||
writeFile(
|
||||
path.join(extraPlugin, "index.server.ts"),
|
||||
`export default function contribute(server) { server.addHook("agent.open.before", async ({ request }) => ({ ...request, appendSystemPrompt: [...(request.appendSystemPrompt ?? []), ${JSON.stringify(prompt)}] })); return () => {}; }`,
|
||||
);
|
||||
await writePrompt("First plugin");
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
try {
|
||||
@@ -553,17 +541,15 @@ test("agent creation hooks change the provider and environment before the sessio
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(pluginDirectory);
|
||||
await client.installDirectoryPlugin(extraPlugin);
|
||||
const agent = await client.createAgent({
|
||||
provider: "claude",
|
||||
cwd: directory,
|
||||
title: "Hook test",
|
||||
systemPrompt: "Saved instructions",
|
||||
});
|
||||
expect(agent.provider).toBe(PROVIDER_ID);
|
||||
expect(await daemon.daemon.agentStorage.get(agent.id)).toMatchObject({
|
||||
provider: PROVIDER_ID,
|
||||
config: { model: "shutdown-model", systemPrompt: "Saved instructions" },
|
||||
config: { model: "shutdown-model" },
|
||||
});
|
||||
await expect
|
||||
.poll(async () => {
|
||||
@@ -583,32 +569,13 @@ test("agent creation hooks change the provider and environment before the sessio
|
||||
},
|
||||
{
|
||||
hook: "provider.open",
|
||||
config: {
|
||||
env: { HOOK_CREATE: "created", HOOK_OPEN: "opened" },
|
||||
systemPrompt: "Saved instructions\n\nFirst plugin\n\nPlugin instructions",
|
||||
},
|
||||
config: { env: { HOOK_CREATE: "created", HOOK_OPEN: "opened" } },
|
||||
},
|
||||
{
|
||||
hook: "agent.create.after",
|
||||
event: { agent: { id: agent.id, provider: PROVIDER_ID } },
|
||||
},
|
||||
]);
|
||||
await writePrompt("Changed plugin");
|
||||
await client.reloadPlugin("a-prompt");
|
||||
await daemon.daemon.agentManager.reloadAgentSession(agent.id);
|
||||
await client.disablePlugin("a-prompt");
|
||||
await daemon.daemon.agentManager.reloadAgentSession(agent.id);
|
||||
const opens = (await client.getPluginLogs("shutdown-provider-plugin"))
|
||||
.filter((entry) => entry.message.startsWith('{"hook":"provider.open"'))
|
||||
.map((entry) => JSON.parse(entry.message).config.systemPrompt);
|
||||
expect(opens).toEqual([
|
||||
"Saved instructions\n\nFirst plugin\n\nPlugin instructions",
|
||||
"Saved instructions\n\nChanged plugin\n\nPlugin instructions",
|
||||
"Saved instructions\n\nPlugin instructions",
|
||||
]);
|
||||
expect((await daemon.daemon.agentStorage.get(agent.id))?.config?.systemPrompt).toBe(
|
||||
"Saved instructions",
|
||||
);
|
||||
await client.archiveAgent(agent.id);
|
||||
} finally {
|
||||
await client.close();
|
||||
|
||||
@@ -228,9 +228,7 @@ test.each([{ title: "Changed" }, { labels: { changed: "true" } }, { background:
|
||||
},
|
||||
paseo,
|
||||
),
|
||||
).rejects.toThrow(
|
||||
"agent.open.before hooks can only change env, tools, mcpServers, and appendSystemPrompt",
|
||||
);
|
||||
).rejects.toThrow("agent.open.before hooks can only change env, tools, and mcpServers");
|
||||
},
|
||||
);
|
||||
|
||||
@@ -359,42 +357,3 @@ test("checkout-branch hooks reject a branch-off baseRef", async () => {
|
||||
validateBeforeResult("worktree.create.before", request, { ...request, baseRef: "main" }),
|
||||
).rejects.toThrow(/baseRef/);
|
||||
});
|
||||
|
||||
test("session-open instructions compose, survive old hooks, and are ignored for history", async () => {
|
||||
const hooks = new PluginHookHandlers(() => {});
|
||||
hooks.addHook("agent.open.before", async ({ request }) => ({
|
||||
...request,
|
||||
appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "first"],
|
||||
}));
|
||||
hooks.addHook("agent.open.before", async ({ request }) => {
|
||||
const { appendSystemPrompt: _ignored, ...oldRequest } = request;
|
||||
return oldRequest;
|
||||
});
|
||||
hooks.addHook("agent.open.before", async ({ request }) => ({
|
||||
...request,
|
||||
appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "second"],
|
||||
}));
|
||||
const input = {
|
||||
agentId: "agent",
|
||||
workspaceId: null,
|
||||
provider: "codex",
|
||||
cwd: "/project",
|
||||
reason: "resume",
|
||||
purpose: "interactive",
|
||||
env: {},
|
||||
title: null,
|
||||
labels: {},
|
||||
metadata: {},
|
||||
tools: [],
|
||||
mcpServers: {},
|
||||
};
|
||||
const interactive = await hooks.invoke("interactive", "agent.open.before", input, paseo);
|
||||
expect(interactive).toMatchObject({ appendSystemPrompt: ["first", "second"] });
|
||||
const history = await hooks.invoke(
|
||||
"history",
|
||||
"agent.open.before",
|
||||
{ ...input, purpose: "history" },
|
||||
paseo,
|
||||
);
|
||||
expect(history).not.toHaveProperty("appendSystemPrompt");
|
||||
});
|
||||
|
||||
@@ -108,7 +108,6 @@ const beforeSchemas = {
|
||||
labels: z.record(z.string(), z.string()),
|
||||
// Optional so a plugin that returns its own object keeps working; omitted means unchanged.
|
||||
metadata: z.record(z.string(), z.custom<JsonValue>()).optional(),
|
||||
appendSystemPrompt: z.array(z.string()).optional(),
|
||||
tools: z.array(agentToolMetadataSchema),
|
||||
env: z.record(z.string(), z.string()),
|
||||
mcpServers: CreateAgentRequestMessageSchema.shape.config.shape.mcpServers.unwrap(),
|
||||
@@ -249,18 +248,9 @@ export async function validateBeforeResult<Name extends keyof PluginWireBeforeRe
|
||||
const previous = beforeSchemas["agent.open.before"].parse(input);
|
||||
const next = beforeSchemas["agent.open.before"].parse(result);
|
||||
if (changesSessionOpenTarget(previous, next)) {
|
||||
throw new Error(
|
||||
"agent.open.before hooks can only change env, tools, mcpServers, and appendSystemPrompt",
|
||||
);
|
||||
throw new Error("agent.open.before hooks can only change env, tools, and mcpServers");
|
||||
}
|
||||
return {
|
||||
...result,
|
||||
background: previous.background,
|
||||
metadata: previous.metadata,
|
||||
...(next.appendSystemPrompt === undefined && previous.appendSystemPrompt !== undefined
|
||||
? { appendSystemPrompt: previous.appendSystemPrompt }
|
||||
: {}),
|
||||
};
|
||||
return { ...result, background: previous.background, metadata: previous.metadata };
|
||||
}
|
||||
if (name === "agent.create.before") {
|
||||
const previous = beforeSchemas["agent.create.before"].parse(input);
|
||||
@@ -386,7 +376,6 @@ export class PluginHookHandlers implements PluginLifecycleRegistration {
|
||||
if (request.purpose === "history") {
|
||||
request.tools = [];
|
||||
request.mcpServers = {};
|
||||
delete request.appendSystemPrompt;
|
||||
} else this.agentTools?.attach(request.agentId, tools);
|
||||
return request;
|
||||
}
|
||||
|
||||
@@ -12,31 +12,12 @@ export function createTestAgentMessages(params: {
|
||||
agentManager: AgentManager;
|
||||
agentStorage: AgentStorage;
|
||||
logger: Logger;
|
||||
schedule?: (delayMs: number, callback: () => void) => () => void;
|
||||
}) {
|
||||
return createAgentMessageDelivery({
|
||||
tryRunOutOfBand: (request, onAccepted) =>
|
||||
params.agentManager.tryRunOutOfBand(
|
||||
request.recipientId,
|
||||
request.prompt,
|
||||
{ clientMessageId: request.messageIds[0] },
|
||||
onAccepted,
|
||||
),
|
||||
isRunning: (agentId) => params.agentManager.hasInFlightRun(agentId),
|
||||
hasPendingPermission: (agentId) => params.agentManager.hasPendingPermissions(agentId),
|
||||
subscribe: (notify) =>
|
||||
params.agentManager.subscribe(
|
||||
(event) => {
|
||||
if (event.type === "agent_state") notify(event.agent.id);
|
||||
},
|
||||
{ replayState: false },
|
||||
),
|
||||
schedule:
|
||||
params.schedule ??
|
||||
((_delay, callback) => {
|
||||
const timer = setTimeout(callback, 0);
|
||||
return () => clearTimeout(timer);
|
||||
}),
|
||||
schedule: (_delay, callback) => {
|
||||
const timer = setTimeout(callback, 0);
|
||||
return () => clearTimeout(timer);
|
||||
},
|
||||
dispatch: async (request) => {
|
||||
const result = await sendPreparedPromptToAgent({
|
||||
...params,
|
||||
@@ -45,8 +26,8 @@ export function createTestAgentMessages(params: {
|
||||
sessionMode: request.sessionMode,
|
||||
unarchive: request.unarchive,
|
||||
activeTurnBehavior: request.activeTurnBehavior,
|
||||
idleOnly: request.idleOnly,
|
||||
clearPendingPermissions: request.clearPendingPermissions,
|
||||
onDispatch: request.onDispatch,
|
||||
runOptions: { clientMessageId: request.messageIds[0] },
|
||||
});
|
||||
if (result.disposition === "turn_started")
|
||||
|
||||
@@ -728,22 +728,6 @@ export class VoiceAssistantWebSocketServer {
|
||||
this.agentManager = agentManager;
|
||||
this.agentStorage = agentStorage;
|
||||
this.agentMessages = createAgentMessageDelivery({
|
||||
tryRunOutOfBand: (request, onAccepted) =>
|
||||
agentManager.tryRunOutOfBand(
|
||||
request.recipientId,
|
||||
request.prompt,
|
||||
{ clientMessageId: request.messageIds[0] },
|
||||
onAccepted,
|
||||
),
|
||||
isRunning: (agentId) => agentManager.hasInFlightRun(agentId),
|
||||
hasPendingPermission: (agentId) => agentManager.hasPendingPermissions(agentId),
|
||||
subscribe: (notify) =>
|
||||
agentManager.subscribe(
|
||||
(event) => {
|
||||
if (event.type === "agent_state") notify(event.agent.id);
|
||||
},
|
||||
{ replayState: false },
|
||||
),
|
||||
dispatch: async (batch) => {
|
||||
const { disposition } = await sendPreparedPromptToAgent({
|
||||
agentManager,
|
||||
@@ -751,11 +735,11 @@ export class VoiceAssistantWebSocketServer {
|
||||
agentId: batch.recipientId,
|
||||
prompt: batch.prompt,
|
||||
activeTurnBehavior: batch.activeTurnBehavior,
|
||||
idleOnly: batch.idleOnly,
|
||||
sessionMode: batch.sessionMode,
|
||||
clearPendingPermissions: batch.clearPendingPermissions,
|
||||
unarchive: batch.unarchive,
|
||||
runOptions: { clientMessageId: batch.messageIds[0] },
|
||||
onDispatch: batch.onDispatch,
|
||||
logger: this.logger,
|
||||
});
|
||||
if (disposition === "turn_started")
|
||||
|
||||
@@ -2195,7 +2195,6 @@ describe("WorkspaceGitServiceImpl D2 read methods", () => {
|
||||
expect(subscribe).toHaveBeenCalledTimes(1);
|
||||
expect(subscribe).toHaveBeenCalledWith(repoDir, expect.any(Function), {
|
||||
ignore: [join(repoDir, ".git"), ignoredRoot],
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
|
||||
subscription.unsubscribe();
|
||||
|
||||
@@ -477,56 +477,6 @@ async function advanceThroughWorkingTreeRecoveryAttempts(
|
||||
}
|
||||
}
|
||||
|
||||
// Stalls every subscription for `watchPath` the way a CPU-starved startup scan does, until the
|
||||
// service aborts it at the subscribe deadline. Other paths subscribe immediately.
|
||||
function createStallingWatchSetup(watchPath: string) {
|
||||
const signals: AbortSignal[] = [];
|
||||
let acceptNext = false;
|
||||
let acceptedCallback: WatchCallback | null = null;
|
||||
const subscribe = vi.fn(
|
||||
async (directory: string, callback: WatchCallback, options?: { signal?: AbortSignal }) => {
|
||||
if (directory !== watchPath) {
|
||||
return createAsyncSubscription();
|
||||
}
|
||||
const signal = options?.signal ?? new AbortController().signal;
|
||||
signals.push(signal);
|
||||
if (acceptNext) {
|
||||
acceptNext = false;
|
||||
acceptedCallback = callback;
|
||||
return createAsyncSubscription();
|
||||
}
|
||||
return new Promise<ReturnType<typeof createAsyncSubscription>>((_resolve, reject) => {
|
||||
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
|
||||
});
|
||||
},
|
||||
);
|
||||
return {
|
||||
subscribe,
|
||||
signals,
|
||||
acceptNextAttempt() {
|
||||
acceptNext = true;
|
||||
},
|
||||
failAcceptedWatcher() {
|
||||
acceptedCallback?.(new Error("accepted watcher stopped"), []);
|
||||
},
|
||||
async expectAttemptAbortedAtDeadline() {
|
||||
const signal = signals.at(-1);
|
||||
expect(signal?.aborted).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS);
|
||||
expect(signal?.aborted).toBe(true);
|
||||
expect(signal?.reason).toMatchObject({ name: "WorkspaceGitWatcherSubscriptionTimeoutError" });
|
||||
},
|
||||
async expectNextAttemptAfter(delayMs: number, service: WorkspaceGitServiceImpl) {
|
||||
const attempts = signals.length;
|
||||
await vi.advanceTimersByTimeAsync(delayMs - 1);
|
||||
await waitForRefreshesToSettle(service);
|
||||
expect(signals).toHaveLength(attempts);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await settle(() => expect(signals).toHaveLength(attempts + 1));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("WorkspaceGitServiceImpl", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
@@ -1623,7 +1573,6 @@ describe("WorkspaceGitServiceImpl", () => {
|
||||
expect(subscribe).toHaveBeenCalledTimes(1);
|
||||
expect(subscribe).toHaveBeenCalledWith(REPO_CWD, expect.any(Function), {
|
||||
ignore: [join(REPO_CWD, ".git")],
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
|
||||
subscription.unsubscribe();
|
||||
@@ -1699,67 +1648,6 @@ describe("WorkspaceGitServiceImpl", () => {
|
||||
15_000,
|
||||
);
|
||||
|
||||
test.each(["repository metadata", "working tree"])(
|
||||
"aborts each timed-out %s watcher setup and backs retries off toward an hour",
|
||||
async (kind) => {
|
||||
const watchPath = kind === "repository metadata" ? join(REPO_CWD, ".git") : REPO_CWD;
|
||||
const setup = createStallingWatchSetup(watchPath);
|
||||
const getCheckoutStatus = vi.fn(async (cwd: string) => createCheckoutStatus(cwd));
|
||||
const service = createService({ subscribe: setup.subscribe, getCheckoutStatus });
|
||||
const subscription = service.registerWorkspace({ cwd: REPO_CWD }, vi.fn());
|
||||
try {
|
||||
await settle(() => expect(setup.signals).toHaveLength(1));
|
||||
await setup.expectAttemptAbortedAtDeadline();
|
||||
await waitForObservationToSettle(service, 1);
|
||||
for (const delayMs of [
|
||||
30_000, 60_000, 120_000, 240_000, 480_000, 960_000, 1_920_000, 3_600_000,
|
||||
]) {
|
||||
await setup.expectNextAttemptAfter(delayMs, service);
|
||||
await setup.expectAttemptAbortedAtDeadline();
|
||||
}
|
||||
// Degraded polling keeps the checkout fresh while the watcher waits out an hour.
|
||||
const readsBeforeCappedWait = getCheckoutStatus.mock.calls.length;
|
||||
await setup.expectNextAttemptAfter(3_600_000, service);
|
||||
expect(getCheckoutStatus.mock.calls.length).toBeGreaterThanOrEqual(
|
||||
readsBeforeCappedWait + 59,
|
||||
);
|
||||
} finally {
|
||||
subscription.unsubscribe();
|
||||
await service.dispose();
|
||||
}
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
|
||||
test.each(["repository metadata", "working tree"])(
|
||||
"an accepted %s watcher subscription resets the setup-timeout backoff",
|
||||
async (kind) => {
|
||||
const watchPath = kind === "repository metadata" ? join(REPO_CWD, ".git") : REPO_CWD;
|
||||
const setup = createStallingWatchSetup(watchPath);
|
||||
const service = createService({ subscribe: setup.subscribe });
|
||||
const subscription = service.registerWorkspace({ cwd: REPO_CWD }, vi.fn());
|
||||
try {
|
||||
await settle(() => expect(setup.signals).toHaveLength(1));
|
||||
await setup.expectAttemptAbortedAtDeadline();
|
||||
for (const delayMs of [30_000, 60_000, 120_000, 240_000, 480_000]) {
|
||||
await setup.expectNextAttemptAfter(delayMs, service);
|
||||
await setup.expectAttemptAbortedAtDeadline();
|
||||
}
|
||||
setup.acceptNextAttempt();
|
||||
await setup.expectNextAttemptAfter(960_000, service);
|
||||
setup.failAcceptedWatcher();
|
||||
// The ordinary recovery ladder's ceiling applies again, not the 32-minute timeout step.
|
||||
await setup.expectNextAttemptAfter(300_000, service);
|
||||
await setup.expectAttemptAbortedAtDeadline();
|
||||
await setup.expectNextAttemptAfter(300_000, service);
|
||||
} finally {
|
||||
subscription.unsubscribe();
|
||||
await service.dispose();
|
||||
}
|
||||
},
|
||||
30_000,
|
||||
);
|
||||
|
||||
test.each(["repository metadata", "working tree"])(
|
||||
"ignores expired %s watcher callbacks after recovery",
|
||||
async (kind) => {
|
||||
@@ -1985,7 +1873,6 @@ describe("WorkspaceGitServiceImpl", () => {
|
||||
expect(subscription.repoRoot).toBeNull();
|
||||
expect(subscribe).toHaveBeenCalledWith(plainCwd, expect.any(Function), {
|
||||
ignore: [join(plainCwd, ".git")],
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
|
||||
|
||||
@@ -123,11 +123,6 @@ const WATCH_RECOVERY_BASE_DELAY_MS = 30_000;
|
||||
// restart, which kills running agents. Back off, but keep trying.
|
||||
const WATCH_RECOVERY_MAX_DELAY_MS = 300_000;
|
||||
const WATCH_RECOVERY_MAX_BACKOFF_STEPS = 4;
|
||||
// A startup scan that missed the subscribe deadline on a CPU-starved host misses it again on the
|
||||
// next attempt, and every attempt repeats the full scan. Consecutive setup timeouts therefore
|
||||
// keep doubling the recovery delay past the ladder cap, up to an hour.
|
||||
const WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS = 3_600_000;
|
||||
const WATCH_SETUP_TIMEOUT_MAX_BACKOFF_STEPS = 7;
|
||||
// Auxiliary reads may reuse cached values within this window; snapshots do not expire on read.
|
||||
const WORKSPACE_GIT_AUXILIARY_READ_TTL_MS = 15_000;
|
||||
// Non-forced refresh triggers share this minimum gap to absorb watcher/self-heal bursts; force bypasses it.
|
||||
@@ -579,10 +574,6 @@ interface WatchRecoveryState {
|
||||
// use (SMB/NFS, Docker virtiofs, some FUSE) resets the ladder on every
|
||||
// attempt and the backoff never engages.
|
||||
establishedAt: number | null;
|
||||
// Setup attempts that hit WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS since the last accepted
|
||||
// subscription. Reset on acceptance: finishing the startup scan in time is the proof that
|
||||
// the next attempt is affordable.
|
||||
setupTimeoutCount: number;
|
||||
}
|
||||
|
||||
function setsEqual(left: ReadonlySet<string>, right: ReadonlySet<string>): boolean {
|
||||
@@ -1528,7 +1519,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
fallbackPolling: false,
|
||||
fallbackPollTimer: null,
|
||||
fallbackPollQuietTickCount: 0,
|
||||
recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 },
|
||||
recovery: { attemptCount: 0, timer: null, establishedAt: null },
|
||||
listeners: new Set(),
|
||||
closed: false,
|
||||
};
|
||||
@@ -1558,12 +1549,9 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
let removeAbortListener = () => {};
|
||||
let unsubscribePromise: Promise<void> | null = null;
|
||||
let subscriptionPromise: Promise<FileObserverSubscription>;
|
||||
// Abandoning the race is not enough: the observer's startup scan would keep walking the
|
||||
// tree after the deadline. Abort it so a timed-out attempt stops costing CPU.
|
||||
const setupController = new AbortController();
|
||||
try {
|
||||
subscriptionPromise = this.deps
|
||||
.subscribe(watchPath, callback, { ...options, signal: setupController.signal })
|
||||
.subscribe(watchPath, callback, options)
|
||||
.finally(onSubscribeSettled);
|
||||
} catch (error) {
|
||||
onSubscribeSettled();
|
||||
@@ -1582,15 +1570,12 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
const timeoutPromise = new Promise<never>((_resolve, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
outcome = "expired";
|
||||
const error = new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath);
|
||||
setupController.abort(error);
|
||||
reject(error);
|
||||
reject(new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath));
|
||||
}, WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS);
|
||||
});
|
||||
const disposalPromise = new Promise<never>((_resolve, reject) => {
|
||||
const rejectForDisposal = () => {
|
||||
outcome = "expired";
|
||||
setupController.abort(signal.reason);
|
||||
reject(signal.reason);
|
||||
};
|
||||
if (signal.aborted) {
|
||||
@@ -1725,7 +1710,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
// `scheduleWorkingTreeWatchRecovery` only resets the ladder once this
|
||||
// one has survived long enough to prove itself durable.
|
||||
target.recovery.establishedAt = this.deps.now().getTime();
|
||||
target.recovery.setupTimeoutCount = 0;
|
||||
if (options?.replaceFallback && target.repoRoot !== null) {
|
||||
target.fallbackPolling = false;
|
||||
if (target.fallbackPollTimer) {
|
||||
@@ -1746,7 +1730,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
{ err: error, cwd: target.cwd },
|
||||
"Failed to start working tree watcher; using degraded polling",
|
||||
);
|
||||
this.noteWatchSetupFailure(target.recovery, error);
|
||||
if (!options?.replaceFallback) {
|
||||
this.startWorkingTreeWatchFallback(target, "watcher_setup_failed");
|
||||
}
|
||||
@@ -1969,26 +1952,11 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
}
|
||||
recovery.establishedAt = null;
|
||||
recovery.attemptCount += 1;
|
||||
const ladderDelayMs = Math.min(
|
||||
return Math.min(
|
||||
WATCH_RECOVERY_BASE_DELAY_MS *
|
||||
2 ** Math.min(recovery.attemptCount - 1, WATCH_RECOVERY_MAX_BACKOFF_STEPS),
|
||||
WATCH_RECOVERY_MAX_DELAY_MS,
|
||||
);
|
||||
if (recovery.setupTimeoutCount === 0) {
|
||||
return ladderDelayMs;
|
||||
}
|
||||
const setupTimeoutDelayMs = Math.min(
|
||||
WATCH_RECOVERY_BASE_DELAY_MS *
|
||||
2 ** Math.min(recovery.setupTimeoutCount - 1, WATCH_SETUP_TIMEOUT_MAX_BACKOFF_STEPS),
|
||||
WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS,
|
||||
);
|
||||
return Math.max(ladderDelayMs, setupTimeoutDelayMs);
|
||||
}
|
||||
|
||||
private noteWatchSetupFailure(recovery: WatchRecoveryState, error: unknown): void {
|
||||
if (error instanceof WorkspaceGitWatcherSubscriptionTimeoutError) {
|
||||
recovery.setupTimeoutCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleWorkingTreeWatchRecovery(target: WorkingTreeWatchTarget): void {
|
||||
@@ -2462,7 +2430,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
fallbackPolling: false,
|
||||
fallbackPollTimer: null,
|
||||
fallbackPollQuietTickCount: 0,
|
||||
recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 },
|
||||
recovery: { attemptCount: 0, timer: null, establishedAt: null },
|
||||
intervalId: null,
|
||||
fetchInFlight: false,
|
||||
bufferedFetchMetadataEvents: [],
|
||||
@@ -2612,7 +2580,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
// subscribe success alone, only record when this subscription was
|
||||
// established.
|
||||
target.recovery.establishedAt = this.deps.now().getTime();
|
||||
target.recovery.setupTimeoutCount = 0;
|
||||
if (options?.replaceFallback) {
|
||||
target.fallbackPolling = false;
|
||||
if (target.fallbackPollTimer) {
|
||||
@@ -2636,7 +2603,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
{ err: error, repoGitRoot: target.repoGitRoot },
|
||||
"Failed to start repository metadata watcher; using degraded polling",
|
||||
);
|
||||
this.noteWatchSetupFailure(target.recovery, error);
|
||||
if (!options?.replaceFallback) {
|
||||
this.startRepoMetadataFallback(target);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
type TerminalWorkerRecord,
|
||||
} from "./terminal-worker-record.js";
|
||||
import { createTerminalWorkerRecordPublisher } from "./terminal-worker-record-publisher.js";
|
||||
import { listenOnTerminalWorkerSocket } from "./terminal-worker-socket-path.js";
|
||||
import { resolveTerminalWorkerSocketPath } from "./terminal-worker-socket-path.js";
|
||||
import {
|
||||
TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV,
|
||||
TERMINAL_WORKER_PROTOCOL_VERSION,
|
||||
@@ -700,25 +700,23 @@ function runWorker(argv: string[]): void {
|
||||
}
|
||||
|
||||
async function start(): Promise<void> {
|
||||
const { socketPath, listener } = await listenOnTerminalWorkerSocket({
|
||||
const socketPath = resolveTerminalWorkerSocketPath({
|
||||
paseoHome: args.paseoHome,
|
||||
workerPid: process.pid,
|
||||
recordId: args.recordId,
|
||||
listen: (candidatePath) => {
|
||||
if (process.platform !== "win32") {
|
||||
rmSync(candidatePath, { force: true });
|
||||
}
|
||||
const listening = createServer(handleConnection);
|
||||
return new Promise<Server>((resolve, reject) => {
|
||||
listening.once("error", reject);
|
||||
listening.listen(candidatePath, () => {
|
||||
listening.off("error", reject);
|
||||
resolve(listening);
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
server = listener;
|
||||
if (process.platform !== "win32") {
|
||||
rmSync(socketPath, { force: true });
|
||||
}
|
||||
const listening = createServer(handleConnection);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
listening.once("error", reject);
|
||||
listening.listen(socketPath, () => {
|
||||
listening.off("error", reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
server = listening;
|
||||
if (process.platform !== "win32") {
|
||||
chmodSync(socketPath, PRIVATE_FILE_MODE);
|
||||
}
|
||||
|
||||
@@ -577,27 +577,20 @@ describe.skipIf(isPlatform("win32"))("terminal worker reaper", () => {
|
||||
|
||||
// chmod cannot make a file unreadable to root.
|
||||
describe.skipIf(process.getuid?.() === 0)("a record that cannot be opened for a moment", () => {
|
||||
// The reaper signals a worker only once its socket accepts, so wait for the listen.
|
||||
async function spawnListeningWorker(socketPath: string): Promise<ChildProcess> {
|
||||
it("still ends a live worker it names, then retires the record", async () => {
|
||||
const home = makeHome();
|
||||
const worker = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
"-e",
|
||||
`require("node:net").createServer(() => {}).listen(${JSON.stringify(socketPath)}, () => process.stdout.write("listening\\n"));setInterval(() => {}, 1e9)`,
|
||||
`require("node:net").createServer(() => {}).listen(${JSON.stringify(path.join(home, "live-record-under-test.sock"))});setInterval(() => {}, 1e9)`,
|
||||
"--",
|
||||
"--paseo-terminal-worker",
|
||||
"record-under-test",
|
||||
],
|
||||
{ detached: true, stdio: ["ignore", "pipe", "ignore"] },
|
||||
{ detached: true, stdio: "ignore" },
|
||||
);
|
||||
children.push(worker);
|
||||
await new Promise((resolve) => worker.stdout!.once("data", resolve));
|
||||
return worker;
|
||||
}
|
||||
|
||||
it("still ends a live worker it names, then retires the record", async () => {
|
||||
const home = makeHome();
|
||||
const worker = await spawnListeningWorker(path.join(home, "live-record-under-test.sock"));
|
||||
const recordPath = writeRecord(home, {
|
||||
pid: worker.pid!,
|
||||
socketPath: path.join(home, "live-record-under-test.sock"),
|
||||
@@ -639,7 +632,18 @@ describe.skipIf(isPlatform("win32"))("terminal worker reaper", () => {
|
||||
|
||||
it("still reports a record that stays unreadable, and signals nothing it names", async () => {
|
||||
const home = makeHome();
|
||||
const worker = await spawnListeningWorker(path.join(home, "live-record-under-test.sock"));
|
||||
const worker = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
"-e",
|
||||
`require("node:net").createServer(() => {}).listen(${JSON.stringify(path.join(home, "live-record-under-test.sock"))});setInterval(() => {}, 1e9)`,
|
||||
"--",
|
||||
"--paseo-terminal-worker",
|
||||
"record-under-test",
|
||||
],
|
||||
{ detached: true, stdio: "ignore" },
|
||||
);
|
||||
children.push(worker);
|
||||
const recordPath = writeRecord(home, {
|
||||
pid: worker.pid!,
|
||||
socketPath: path.join(home, "live-record-under-test.sock"),
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";
|
||||
import { createServer, type Server } from "node:net";
|
||||
import { createServer } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { isPlatform } from "../test-utils/platform.js";
|
||||
import {
|
||||
listenOnTerminalWorkerSocket,
|
||||
resolveTerminalWorkerSocketPath,
|
||||
TerminalWorkerSocketPathError,
|
||||
} from "./terminal-worker-socket-path.js";
|
||||
@@ -26,36 +25,7 @@ function longHome(root: string): string {
|
||||
return home;
|
||||
}
|
||||
|
||||
const openServers: Server[] = [];
|
||||
|
||||
function listenFor(socketPath: string): Promise<Server> {
|
||||
const server = createServer();
|
||||
return new Promise((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(socketPath, () => {
|
||||
openServers.push(server);
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Stands in for a filesystem that passes the directory checks but refuses AF_UNIX bind, as AFS
|
||||
// does with EPERM.
|
||||
function refuseBindUnder(directory: string, code: string) {
|
||||
return (socketPath: string): Promise<Server> => {
|
||||
if (socketPath.startsWith(directory + path.sep)) {
|
||||
return Promise.reject(
|
||||
Object.assign(new Error(`listen ${code}: ${socketPath}`), { code, syscall: "listen" }),
|
||||
);
|
||||
}
|
||||
return listenFor(socketPath);
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
openServers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))),
|
||||
);
|
||||
afterEach(() => {
|
||||
for (const dir of temporaryDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
@@ -172,66 +142,6 @@ describe.skipIf(isPlatform("win32"))("terminal worker socket path", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(isPlatform("win32"))("terminal worker socket listen", () => {
|
||||
it("falls back to the next directory when the home's filesystem refuses the bind", async () => {
|
||||
const home = makeDir("tw-b-", "/tmp");
|
||||
const tmpDir = makeDir("tw-t-", "/tmp");
|
||||
const homeSocketDirectory = path.join(home, "terminal-worker", "sock");
|
||||
const { socketPath, listener } = await listenOnTerminalWorkerSocket({
|
||||
paseoHome: home,
|
||||
recordId: "test",
|
||||
workerPid: 11,
|
||||
tmpDir,
|
||||
listen: refuseBindUnder(homeSocketDirectory, "EPERM"),
|
||||
});
|
||||
expect(path.dirname(socketPath)).toBe(path.join(tmpDir, `paseo-${process.getuid!()}`));
|
||||
expect(listener.address()).toBe(socketPath);
|
||||
});
|
||||
|
||||
it("throws a listen error that does not mean the filesystem refuses sockets", async () => {
|
||||
const home = makeDir("tw-u-", "/tmp");
|
||||
const homeSocketDirectory = path.join(home, "terminal-worker", "sock");
|
||||
await expect(
|
||||
listenOnTerminalWorkerSocket({
|
||||
paseoHome: home,
|
||||
recordId: "test",
|
||||
workerPid: 12,
|
||||
tmpDir: makeDir("tw-t-", "/tmp"),
|
||||
listen: refuseBindUnder(homeSocketDirectory, "EADDRINUSE"),
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "EADDRINUSE" });
|
||||
});
|
||||
|
||||
it("names every candidate's bind error when no directory accepts a socket", async () => {
|
||||
const home = makeDir("tw-n-", "/tmp");
|
||||
const tmpDir = makeDir("tw-t-", "/tmp");
|
||||
let caught: unknown;
|
||||
try {
|
||||
await listenOnTerminalWorkerSocket({
|
||||
paseoHome: home,
|
||||
recordId: "test",
|
||||
workerPid: 13,
|
||||
tmpDir,
|
||||
listen: refuseBindUnder("", "EPERM"),
|
||||
});
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(TerminalWorkerSocketPathError);
|
||||
const rejected = (caught as TerminalWorkerSocketPathError).rejected;
|
||||
expect(rejected.slice(0, 2)).toEqual([
|
||||
expect.objectContaining({
|
||||
path: expect.stringContaining(path.join(home, "terminal-worker", "sock")),
|
||||
reason: "cannot bind a socket here (EPERM)",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
path: expect.stringContaining(path.join(tmpDir, `paseo-${process.getuid!()}`)),
|
||||
reason: "cannot bind a socket here (EPERM)",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it("uses a separate socket for each record even when its pid is reused", () => {
|
||||
const paseoHome = makeDir("tw-id-");
|
||||
const first = resolveTerminalWorkerSocketPath({ paseoHome, workerPid: 42, recordId: "old" });
|
||||
|
||||
@@ -14,9 +14,6 @@ const SOCKET_PATH_BYTE_BUDGET: Partial<Record<NodeJS.Platform, number>> = {
|
||||
};
|
||||
const DEFAULT_SOCKET_PATH_BYTE_BUDGET = 103;
|
||||
const OWNER_ONLY_MODE = 0o700;
|
||||
// Bind errors that mean the directory's filesystem cannot hold a Unix socket. AFS and some other
|
||||
// network filesystems pass the directory checks and then refuse AF_UNIX bind with EPERM.
|
||||
const SOCKET_UNSUPPORTED_BIND_CODES = new Set(["EPERM", "EACCES", "EOPNOTSUPP", "ENOTSUP"]);
|
||||
|
||||
export interface TerminalWorkerSocketPathInput {
|
||||
paseoHome: string;
|
||||
@@ -27,16 +24,6 @@ export interface TerminalWorkerSocketPathInput {
|
||||
uid?: number;
|
||||
}
|
||||
|
||||
export interface TerminalWorkerSocketListenInput<T> extends TerminalWorkerSocketPathInput {
|
||||
/** Binds a fresh listener at the path, removing any stale socket there first. */
|
||||
listen: (socketPath: string) => Promise<T>;
|
||||
}
|
||||
|
||||
export interface TerminalWorkerSocketListener<T> {
|
||||
socketPath: string;
|
||||
listener: T;
|
||||
}
|
||||
|
||||
export interface RejectedSocketCandidate {
|
||||
path: string;
|
||||
byteLength: number;
|
||||
@@ -49,7 +36,7 @@ export class TerminalWorkerSocketPathError extends Error {
|
||||
constructor(rejected: RejectedSocketCandidate[], budget: number) {
|
||||
super(
|
||||
[
|
||||
`No terminal worker socket path fits ${budget} bytes in an owner-only directory that accepts a socket:`,
|
||||
`No terminal worker socket path fits ${budget} bytes in an owner-only directory:`,
|
||||
...rejected.map(
|
||||
(candidate) => ` ${candidate.path} (${candidate.byteLength} bytes): ${candidate.reason}`,
|
||||
),
|
||||
@@ -70,73 +57,18 @@ export function terminalWorkerSocketId(paseoHome: string, workerPid: number): st
|
||||
* Picks (and creates) the socket path a worker listens on. Windows uses a named pipe; POSIX
|
||||
* tries $PASEO_HOME/terminal-worker/sock, then <tmpdir>/paseo-<uid>, then /tmp/paseo-<uid>.
|
||||
* A shared root is never chmodded: an existing directory there is used only when it is a real
|
||||
* directory owned by this user with mode 0700. It does not bind; the worker listens through
|
||||
* `listenOnTerminalWorkerSocket`, which also skips directories that refuse a socket.
|
||||
* directory owned by this user with mode 0700.
|
||||
*/
|
||||
export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathInput): string {
|
||||
const platform = input.platform ?? process.platform;
|
||||
const id = terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
|
||||
if (platform === "win32") {
|
||||
return windowsPipePath(input);
|
||||
return `\\\\.\\pipe\\paseo-tw-${id}`;
|
||||
}
|
||||
const budget = socketPathByteBudget(platform);
|
||||
const rejected: RejectedSocketCandidate[] = [];
|
||||
for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) {
|
||||
return candidate.path;
|
||||
}
|
||||
throw new TerminalWorkerSocketPathError(rejected, budget);
|
||||
}
|
||||
|
||||
/**
|
||||
* Listens on the first candidate path that accepts a socket. A bind refused by the filesystem
|
||||
* moves on to the next candidate; any other listen error (EADDRINUSE, ...) is thrown as is.
|
||||
*/
|
||||
export async function listenOnTerminalWorkerSocket<T>(
|
||||
input: TerminalWorkerSocketListenInput<T>,
|
||||
): Promise<TerminalWorkerSocketListener<T>> {
|
||||
const { listen } = input;
|
||||
const platform = input.platform ?? process.platform;
|
||||
if (platform === "win32") {
|
||||
const socketPath = windowsPipePath(input);
|
||||
return { socketPath, listener: await listen(socketPath) };
|
||||
}
|
||||
const budget = socketPathByteBudget(platform);
|
||||
const rejected: RejectedSocketCandidate[] = [];
|
||||
for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) {
|
||||
try {
|
||||
return { socketPath: candidate.path, listener: await listen(candidate.path) };
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (!code || !SOCKET_UNSUPPORTED_BIND_CODES.has(code)) throw error;
|
||||
rejected.push({
|
||||
path: candidate.path,
|
||||
byteLength: candidate.byteLength,
|
||||
reason: `cannot bind a socket here (${code})`,
|
||||
});
|
||||
}
|
||||
}
|
||||
throw new TerminalWorkerSocketPathError(rejected, budget);
|
||||
}
|
||||
|
||||
function windowsPipePath(input: TerminalWorkerSocketPathInput): string {
|
||||
return `\\\\.\\pipe\\paseo-tw-${socketFileId(input)}`;
|
||||
}
|
||||
|
||||
function socketFileId(input: TerminalWorkerSocketPathInput): string {
|
||||
return terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
|
||||
}
|
||||
|
||||
function socketPathByteBudget(platform: NodeJS.Platform): number {
|
||||
return SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
|
||||
}
|
||||
|
||||
/** Yields each candidate that fits the budget in an owner-only directory, in order. */
|
||||
function* eligibleUnixSocketPaths(
|
||||
input: TerminalWorkerSocketPathInput,
|
||||
budget: number,
|
||||
rejected: RejectedSocketCandidate[],
|
||||
): Generator<{ path: string; byteLength: number }> {
|
||||
const uid = input.uid ?? process.getuid?.() ?? 0;
|
||||
const fileName = `tw-${socketFileId(input)}.sock`;
|
||||
const budget = SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
|
||||
const fileName = `tw-${id}.sock`;
|
||||
const homeSocketDirectory = path.join(terminalWorkerDirectory(input.paseoHome), "sock");
|
||||
const candidates: Array<{ directory: string; prepare: () => string | null }> = [
|
||||
{
|
||||
@@ -155,6 +87,7 @@ function* eligibleUnixSocketPaths(
|
||||
}),
|
||||
];
|
||||
|
||||
const rejected: RejectedSocketCandidate[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const candidate of candidates) {
|
||||
const socketPath = path.join(candidate.directory, fileName);
|
||||
@@ -175,8 +108,9 @@ function* eligibleUnixSocketPaths(
|
||||
rejected.push({ path: socketPath, byteLength, reason: problem });
|
||||
continue;
|
||||
}
|
||||
yield { path: socketPath, byteLength };
|
||||
return socketPath;
|
||||
}
|
||||
throw new TerminalWorkerSocketPathError(rejected, budget);
|
||||
}
|
||||
|
||||
function prepareSharedRootDirectory(directory: string, uid: number): string | null {
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
stat as statFile,
|
||||
mkdtemp,
|
||||
copyFile,
|
||||
utimes,
|
||||
realpath,
|
||||
access,
|
||||
rm,
|
||||
@@ -3666,12 +3665,6 @@ export async function prepareAllChangesIndex(cwd: string, baseRef: string) {
|
||||
|
||||
// write-tree rewrites its index. A private snapshot prevents an index read from
|
||||
// invalidating the observation that requested it.
|
||||
//
|
||||
// Git re-reads a file whose stat matches its index entry only when the entry is
|
||||
// not older than the index file ("racy git"). A fresh copy would be newer than
|
||||
// every entry, so a same-size edit made in the tick the index was written would
|
||||
// read as unchanged. The copy takes the source's mtime, read before copying and
|
||||
// rounded down to the second, so it is never later than the source.
|
||||
export async function snapshotComparisonIndex(cwd: string) {
|
||||
const directory = await mkdtemp(resolve(tmpdir(), "paseo-comparison-index-"));
|
||||
const indexFile = resolve(directory, "index");
|
||||
@@ -3683,9 +3676,7 @@ export async function snapshotComparisonIndex(cwd: string) {
|
||||
const source = resolveGitRevParsePath(cwd, index.stdout);
|
||||
if (!source) throw new Error("Git did not return an index path");
|
||||
try {
|
||||
const { atime, mtimeMs } = await statFile(source);
|
||||
await copyFile(source, indexFile);
|
||||
await utimes(indexFile, atime, Math.floor(mtimeMs / 1000));
|
||||
} catch (error) {
|
||||
if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
|
||||
await runGitCommand(["read-tree", "--empty"], {
|
||||
|
||||
@@ -27,10 +27,6 @@ export default function contribute(server: PluginServerContext) {
|
||||
|
||||
return {
|
||||
...request,
|
||||
appendSystemPrompt: [
|
||||
...(request.appendSystemPrompt ?? []),
|
||||
"Follow the team engineering guide.",
|
||||
],
|
||||
mcpServers: {
|
||||
...request.mcpServers,
|
||||
company: {
|
||||
|
||||
@@ -31,7 +31,7 @@ Names follow `subject.operation.position`: the subject, the operation, then `bef
|
||||
|
||||
All handlers must be async. Turn completion includes success, failure, and cancellation; inspect `outcome`. Permission completion includes every resolution; inspect `resolution`.
|
||||
|
||||
Creating an agent happens once, and `agent.create.before` changes its saved configuration. Opening starts the provider process: the first run, resume after a daemon restart, reading history, importing an outside session, or reload. `agent.open.before` contributes launch-only environment, instructions, tools, and MCP servers each time. Creating opens the agent; opening an existing agent does not create it; closing ends the running instance. Opening a tab in the app is a separate action.
|
||||
Creating an agent happens once, and `agent.create.before` changes its saved configuration. Opening starts the provider process: the first run, resume after a daemon restart, reading history, importing an outside session, or reload. `agent.open.before` contributes launch-only environment, tools, and MCP servers each time. Creating opens the agent; opening an existing agent does not create it; closing ends the running instance. Opening a tab in the app is a separate action.
|
||||
|
||||
`worktree.create.after` runs before the workspace is registered. It precedes `workspace.create.after`, and both precede the first agent's `agent.create.before` / `agent.open.before`.
|
||||
|
||||
@@ -49,22 +49,22 @@ Paseo only sees the returned promise, so detached work gets no error reporting a
|
||||
|
||||
## Hooks
|
||||
|
||||
| Hook | Waits | Payload | Handler may change |
|
||||
| ------------------------- | ----- | ----------------------------------------- | -------------------------------------------------------------- |
|
||||
| `workspace.create.before` | yes | `{ request }` | Entire create request |
|
||||
| `workspace.create.after` | no | `{ workspace }` | |
|
||||
| `workspace.archive.after` | no | `{ workspace }` | |
|
||||
| `worktree.create.before` | yes | `{ request }` | Creation options and destination |
|
||||
| `worktree.create.after` | yes | `{ worktree }` | Files in the worktree; throw to abort creation |
|
||||
| `agent.create.before` | yes | `{ request: { config, env?, metadata } }` | Saved config except `cwd`; `env`; `metadata` |
|
||||
| `agent.create.after` | no | `{ agent }` | |
|
||||
| `agent.open.before` | yes | `{ request }` | Launch-only `env`, `appendSystemPrompt`, `tools`, `mcpServers` |
|
||||
| `agent.close.after` | no | `{ agent }` | |
|
||||
| `agent.archive.after` | no | `{ agent, archivedAt }` | |
|
||||
| `agent.turn.before` | no | `{ agent, turnId }` | |
|
||||
| `agent.turn.after` | no | `{ agent, turnId, outcome }` | |
|
||||
| `agent.permission.before` | no | `{ agent, request }` | |
|
||||
| `agent.permission.after` | no | `{ agent, requestId, resolution }` | |
|
||||
| Hook | Waits | Payload | Handler may change |
|
||||
| ------------------------- | ----- | ----------------------------------------- | ---------------------------------------------- |
|
||||
| `workspace.create.before` | yes | `{ request }` | Entire create request |
|
||||
| `workspace.create.after` | no | `{ workspace }` | |
|
||||
| `workspace.archive.after` | no | `{ workspace }` | |
|
||||
| `worktree.create.before` | yes | `{ request }` | Creation options and destination |
|
||||
| `worktree.create.after` | yes | `{ worktree }` | Files in the worktree; throw to abort creation |
|
||||
| `agent.create.before` | yes | `{ request: { config, env?, metadata } }` | Saved config except `cwd`; `env`; `metadata` |
|
||||
| `agent.create.after` | no | `{ agent }` | |
|
||||
| `agent.open.before` | yes | `{ request }` | Launch-only `env`, `tools`, `mcpServers` |
|
||||
| `agent.close.after` | no | `{ agent }` | |
|
||||
| `agent.archive.after` | no | `{ agent, archivedAt }` | |
|
||||
| `agent.turn.before` | no | `{ agent, turnId }` | |
|
||||
| `agent.turn.after` | no | `{ agent, turnId, outcome }` | |
|
||||
| `agent.permission.before` | no | `{ agent, request }` | |
|
||||
| `agent.permission.after` | no | `{ agent, requestId, resolution }` | |
|
||||
|
||||
## Shared payloads
|
||||
|
||||
@@ -283,7 +283,7 @@ server.addHook("agent.create.after", async ({ agent }) => {
|
||||
|
||||
## agent.open.before
|
||||
|
||||
Receives `{ request }`; only `env`, `appendSystemPrompt`, `tools`, and `mcpServers` may change, for this launch. All other fields are read-only. A throw, invalid result, or timeout fails the open.
|
||||
Receives `{ request }`; only `env`, `tools`, and `mcpServers` may change, for this launch. All other fields are read-only. A throw, invalid result, or timeout fails the open.
|
||||
|
||||
Do not await a write to the agent being opened: `setMetadata`, `setLabels`, or an option, model, thinking or mode change. The write waits for the open to finish, the open waits for your hook, so the hook times out and the open fails. Start the write without awaiting it; it runs right after the open:
|
||||
|
||||
@@ -329,19 +329,6 @@ server.addHook("agent.open.before", async ({ request }, { paseo }) => {
|
||||
| `purpose` | `interactive`, `history` |
|
||||
| `env` | Launch override map; excludes the daemon's inherited environment. Replace the map to add, replace, or remove overrides. |
|
||||
|
||||
### Append instructions on every session opening
|
||||
|
||||
```ts
|
||||
server.addHook("agent.open.before", async ({ request }) => ({
|
||||
...request,
|
||||
appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "Follow the team engineering guide."],
|
||||
}));
|
||||
```
|
||||
|
||||
Instructions follow the saved agent prompt and daemon instructions, in plugin order. They are not saved in the agent configuration and are ignored for history opens. Reload the plugin after changing its data to apply new instructions on the next reopen. Running turns continue; removing an instruction does not remove conversation history. Internal agents also receive these instructions. The ACP adapter does not send system instructions to its providers. Plugin providers receive the composed prompt, but must apply it themselves.
|
||||
|
||||
Codex instruction updates require Codex 0.121.0 or newer with a recognizable version reported by the app server. Source builds reporting `0.0.0` must use a versioned build. Paseo adds a current instruction snapshot to existing threads; earlier snapshots remain in the conversation. A crash during an update or rewinding a thread can repeat a snapshot.
|
||||
|
||||
### Inject environment variables on every session opening
|
||||
|
||||
```ts
|
||||
|
||||
@@ -29,7 +29,7 @@ export default function contribute(server: PluginServerContext) {
|
||||
|
||||
所有处理函数都必须为异步函数。轮次完成包括成功、失败和取消,请查看 `outcome`。权限完成包括所有处理结果,请查看 `resolution`。
|
||||
|
||||
创建 Agent 会发生一次,`agent.create.before` 修改已保存的配置。打开 Agent 指启动 Provider 进程,包括首次运行、daemon 重启后恢复、读取历史、导入外部会话和重新加载。`agent.open.before` 为每次启动提供临时的环境变量、指令、工具和 MCP 服务器。创建会打开 Agent;打开已有 Agent 不会创建它;关闭会结束运行中的实例。在应用中打开标签页不属于此操作。
|
||||
创建 Agent 会发生一次,`agent.create.before` 修改已保存的配置。打开 Agent 指启动 Provider 进程,包括首次运行、daemon 重启后恢复、读取历史、导入外部会话和重新加载。`agent.open.before` 为每次启动提供临时的环境变量、工具和 MCP 服务器。创建会打开 Agent;打开已有 Agent 不会创建它;关闭会结束运行中的实例。在应用中打开标签页不属于此操作。
|
||||
|
||||
`worktree.create.after` 在工作区注册前运行,随后是 `workspace.create.after`,两者都早于第一个 Agent 的 `agent.create.before` / `agent.open.before`。
|
||||
|
||||
@@ -47,22 +47,22 @@ Paseo 只观察返回的 Promise,因此独立任务没有错误报告,也没
|
||||
|
||||
## 钩子一览 {#hooks}
|
||||
|
||||
| 钩子 | 等待 | 载荷 | 可修改 |
|
||||
| ------------------------- | ---- | ----------------------------------------- | --------------------------------------------------------------- |
|
||||
| `workspace.create.before` | 是 | `{ request }` | 整个创建请求 |
|
||||
| `workspace.create.after` | 否 | `{ workspace }` | |
|
||||
| `workspace.archive.after` | 否 | `{ workspace }` | |
|
||||
| `worktree.create.before` | 是 | `{ request }` | 创建选项和目标路径 |
|
||||
| `worktree.create.after` | 是 | `{ worktree }` | worktree 中的文件;抛出错误中止创建 |
|
||||
| `agent.create.before` | 是 | `{ request: { config, env?, metadata } }` | 除 `cwd` 外的已保存配置;`env`;`metadata` |
|
||||
| `agent.create.after` | 否 | `{ agent }` | |
|
||||
| `agent.open.before` | 是 | `{ request }` | 仅用于启动的 `env`、`appendSystemPrompt`、`tools`、`mcpServers` |
|
||||
| `agent.close.after` | 否 | `{ agent }` | |
|
||||
| `agent.archive.after` | 否 | `{ agent, archivedAt }` | |
|
||||
| `agent.turn.before` | 否 | `{ agent, turnId }` | |
|
||||
| `agent.turn.after` | 否 | `{ agent, turnId, outcome }` | |
|
||||
| `agent.permission.before` | 否 | `{ agent, request }` | |
|
||||
| `agent.permission.after` | 否 | `{ agent, requestId, resolution }` | |
|
||||
| 钩子 | 等待 | 载荷 | 可修改 |
|
||||
| ------------------------- | ---- | ----------------------------------------- | ------------------------------------------ |
|
||||
| `workspace.create.before` | 是 | `{ request }` | 整个创建请求 |
|
||||
| `workspace.create.after` | 否 | `{ workspace }` | |
|
||||
| `workspace.archive.after` | 否 | `{ workspace }` | |
|
||||
| `worktree.create.before` | 是 | `{ request }` | 创建选项和目标路径 |
|
||||
| `worktree.create.after` | 是 | `{ worktree }` | worktree 中的文件;抛出错误中止创建 |
|
||||
| `agent.create.before` | 是 | `{ request: { config, env?, metadata } }` | 除 `cwd` 外的已保存配置;`env`;`metadata` |
|
||||
| `agent.create.after` | 否 | `{ agent }` | |
|
||||
| `agent.open.before` | 是 | `{ request }` | 仅用于启动的 `env`、`tools`、`mcpServers` |
|
||||
| `agent.close.after` | 否 | `{ agent }` | |
|
||||
| `agent.archive.after` | 否 | `{ agent, archivedAt }` | |
|
||||
| `agent.turn.before` | 否 | `{ agent, turnId }` | |
|
||||
| `agent.turn.after` | 否 | `{ agent, turnId, outcome }` | |
|
||||
| `agent.permission.before` | 否 | `{ agent, request }` | |
|
||||
| `agent.permission.after` | 否 | `{ agent, requestId, resolution }` | |
|
||||
|
||||
## 共享载荷 {#shared-payloads}
|
||||
|
||||
@@ -279,7 +279,7 @@ server.addHook("agent.create.after", async ({ agent }) => {
|
||||
|
||||
## agent.open.before {#agentopenbefore}
|
||||
|
||||
收到 `{ request }`,只能修改 `env`、`appendSystemPrompt`、`tools` 和 `mcpServers`,修改只用于此次启动。其他字段只读。抛出错误、无效返回或超时会让打开操作失败。
|
||||
收到 `{ request }`,只能修改 `env`、`tools` 和 `mcpServers`,修改只用于此次启动。其他字段只读。抛出错误、无效返回或超时会让打开操作失败。
|
||||
|
||||
不要 await 对正在打开的 Agent 的写入,例如 `setMetadata`。该写入要等打开完成,而打开在等你的钩子,结果钩子超时,打开失败。启动写入但不要 await,它会在打开完成后立即执行:
|
||||
|
||||
@@ -325,19 +325,6 @@ server.addHook("agent.open.before", async ({ request }, { paseo }) => {
|
||||
| `purpose` | `interactive`、`history` |
|
||||
| `env` | 启动覆盖映射;不包括 daemon 继承的环境变量。替换整个映射即可添加、替换或移除覆盖项。 |
|
||||
|
||||
### 在每次打开会话时追加指令 {#append-instructions-on-every-session-opening}
|
||||
|
||||
```ts
|
||||
server.addHook("agent.open.before", async ({ request }) => ({
|
||||
...request,
|
||||
appendSystemPrompt: [...(request.appendSystemPrompt ?? []), "Follow the team engineering guide."],
|
||||
}));
|
||||
```
|
||||
|
||||
插件指令按插件顺序追加在已保存的 Agent 提示词和 daemon 指令之后。指令不会保存到 Agent 配置中,读取历史时也会忽略这些指令。插件数据更改后,重新加载插件以在下次重新打开会话时应用新指令。正在运行的轮次会继续。移除指令不会删除对话历史。内部 Agent 也会收到这些指令。ACP 适配器不会向 Provider 发送系统指令。插件 Provider 会收到组合后的提示词,但需要自行应用。
|
||||
|
||||
更新 Codex 指令需要 Codex 0.121.0 或更新版本,且 app server 报告的版本必须可识别。版本显示为 `0.0.0` 的源码构建需要换用带版本号的构建。Paseo 会向现有会话添加当前指令快照;之前的快照仍保留在对话中。更新期间发生崩溃或回退会话时,快照可能重复。
|
||||
|
||||
### 在每次打开会话时注入环境变量 {#inject-environment-variables-on-every-session-opening}
|
||||
|
||||
```ts
|
||||
|
||||
@@ -84,7 +84,7 @@ Detach is an explicit user action in the subagents track, not an agent tool. A c
|
||||
|
||||
Agent-scoped `create_agent` defaults `notifyOnFinish` to true. Set it to `false` when you want explicit reporting or no completion callback.
|
||||
|
||||
**`send_agent_prompt`** — `{ agentId, prompt, activeTurnBehavior? }`. Use for follow-ups to an existing agent. Agent-scoped calls default to `steer`; top-level calls default to `interrupt`. For agent-scoped calls, `steer` waits until the recipient's current turn ends, and only `interrupt` stops a running turn. For top-level calls, `steer` joins the running turn and falls back to interruption when unavailable. CLI agent sends use the same defaults and accept `--behavior steer|interrupt`. Agent-scoped calls return a queued receipt immediately; messages to each recipient deliver together after two quiet seconds, or after the recipient's turn ends if it is running. Top-level calls return after dispatch acknowledgement. Agent-scoped calls default `notifyOnFinish` to true; top-level calls have no parent callback.
|
||||
**`send_agent_prompt`** — `{ agentId, prompt, activeTurnBehavior? }`. Use for follow-ups to an existing agent. Agent-scoped calls default to `steer`; top-level calls default to `interrupt`. Set `activeTurnBehavior` to `steer` or `interrupt` to override the default. Steering falls back to interruption when unavailable. CLI agent sends use the same defaults and accept `--behavior steer|interrupt`. Agent-scoped calls return a queued receipt immediately; messages to each recipient deliver after two quiet seconds. Top-level calls return after dispatch acknowledgement. Agent-scoped calls default `notifyOnFinish` to true; top-level calls have no parent callback.
|
||||
|
||||
**`update_agent`** — `{ agentId, name?, labels?, settings? }`. Use `settings` for runtime changes on an existing agent: `modeId`, `model`, `thinkingOptionId`, and provider-specific `features`. For Codex fast mode, pass `settings: { features: { "fast_mode": true } }`.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user