mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-25 17:55:18 +00:00
Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd4e817951 | ||
|
|
9f999bd570 | ||
|
|
bf10ea8732 | ||
|
|
a8528ad3d2 | ||
|
|
2c661fb076 | ||
|
|
531f6e549d | ||
|
|
e32564f2bc | ||
|
|
0258d6752e | ||
|
|
de5f139d33 | ||
|
|
372c1ba949 | ||
|
|
4dc1730a62 | ||
|
|
2581f2af45 | ||
|
|
6973c48d7e | ||
|
|
9dd0cbc146 | ||
|
|
f088fa5049 | ||
|
|
5dcd1e1e57 | ||
|
|
7ba54499d9 | ||
|
|
cbd5b7a73b | ||
|
|
8e88ce3a56 | ||
|
|
fb59e58ef1 | ||
|
|
825fa04467 | ||
|
|
8338e77f46 | ||
|
|
e5d81304f7 | ||
|
|
6b0fbfc640 | ||
|
|
b4e4803df2 | ||
|
|
3153f6f94a | ||
|
|
ecf8c812cd | ||
|
|
ab4bd6d59d | ||
|
|
2547edefcc |
@@ -131,6 +131,29 @@ jobs:
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run typecheck:examples --workspace=@getpaseo/client
|
||||
|
||||
# Plugin process launches and launch wraps quote for cmd.exe, which only real Windows checks.
|
||||
sdk-tests-windows:
|
||||
name: sdk-tests (windows-latest)
|
||||
needs: changes
|
||||
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
|
||||
- name: Install dependencies
|
||||
run: node scripts/npm-retry.mjs ci
|
||||
|
||||
- name: Build plugin SDK
|
||||
run: npm run build:relay && npm run build:client && npm run build:plugin
|
||||
|
||||
- name: Run plugin SDK tests
|
||||
run: npm run test --workspace=@getpaseo/plugin
|
||||
|
||||
# The locked Playwright installers do not support ubuntu-latest's Ubuntu 26.04.
|
||||
typecheck:
|
||||
name: typecheck
|
||||
|
||||
+60
-2
@@ -462,13 +462,56 @@ Server entries register async handlers with `server.addHook(name, handler)`, ret
|
||||
function. Names follow `subject.operation.position`, ending in `before` or `after`. Waiting is a per-hook
|
||||
registry property, independent of position. The [hooks reference](../public-docs/plugins/hooks.md)
|
||||
owns payloads, ordering, failure behavior, and examples. `agent.create.before` edits saved
|
||||
configuration; `agent.open.before` contributes launch-only `env`, `tools`, and `mcpServers` on
|
||||
every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
|
||||
configuration; `agent.open.before` contributes launch-only `env`, `tools`, `mcpServers`, and a
|
||||
[launch wrap](#launch-wrap) on every open. Executable tool definitions stay in the plugin process; only metadata crosses the boundary.
|
||||
`packages/server/src/server/plugins/session-attachments.ts` records what each plugin contributed to
|
||||
each live session. A plugin start, stop, or reload reruns only that plugin's callback per session,
|
||||
swaps its tools in place, and reopens a session only when its launch would differ. A reopen closes
|
||||
the provider process, so a reload must not reopen agents the plugin does not change.
|
||||
|
||||
### Launch wrap
|
||||
|
||||
An `agent.open.before` result can carry `wrap: [executable, ...args]`. The provider then starts that
|
||||
session's harness as `[...wrap, command, ...args]` with the final hook env. It starts with no shell,
|
||||
except Windows script launchers, which go through cmd.exe like any provider launcher
|
||||
(`spawnProcess` quotes each argument). An argument with spaces stays one element. `executable` must
|
||||
be an absolute path.
|
||||
The wrap is never saved on the agent; every open asks the hooks again, and a plugin session reopen
|
||||
reuses the wrap it opened with.
|
||||
|
||||
- **Support is a provider property.** The provider snapshot entry carries `launchWrap: true` when the
|
||||
provider can apply a wrap. Read it in `agent.create.before` with `paseo.providers.snapshot()`; an
|
||||
absent field means unsupported, which is also what a host without this feature reports. Core
|
||||
providers declare it in the provider contract table in `provider-registry.ts`; every core provider
|
||||
that starts a local harness declares it, and custom ACP providers and providers that extend a core
|
||||
one inherit it. A plugin provider declares `ProviderRegistration.launchWrap`;
|
||||
`runAcpProvider({ command })` sets it, a connector declares it itself (Muse Code does). The declaration travels with the
|
||||
registration metadata, so it is in the snapshot before the provider first connects.
|
||||
- **One wrap per open.** A later hook, in the same plugin or a later one, may omit the wrap or return
|
||||
the same value. A different value fails the open.
|
||||
- **Fail closed.** `buildLaunchContext` admits a wrapped open before any session harness starts. It
|
||||
throws `LaunchWrapUnsupportedError` (`code: "launch_wrap_unsupported"`) when the provider does not
|
||||
declare support, or when a plugin provider's live connection lacks `session.launch_wrap`. A host
|
||||
that predates `wrap` rejects the key: the hook result schema is strict. A missing launcher fails the
|
||||
spawn; nothing retries the bare command.
|
||||
|
||||
Once an open selects a wrap, a supported provider runs that session's harness through it or fails
|
||||
before starting the harness. Every provider starts through `spawnProcess({ wrap })`, which owns the
|
||||
argv and Windows launcher handling; `applyLaunchWrap` covers the launches that do not go through it
|
||||
(pty terminals, MCP stdio transports, worktree commands). The wrap also covers what Paseo starts for
|
||||
the session: stdio MCP servers Paseo hosts for the agent (OMP, OpenCode v2), Pi's MCP probe, and ACP
|
||||
client terminals. OpenCode shares one server between sessions, so a wrapped session gets a dedicated
|
||||
server instead; an explicitly configured external OpenCode server cannot be wrapped and the open
|
||||
fails. The guarantee does not cover:
|
||||
|
||||
1. Paseo's host terminal tools (`create_terminal`, `send_terminal_keys`) run outside the wrap.
|
||||
2. Work before the open hook runs unwrapped: draft command and control discovery, and the catalog
|
||||
lookup during create when no model is set.
|
||||
3. Host-side operations run unwrapped: availability and capability probes (the ACP connection's
|
||||
initialize probe included), catalog and session listing, version and update commands, usage
|
||||
queries, and Codex native archive and unarchive.
|
||||
4. Losing the plugin that chose the wrap is not covered: a later open without it runs unwrapped.
|
||||
|
||||
Worktree placement is resolved before Git source planning, so a hook can change the branch and base
|
||||
without undoing fetched refs. Restores use the recorded destination and bypass creation hooks.
|
||||
Workspace records decide ownership, including explicit non-ownership after recovery. Without a record,
|
||||
@@ -487,6 +530,17 @@ change requests; `remove` and `restore` fall back to built-in Git when the plugi
|
||||
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
|
||||
`plugin-examples/worktrunk`.
|
||||
|
||||
`terminal.create.before` runs in `withTerminalCreateHook`, which wraps the daemon's one terminal manager, so every creation path is covered and adopted terminals are not; callers pass an `origin` to name the source. `command.run.before` runs inside the setup and teardown runners through `commandRunHook`. Setup and archive dependencies take `lifecycle` as a required field so a new caller cannot skip the hook by omission; pass `null` only where no plugins run.
|
||||
|
||||
Both hooks change only `env` and a [launch wrap](#launch-wrap); `keepSelectedWrap` in the lifecycle
|
||||
module applies the one-wrap rule to all three wrap hooks. The terminal wrap becomes the terminal's
|
||||
`command` and `args` in `withTerminalCreateHook`, so the terminal worker protocol does not change and
|
||||
no previous-version adapter is needed. A default-shell terminal resolves the shell there through
|
||||
`default-terminal-shell.ts`, which stays apart from `terminal.ts` so the daemon does not load node-pty.
|
||||
The wrapped shell starts without Paseo's shell integration, which is why a wrapped script does not
|
||||
report command completion. A setup or teardown wrap goes in front of the
|
||||
`buildStringCommandShellInvocation` argv.
|
||||
|
||||
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
|
||||
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
|
||||
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
|
||||
@@ -586,6 +640,10 @@ persistence. Re-read credentials and provider-owned configuration on `session.op
|
||||
daemon launch from `connect` and the per-session env and MCP servers from `session.open`. There is
|
||||
no provider reload input.
|
||||
|
||||
Declare `ProviderRegistration.launchWrap: true` when every session spawns its own harness and can
|
||||
run it as `[...config.wrap, command, ...args]`; offer `session.launch_wrap` on the connection. See
|
||||
[Launch wrap](#launch-wrap). `runAcpProvider({ command })` does both.
|
||||
|
||||
For an ACP command, register `runAcpProvider({ id, label, command })` from
|
||||
`@getpaseo/plugin/server/acp`. The shim builds the standard row for each ACP tool `kind`
|
||||
(`acp-internal/tool-call-detail.ts`). Its transformer hooks cover narrow vendor differences; do not translate the
|
||||
|
||||
@@ -58,6 +58,11 @@
|
||||
"types": "./dist/server/lifecycle.d.ts",
|
||||
"source": "./src/server/lifecycle.ts",
|
||||
"default": "./dist/server/lifecycle.js"
|
||||
},
|
||||
"./internal/windows-command": {
|
||||
"types": "./dist/server/process-internal/windows-command.d.ts",
|
||||
"source": "./src/server/process-internal/windows-command.ts",
|
||||
"default": "./dist/server/process-internal/windows-command.js"
|
||||
}
|
||||
},
|
||||
"publishConfig": {
|
||||
|
||||
@@ -14,6 +14,7 @@ const entries = {
|
||||
"./server/usage": "server",
|
||||
"./server/acp": "server",
|
||||
"./internal/lifecycle": "server",
|
||||
"./internal/windows-command": "server",
|
||||
"./client": "client",
|
||||
"./client/host": "client",
|
||||
"./client/ui": "client",
|
||||
@@ -392,7 +393,7 @@ describe("lifecycle hook SDK types", () => {
|
||||
it("infers payloads and replacement requests and requires async handlers and new names", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult } from "@getpaseo/plugin/server";
|
||||
import type { PluginServerContext, PluginHooks, PluginHookPayload, PluginHookResult, PluginLaunchWrap } from "@getpaseo/plugin/server";
|
||||
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
server.addHook("worktree.create.before", async ({ request }) => {
|
||||
@@ -427,6 +428,38 @@ describe("lifecycle hook SDK types", () => {
|
||||
const { metadata, ...withoutMetadata } = request;
|
||||
return withoutMetadata;
|
||||
});
|
||||
server.addHook("agent.create.before", async ({ request }) => {
|
||||
const workspace: string | null = request.workspaceId;
|
||||
// @ts-expect-error The agent's workspace is read-only.
|
||||
request.workspaceId = "wks_other";
|
||||
});
|
||||
// Results built before workspaceId existed still typecheck; the daemon keeps the id.
|
||||
server.addHook("agent.create.before", async ({ request }) => ({ config: request.config, env: request.env }));
|
||||
server.before("agent.create", ({ request }) => ({ config: request.config, env: request.env }));
|
||||
server.addHook("terminal.create.before", async ({ request }) => {
|
||||
const source: "client" | "agent" | "script" | "worktree" = request.source;
|
||||
const input: string | null = request.input;
|
||||
const program: string | null = request.command;
|
||||
// @ts-expect-error The terminal's workspace is read-only.
|
||||
request.workspaceId = "wks_other";
|
||||
// @ts-expect-error The terminal's program is read-only; return a wrap instead.
|
||||
request.command = "/usr/bin/other";
|
||||
const wrap: PluginLaunchWrap = ["/usr/bin/sandbox", "--workspace", request.workspaceId];
|
||||
return { ...request, env: { A: "1" }, wrap };
|
||||
});
|
||||
server.addHook("command.run.before", async ({ request }) => {
|
||||
const workspace: string | null = request.workspaceId;
|
||||
const purpose: "setup" | "teardown" = request.purpose;
|
||||
// @ts-expect-error A command's purpose is read-only.
|
||||
request.purpose = "setup";
|
||||
// @ts-expect-error The configured command is read-only; return a wrap instead.
|
||||
request.command = "wrapper " + request.command;
|
||||
return { ...request, wrap: ["/usr/bin/sandbox"] };
|
||||
});
|
||||
server.addHook("agent.open.before", async ({ request }) => ({
|
||||
...request,
|
||||
wrap: ["/usr/bin/sandbox", "--workspace", request.workspaceId ?? "none"],
|
||||
}));
|
||||
server.addHook("agent.turn.after", async (event, { paseo, signal }) => {
|
||||
const { agent, outcome } = event;
|
||||
const kind: "completed" | "failed" | "canceled" = outcome.kind;
|
||||
|
||||
@@ -86,6 +86,8 @@ export async function createAcpProviderConnection(
|
||||
emit: () => undefined,
|
||||
});
|
||||
const supportedCapabilities: ProviderCapability[] = [...ADAPTER_CAPABILITIES];
|
||||
// A connector stream has no process of its own to wrap.
|
||||
if (options.command) supportedCapabilities.push("session.launch_wrap");
|
||||
if (probe.agentCapabilities.promptCapabilities?.image) {
|
||||
supportedCapabilities.push("prompt.image");
|
||||
}
|
||||
@@ -333,6 +335,7 @@ async function openSession(
|
||||
boundarySessionId: input.sessionId,
|
||||
cwd: input.config.cwd,
|
||||
env: input.config.env,
|
||||
wrap: input.config.wrap,
|
||||
emit: state.emit,
|
||||
onRetired: () => retireSession(state, input.sessionId),
|
||||
});
|
||||
@@ -375,6 +378,7 @@ interface StartRuntimeOptions {
|
||||
boundarySessionId: string;
|
||||
cwd?: string;
|
||||
env: Readonly<Record<string, string>>;
|
||||
wrap?: readonly [string, ...string[]];
|
||||
emit(event: ProviderEvent): void;
|
||||
onRetired?: () => void;
|
||||
}
|
||||
@@ -498,6 +502,7 @@ class AcpRuntime {
|
||||
env: process.env,
|
||||
};
|
||||
child = spawnProcess(launch.command, launch.args, {
|
||||
wrap: options.wrap,
|
||||
cwd: options.cwd,
|
||||
env: { ...launch.env, ...options.env },
|
||||
stdio: "pipe",
|
||||
@@ -511,6 +516,7 @@ class AcpRuntime {
|
||||
>[1];
|
||||
stream = ndJsonStream(output, input);
|
||||
} else {
|
||||
if (options.wrap) throw new Error("An ACP connector cannot run behind a launch wrap");
|
||||
const owned = ownConnectorStream(await options.options.connector());
|
||||
stream = owned.stream;
|
||||
closeConnector = owned.close;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import diagnosticsChannel from "node:diagnostics_channel";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -6166,7 +6168,6 @@ describe("deferTurnOnRunningTools", () => {
|
||||
);
|
||||
|
||||
const childPid = Number((await readFile(pidFile, "utf8")).trim());
|
||||
const startedAt = Date.now();
|
||||
await Promise.all([
|
||||
connection.send({
|
||||
type: "session.interrupt",
|
||||
@@ -6188,8 +6189,8 @@ describe("deferTurnOnRunningTools", () => {
|
||||
(event) => event.type === "request.completed" && event.requestId === "int-2",
|
||||
);
|
||||
|
||||
// Both interrupts waited for the 250ms SIGTERM exit, and process is now dead.
|
||||
expect(Date.now() - startedAt).toBeGreaterThanOrEqual(200);
|
||||
// Both interrupts waited for the process to exit. On POSIX it lives 250ms past SIGTERM, so an
|
||||
// interrupt that returned early would find it alive; Windows ends it at once.
|
||||
expect(() => process.kill(childPid, 0)).toThrow();
|
||||
|
||||
// Canceled turn and session.closed were each emitted exactly once.
|
||||
@@ -7125,3 +7126,187 @@ describe("ACP tool call rows", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("runAcpProvider launch wrap", () => {
|
||||
async function wrapFixture(): Promise<{
|
||||
agent: string;
|
||||
launchLog: string;
|
||||
/** The wrap that runs the recording launcher as Node, tagged so the agent can tell. */
|
||||
wrap: (tag: string) => [string, ...string[]];
|
||||
launches: () => Promise<Array<{ argv: string[]; token: string | null }>>;
|
||||
agentStarts: () => Promise<string[]>;
|
||||
}> {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-acp-wrap-"));
|
||||
temporaryDirectories.push(directory);
|
||||
const launchLog = path.join(directory, "launches.jsonl");
|
||||
const agentLog = path.join(directory, "agent.log");
|
||||
const launcher = path.join(directory, "launcher.cjs");
|
||||
// Consumes two arguments of its own (log path, tag), records what it saw, then runs the rest.
|
||||
await writeFile(
|
||||
launcher,
|
||||
`const { appendFileSync } = require("node:fs");
|
||||
const { spawn } = require("node:child_process");
|
||||
const [log, tag, command, ...args] = process.argv.slice(2);
|
||||
appendFileSync(log, JSON.stringify({ argv: process.argv.slice(2), token: process.env.SESSION_TOKEN ?? null }) + "\\n");
|
||||
const child = spawn(command, args, { stdio: "inherit", env: { ...process.env, WRAPPED_BY: tag } });
|
||||
process.on("SIGTERM", () => child.kill("SIGTERM"));
|
||||
child.on("exit", (code) => process.exit(code ?? 1));
|
||||
`,
|
||||
"utf8",
|
||||
);
|
||||
const agent = path.join(directory, "agent.cjs");
|
||||
await writeFile(
|
||||
agent,
|
||||
`const { appendFileSync } = require("node:fs");
|
||||
const record = (event) => appendFileSync(${JSON.stringify(agentLog)}, event + ":" + (process.env.WRAPPED_BY ?? "bare") + "\\n");
|
||||
const readline = require("node:readline");
|
||||
const lines = readline.createInterface({ input: process.stdin });
|
||||
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
|
||||
lines.on("line", (line) => {
|
||||
const message = JSON.parse(line);
|
||||
if (message.method === "initialize") { record("init"); send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: message.params.protocolVersion, agentCapabilities: {} } }); }
|
||||
else if (message.method === "session/new") { record("new"); send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "native-" + Math.random(), modes: null, configOptions: [] } }); }
|
||||
});`,
|
||||
"utf8",
|
||||
);
|
||||
const readLines = async (file: string) =>
|
||||
(await readFile(file, "utf8").catch(() => "")).split("\n").filter(Boolean);
|
||||
return {
|
||||
agent,
|
||||
launchLog,
|
||||
wrap: (tag) => [process.execPath, launcher, launchLog, tag],
|
||||
launches: async () => (await readLines(launchLog)).map((line) => JSON.parse(line)),
|
||||
agentStarts: async () => await readLines(agentLog),
|
||||
};
|
||||
}
|
||||
|
||||
function wrappedOpen(
|
||||
sessionId: string,
|
||||
wrap: readonly [string, ...string[]] | undefined,
|
||||
): Extract<ProviderInput, { type: "session.open" }> {
|
||||
const input = openInput();
|
||||
return {
|
||||
...input,
|
||||
requestId: `open-${sessionId}`,
|
||||
sessionId,
|
||||
config: { ...input.config, env: { SESSION_TOKEN: sessionId }, ...(wrap ? { wrap } : {}) },
|
||||
};
|
||||
}
|
||||
|
||||
async function connectWrapped(command: readonly [string, ...string[]]) {
|
||||
const registration = runAcpProvider({ id: "wrap-acp", label: "Wrap ACP", command });
|
||||
expect(registration.launchWrap).toBe(true);
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message", "session.launch_wrap"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
return { connection, events };
|
||||
}
|
||||
|
||||
it("spawns the session as [...wrap, command, ...args] with the session env", async () => {
|
||||
const fixture = await wrapFixture();
|
||||
const { launchLog } = fixture;
|
||||
const { connection, events } = await connectWrapped([process.execPath, fixture.agent]);
|
||||
expect(connection.capabilities).toContain("session.launch_wrap");
|
||||
try {
|
||||
await connection.send(wrappedOpen("one", fixture.wrap("sandbox")));
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
expect(await fixture.launches()).toEqual([
|
||||
{ argv: [launchLog, "sandbox", process.execPath, fixture.agent], token: "one" },
|
||||
]);
|
||||
expect(await fixture.agentStarts()).toEqual(["init:bare", "init:sandbox", "new:sandbox"]);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("passes wrap and command arguments that contain spaces as single argv elements", async () => {
|
||||
const fixture = await wrapFixture();
|
||||
const { launchLog } = fixture;
|
||||
const { connection, events } = await connectWrapped([
|
||||
process.execPath,
|
||||
fixture.agent,
|
||||
"--profile name with spaces",
|
||||
]);
|
||||
try {
|
||||
await connection.send(wrappedOpen("one", fixture.wrap("tag with spaces")));
|
||||
await waitForEvent(events, (event) => event.type === "session.ready");
|
||||
expect((await fixture.launches())[0]?.argv).toEqual([
|
||||
launchLog,
|
||||
"tag with spaces",
|
||||
process.execPath,
|
||||
fixture.agent,
|
||||
"--profile name with spaces",
|
||||
]);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("wraps only the session that selected a wrap on a shared connection", async () => {
|
||||
const fixture = await wrapFixture();
|
||||
const { launchLog } = fixture;
|
||||
const { connection, events } = await connectWrapped([process.execPath, fixture.agent]);
|
||||
try {
|
||||
await connection.send(wrappedOpen("wrapped", fixture.wrap("sandbox")));
|
||||
await connection.send(wrappedOpen("bare", undefined));
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.ready" && event.sessionId === "wrapped",
|
||||
);
|
||||
await waitForEvent(
|
||||
events,
|
||||
(event) => event.type === "session.ready" && event.sessionId === "bare",
|
||||
);
|
||||
expect(await fixture.launches()).toEqual([
|
||||
{ argv: [launchLog, "sandbox", process.execPath, fixture.agent], token: "wrapped" },
|
||||
]);
|
||||
expect(
|
||||
(await fixture.agentStarts()).filter((line) => line.startsWith("new:")).sort(),
|
||||
).toEqual(["new:bare", "new:sandbox"]);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("fails the open when the launcher is missing and never starts the bare command", async () => {
|
||||
const fixture = await wrapFixture();
|
||||
const missing = path.join(path.dirname(fixture.agent), "missing-launcher");
|
||||
const { connection, events } = await connectWrapped([process.execPath, fixture.agent]);
|
||||
// Node publishes every spawn attempt, a failed one included, before it fills in the fields.
|
||||
const spawned: ChildProcess[] = [];
|
||||
const onSpawn = (message: unknown) =>
|
||||
spawned.push((message as { process: ChildProcess }).process);
|
||||
diagnosticsChannel.subscribe("child_process", onSpawn);
|
||||
try {
|
||||
await connection.send(wrappedOpen("one", [missing, "--profile", "a b"]));
|
||||
expect(await waitForEvent(events, (event) => event.type === "request.failed")).toMatchObject({
|
||||
requestId: "open-one",
|
||||
error: { message: expect.stringMatching(/ENOENT/u) },
|
||||
});
|
||||
expect(spawned.map((child) => child.spawnargs)).toEqual([
|
||||
[missing, "--profile", "a b", process.execPath, fixture.agent],
|
||||
]);
|
||||
// The only start of the agent is the connection's capability probe, before the open.
|
||||
expect(await fixture.agentStarts()).toEqual(["init:bare"]);
|
||||
expect(events.some((event) => event.type === "session.opened")).toBe(false);
|
||||
} finally {
|
||||
diagnosticsChannel.unsubscribe("child_process", onSpawn);
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not offer launch wrap through a connector", async () => {
|
||||
const { connector } = connectorHarness();
|
||||
const registration = runAcpProvider({ id: "connector-acp", label: "Connector", connector });
|
||||
expect(registration).not.toHaveProperty("launchWrap");
|
||||
const connection = await registration.connect({
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message", "session.launch_wrap"],
|
||||
});
|
||||
expect(connection.capabilities).not.toContain("session.launch_wrap");
|
||||
await connection.close();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -181,6 +181,8 @@ export function runAcpProvider(options: RunAcpProviderOptions): ProviderRegistra
|
||||
description: options.description,
|
||||
icon: options.icon,
|
||||
command: options.command,
|
||||
// Each command-based session spawns its own process, so it can run behind that session's wrap.
|
||||
...(hasCommand ? { launchWrap: true } : {}),
|
||||
connect(request) {
|
||||
return createAcpProviderConnection(options, request);
|
||||
},
|
||||
|
||||
@@ -23,6 +23,9 @@ export type {
|
||||
PluginHookWorkspace,
|
||||
PluginHookWorktree,
|
||||
PluginWorktreeCreateRequest,
|
||||
PluginLaunchWrap,
|
||||
PluginTerminalCreateRequest,
|
||||
PluginCommandRunRequest,
|
||||
PluginHookAgent,
|
||||
PluginSessionOpenRequest,
|
||||
PluginTurnOutcome,
|
||||
@@ -32,6 +35,7 @@ export type {
|
||||
} from "./lifecycle.js";
|
||||
|
||||
export { spawnProcess, execCommand, terminateProcess } from "./process.js";
|
||||
export type { SpawnProcessOptions } from "./process.js";
|
||||
|
||||
export { defineAgentTool } from "./agent-tools.js";
|
||||
export type { AgentToolDefinition, AgentToolResult, AgentToolContext } from "./agent-tools.js";
|
||||
|
||||
@@ -68,6 +68,49 @@ export type PluginWorktreeCreateRequest = {
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* A launcher Paseo starts a process behind: the process runs as `[...wrap, command, ...args]`.
|
||||
* The executable is an absolute path on the daemon host. Each element is one argument; no shell
|
||||
* parses them, except that Windows runs a `.cmd` or `.bat` executable through cmd.exe. A later
|
||||
* hook may omit the wrap or return the same one; a different wrap fails the operation.
|
||||
*/
|
||||
export type PluginLaunchWrap = readonly [executable: string, ...args: string[]];
|
||||
|
||||
/** A terminal Paseo is about to create in a workspace. */
|
||||
export interface PluginTerminalCreateRequest {
|
||||
readonly workspaceId: string;
|
||||
readonly cwd: string;
|
||||
/**
|
||||
* `agent`: an agent's Paseo tool. `script`: a `paseo.json` script or service. `worktree`: a
|
||||
* `paseo.json` worktree terminal. `client`: everything else (the app, CLI, SDK, plugins).
|
||||
*/
|
||||
readonly source: "client" | "agent" | "script" | "worktree";
|
||||
readonly name: string | null;
|
||||
/** The program the terminal starts, or `null` for the user's default shell. */
|
||||
readonly command: string | null;
|
||||
readonly args: readonly string[];
|
||||
/** What Paseo types into the shell once it starts: the command of a script or worktree terminal. */
|
||||
readonly input: string | null;
|
||||
/** Environment overrides for the terminal; excludes the daemon's inherited environment. */
|
||||
env: Record<string, string>;
|
||||
/** Start the terminal as `[...wrap, command, ...args]`; with no `command`, the default shell. */
|
||||
wrap?: PluginLaunchWrap;
|
||||
}
|
||||
|
||||
/** A `paseo.json` worktree setup or teardown command Paseo is about to run. */
|
||||
export interface PluginCommandRunRequest {
|
||||
/** Null when a worktree is archived by path and no workspace record remains. */
|
||||
readonly workspaceId: string | null;
|
||||
readonly cwd: string;
|
||||
readonly purpose: "setup" | "teardown";
|
||||
/** The command as written in `paseo.json`. Paseo runs it through a shell. */
|
||||
readonly command: string;
|
||||
/** Environment overrides for the command; excludes the daemon's inherited environment. */
|
||||
env: Record<string, string>;
|
||||
/** Start the command's shell as `[...wrap, shell, ...shellArgs]`. */
|
||||
wrap?: PluginLaunchWrap;
|
||||
}
|
||||
|
||||
export interface PluginHookAgent {
|
||||
id: string;
|
||||
workspaceId: string | null;
|
||||
@@ -98,6 +141,12 @@ export interface PluginSessionOpenRequest {
|
||||
tools: AgentToolDefinition[];
|
||||
env: Record<string, string>;
|
||||
mcpServers: NonNullable<AgentSessionConfig["mcpServers"]>;
|
||||
/**
|
||||
* Start the provider's harness as `[...wrap, command, ...args]`. Only a provider whose snapshot
|
||||
* entry has `launchWrap: true` applies it; any other provider fails the open. Not saved on the
|
||||
* agent.
|
||||
*/
|
||||
wrap?: PluginLaunchWrap;
|
||||
}
|
||||
|
||||
export type PluginTurnOutcome =
|
||||
@@ -138,18 +187,28 @@ export interface PluginHookRequests {
|
||||
env?: Record<string, string>;
|
||||
/** Stored on the new agent. Always present in the payload; return it changed to change it. */
|
||||
metadata?: Record<string, JsonValue>;
|
||||
/** The workspace the agent is created in, which `config.cwd` alone does not identify. */
|
||||
readonly workspaceId: string | null;
|
||||
};
|
||||
"agent.open.before": PluginSessionOpenRequest;
|
||||
"workspace.create.before": Omit<WorkspaceCreateRequest, "type" | "requestId">;
|
||||
"terminal.create.before": PluginTerminalCreateRequest;
|
||||
"command.run.before": PluginCommandRunRequest;
|
||||
}
|
||||
|
||||
/** What a hook may return. An omitted `metadata` stays as it was. */
|
||||
type PluginHookRequestResults = Omit<PluginHookRequests, "agent.open.before"> & {
|
||||
/** What a hook may return. An omitted `metadata` or `workspaceId` stays as it was. */
|
||||
type PluginHookRequestResults = Omit<
|
||||
PluginHookRequests,
|
||||
"agent.open.before" | "agent.create.before"
|
||||
> & {
|
||||
// Read-only fields added after the first SDK stay optional in a result; omitted means unchanged.
|
||||
"agent.open.before": Omit<PluginSessionOpenRequest, "metadata" | "background"> & {
|
||||
readonly background?: boolean;
|
||||
metadata?: Readonly<Record<string, JsonValue>>;
|
||||
};
|
||||
"agent.create.before": Omit<PluginHookRequests["agent.create.before"], "workspaceId"> & {
|
||||
readonly workspaceId?: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
export type PluginHooks = {
|
||||
@@ -217,6 +276,8 @@ export const pluginHookRegistry = {
|
||||
"agent.turn.after": { waits: false },
|
||||
"agent.permission.before": { waits: false },
|
||||
"agent.permission.after": { waits: false },
|
||||
"terminal.create.before": { waits: true },
|
||||
"command.run.before": { waits: true },
|
||||
} as const satisfies Record<keyof PluginHooks, { waits: boolean }>;
|
||||
|
||||
// COMPAT(pluginHookNames): added in v0.14, remove after 2027-04-30
|
||||
|
||||
@@ -1,117 +1,92 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { quoteWindowsArgument, quoteWindowsCommand } from "./windows-command.js";
|
||||
import { findWindowsCommand, quoteWindowsCommand, windowsCommandLine } from "./windows-command.js";
|
||||
|
||||
const program = { commandScript: false } as const;
|
||||
const script = { commandScript: true } as const;
|
||||
|
||||
describe("quoteWindowsCommand", () => {
|
||||
const originalPlatform = process.platform;
|
||||
|
||||
function setPlatform(value: string) {
|
||||
Object.defineProperty(process, "platform", { value, writable: true });
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setPlatform(originalPlatform);
|
||||
});
|
||||
|
||||
test("quotes a Windows path with spaces", () => {
|
||||
setPlatform("win32");
|
||||
test("quotes a path with spaces and keeps cmd.exe syntax in it as text", () => {
|
||||
expect(quoteWindowsCommand("C:\\Program Files\\Anthropic\\claude.exe")).toBe(
|
||||
'"C:\\Program Files\\Anthropic\\claude.exe"',
|
||||
);
|
||||
});
|
||||
|
||||
test("does not double-quote an already-quoted path", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand('"C:\\Program Files\\Anthropic\\claude.exe"')).toBe(
|
||||
'"C:\\Program Files\\Anthropic\\claude.exe"',
|
||||
expect(quoteWindowsCommand("C:\\Program Files (x86)\\Tool & Co\\run.cmd")).toBe(
|
||||
'"C:\\Program Files (x86)\\Tool & Co\\run.cmd"',
|
||||
);
|
||||
});
|
||||
|
||||
test("returns the command unchanged when there are no spaces", () => {
|
||||
setPlatform("win32");
|
||||
test("leaves a plain or already quoted path as given", () => {
|
||||
expect(quoteWindowsCommand("C:\\nvm4w\\nodejs\\codex")).toBe("C:\\nvm4w\\nodejs\\codex");
|
||||
});
|
||||
|
||||
test("escapes ampersands", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("feature&bugfix")).toBe("feature^&bugfix");
|
||||
});
|
||||
|
||||
test("escapes pipes", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("feature|bugfix")).toBe("feature^|bugfix");
|
||||
});
|
||||
|
||||
test("does not double percent signs", () => {
|
||||
setPlatform("win32");
|
||||
// cmd.exe only collapses %% → % inside batch files; on the command line
|
||||
// it stays literal, which corrupts git --format atoms etc.
|
||||
expect(quoteWindowsCommand("100%")).toBe("100%");
|
||||
});
|
||||
|
||||
test("preserves git --format atoms verbatim", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("--format=%(refname)%09%(committerdate:unix)")).toBe(
|
||||
"--format=%^(refname^)%09%^(committerdate:unix^)",
|
||||
);
|
||||
});
|
||||
|
||||
test("escapes carets", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("feature^bugfix")).toBe("feature^^bugfix");
|
||||
});
|
||||
|
||||
test("escapes multiple metacharacters", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("build&(test|deploy)!<output>")).toBe(
|
||||
"build^&^(test^|deploy^)^!^<output^>",
|
||||
);
|
||||
});
|
||||
|
||||
test("quotes commands with spaces after escaping metacharacters", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsCommand("C:\\Program Files\\My Tool&Stuff\\run 100%.cmd")).toBe(
|
||||
'"C:\\Program Files\\My Tool^&Stuff\\run 100%.cmd"',
|
||||
);
|
||||
});
|
||||
|
||||
test("returns the command unchanged on non-Windows platforms", () => {
|
||||
setPlatform("darwin");
|
||||
expect(quoteWindowsCommand("/usr/local/bin/claude code")).toBe("/usr/local/bin/claude code");
|
||||
expect(quoteWindowsCommand('"C:\\Program Files\\x.exe"')).toBe('"C:\\Program Files\\x.exe"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("quoteWindowsArgument", () => {
|
||||
const originalPlatform = process.platform;
|
||||
|
||||
function setPlatform(value: string) {
|
||||
Object.defineProperty(process, "platform", { value, writable: true });
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setPlatform(originalPlatform);
|
||||
});
|
||||
|
||||
test("quotes a Windows argument with spaces", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsArgument("C:\\Program Files\\Anthropic\\cli.js")).toBe(
|
||||
'"C:\\Program Files\\Anthropic\\cli.js"',
|
||||
describe("windowsCommandLine", () => {
|
||||
test("passes an argument without a cmd.exe metacharacter as given", () => {
|
||||
expect(windowsCommandLine("echo", ["hello", "--flag", "feature/x", "C:\\dir"], program)).toBe(
|
||||
'"echo hello --flag feature/x C:\\dir"',
|
||||
);
|
||||
});
|
||||
|
||||
test("does not double-quote an already-quoted argument", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsArgument('"C:\\Program Files\\Anthropic\\cli.js"')).toBe(
|
||||
'"C:\\Program Files\\Anthropic\\cli.js"',
|
||||
test("quotes and caret-escapes every other argument once, the qntm way", () => {
|
||||
expect(windowsCommandLine("node", ["feature&bugfix", "work profile", ""], program)).toBe(
|
||||
'"node ^"feature^&bugfix^" ^"work^ profile^" ^"^""',
|
||||
);
|
||||
// A caret before each `%` keeps cmd.exe from reading a variable name, inside the quotes too.
|
||||
expect(windowsCommandLine("node", ["%PATH%", "100% of %PATH%"], program)).toBe(
|
||||
'"node ^"^%PATH^%^" ^"100^%^ of^ ^%PATH^%^""',
|
||||
);
|
||||
// Backslashes before the closing quote double, as the program's argv parser expects.
|
||||
expect(windowsCommandLine("node", ["C:\\path with space\\"], program)).toBe(
|
||||
'"node ^"C:\\path^ with^ space\\\\^""',
|
||||
);
|
||||
});
|
||||
|
||||
test("returns the argument unchanged when there are no spaces", () => {
|
||||
setPlatform("win32");
|
||||
expect(quoteWindowsArgument("--version")).toBe("--version");
|
||||
test("quotes =, comma and semicolon, where a batch script splits its arguments", () => {
|
||||
expect(windowsCommandLine("run.cmd", ["--profile=restricted", "a,b;c"], script)).toBe(
|
||||
'"run.cmd ^"--profile=restricted^" ^"a^,b^;c^""',
|
||||
);
|
||||
});
|
||||
|
||||
test("returns the argument unchanged on non-Windows platforms", () => {
|
||||
setPlatform("darwin");
|
||||
expect(quoteWindowsArgument("/usr/local/bin/claude code")).toBe("/usr/local/bin/claude code");
|
||||
test("escapes an argument with a quote twice for a batch script, which reads it again", () => {
|
||||
expect(windowsCommandLine("node", ['say "hi"'], program)).toBe('"node ^"say^ \\^"hi\\^"^""');
|
||||
expect(windowsCommandLine("run.cmd", ['say "hi"', "a & b"], script)).toBe(
|
||||
'"run.cmd ^^^"say^^^ \\^^^"hi\\^^^"^^^" ^"a^ ^&^ b^""',
|
||||
);
|
||||
});
|
||||
|
||||
test("quotes the command path at the start of the line", () => {
|
||||
expect(windowsCommandLine("C:\\Program Files (x86)\\run.cmd", ["acp"], script)).toBe(
|
||||
'""C:\\Program Files (x86)\\run.cmd" acp"',
|
||||
);
|
||||
});
|
||||
|
||||
test("refuses a line break, which ends a cmd.exe command whatever the quoting", () => {
|
||||
for (const argument of ["line one\nline two", "line one\r\n& calc"]) {
|
||||
expect(() => windowsCommandLine("run.cmd", ["--", argument], script)).toThrow(
|
||||
"cmd.exe cannot pass an argument with a line break to run.cmd",
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("findWindowsCommand", () => {
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
test("finds a bare name on PATH with each PATHEXT extension, whatever the env key case", async () => {
|
||||
const empty = await mkdtemp(path.join(os.tmpdir(), "windows-command-empty-"));
|
||||
const tools = await mkdtemp(path.join(os.tmpdir(), "windows-command-tools-"));
|
||||
roots.push(empty, tools);
|
||||
await writeFile(path.join(tools, "agent.CMD"), "");
|
||||
const env = { Path: `${empty};${tools}`, PathExt: ".EXE;.CMD" };
|
||||
expect(findWindowsCommand("agent", env)).toBe(path.join(tools, "agent.CMD"));
|
||||
expect(findWindowsCommand("echo", env)).toBeUndefined();
|
||||
expect(findWindowsCommand("agent.cmd", env)).toBeUndefined();
|
||||
expect(findWindowsCommand(path.join(tools, "agent"), env)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,46 +1,100 @@
|
||||
import { extname } from "node:path";
|
||||
import { statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
export function isWindowsCommandScript(executablePath: string): boolean {
|
||||
/**
|
||||
* How Paseo starts a program through cmd.exe on Windows: `cmd.exe /d /s /c "<line>"`, with the line
|
||||
* passed verbatim. The SDK process functions and the daemon's terminals share this one dialect.
|
||||
*/
|
||||
|
||||
export function isWindowsCommandScript(
|
||||
executablePath: string,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): boolean {
|
||||
const extension = extname(executablePath).toLowerCase();
|
||||
return process.platform === "win32" && (extension === ".cmd" || extension === ".bat");
|
||||
}
|
||||
|
||||
function escapeWindowsCmdValue(value: string): string {
|
||||
if (process.platform !== "win32") return value;
|
||||
|
||||
const isQuoted = value.startsWith('"') && value.endsWith('"');
|
||||
const unquoted = isQuoted ? value.slice(1, -1) : value;
|
||||
// Do NOT double `%` here. cmd.exe only collapses `%%` → `%` inside batch
|
||||
// files; on the command line / `cmd /c "..."` `%%` stays literal, which
|
||||
// breaks args like git's `--format=%(refname)` (git treats `%%` as the
|
||||
// escape for a literal `%`, so the format atoms become literals).
|
||||
const escaped = unquoted.replace(/([&|^<>()!])/g, "^$1");
|
||||
|
||||
if (isQuoted || /[\s"]/u.test(unquoted)) {
|
||||
const quoted = escaped
|
||||
.replace(/(\\*)"/g, (_match, slashes: string) => `${slashes}${slashes}\\"`)
|
||||
.replace(/\\+$/u, (slashes) => `${slashes}${slashes}`);
|
||||
return `"${quoted}"`;
|
||||
}
|
||||
|
||||
return escaped;
|
||||
return platform === "win32" && (extension === ".cmd" || extension === ".bat");
|
||||
}
|
||||
|
||||
/**
|
||||
* When spawning with `shell: true` on Windows, the command is passed to
|
||||
* `cmd.exe /d /s /c "command args"`. The `/s` strips outer quotes, so a
|
||||
* command path with spaces (e.g. `C:\Program Files\...`) is split at the
|
||||
* space. Wrapping it in quotes produces the correct `"C:\Program Files\..." args`.
|
||||
* Find a bare command name the way cmd.exe would on `PATH`, trying each `PATHEXT` extension. The
|
||||
* current directory is not searched. Returns undefined for a name with a path or an extension, and
|
||||
* for a name that is not on `PATH`, such as a cmd.exe builtin.
|
||||
*/
|
||||
export function findWindowsCommand(name: string, env: NodeJS.ProcessEnv): string | undefined {
|
||||
if (name.includes("/") || name.includes("\\") || extname(name)) return undefined;
|
||||
const extensions = (readEnv(env, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
|
||||
for (const directory of (readEnv(env, "PATH") ?? "").split(";").filter(Boolean)) {
|
||||
for (const extension of extensions) {
|
||||
const candidate = join(directory, name + extension);
|
||||
if (statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The cmd.exe that runs a command line: the child's `ComSpec`, else the daemon's. */
|
||||
export function windowsCommandShell(env: NodeJS.ProcessEnv): string {
|
||||
return readEnv(env, "ComSpec") ?? readEnv(process.env, "ComSpec") ?? "cmd.exe";
|
||||
}
|
||||
|
||||
// Windows environment names ignore case, and a copied env object keeps whatever case it had.
|
||||
function readEnv(env: NodeJS.ProcessEnv, name: string): string | undefined {
|
||||
const key = Object.keys(env).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
|
||||
return key === undefined ? undefined : env[key] || undefined;
|
||||
}
|
||||
|
||||
// The cmd.exe metacharacters, as cross-spawn's `lib/util/escape.js` lists them.
|
||||
const CMD_METACHARACTERS = /([()\][%!^"`<>&|;, *?])/g;
|
||||
// A batch script also splits its arguments at `=` and tab.
|
||||
const NEEDS_ESCAPE = /[()\][%!^"`<>&|;, *?=\t]/u;
|
||||
|
||||
/**
|
||||
* Escape one argument for a `cmd.exe /c` line by the qntm algorithm (https://qntm.org/cmd), the
|
||||
* one cross-spawn's `lib/util/escape.js` implements: quote it for the program's own argv parser,
|
||||
* then put a `^` before every cmd.exe metacharacter, the added quotes included. cmd.exe then sees
|
||||
* no quoted region, so a `%NAME%` never expands, and the program gets the argument unchanged.
|
||||
* `twice` escapes again for a batch script that reads the argument a second time.
|
||||
*/
|
||||
function escapeCmdArgument(argument: string, twice: boolean): string {
|
||||
const quoted = `"${argument.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1")}"`;
|
||||
const escaped = quoted.replace(CMD_METACHARACTERS, "^$1");
|
||||
return twice ? escaped.replace(CMD_METACHARACTERS, "^$1") : escaped;
|
||||
}
|
||||
|
||||
/**
|
||||
* Quote the program path for the start of a cmd.exe line. Inside the quotes cmd.exe reads `&`, `(`
|
||||
* and `)` as text, so a path such as `C:\Program Files (x86)\...` starts.
|
||||
*/
|
||||
export function quoteWindowsCommand(command: string): string {
|
||||
return escapeWindowsCmdValue(command);
|
||||
if (command.startsWith('"') && command.endsWith('"')) return command;
|
||||
if (command === "" || /[\s()!^"<>&|%;,=]/u.test(command)) return `"${command}"`;
|
||||
return command;
|
||||
}
|
||||
|
||||
/**
|
||||
* `spawn(..., { shell: true })` on Windows also passes argv through `cmd.exe`.
|
||||
* Any argument containing spaces must be quoted or it will be split before the
|
||||
* child process sees it.
|
||||
* The quoted line for `cmd.exe /d /s /c <line>` that starts `command` with `args`.
|
||||
*
|
||||
* - An argument without a metacharacter needs no escape and stays as given, so cmd.exe builtins
|
||||
* and batch scripts that read `%1` get it unchanged.
|
||||
* - Any other argument is escaped once. A batch script that reads it as `%~1` gets it without the
|
||||
* quotes, and one that forwards it with `%*` hands the program the quoted argument, where cmd.exe
|
||||
* reads every metacharacter as text.
|
||||
* - For a batch script (`commandScript`), an argument with a `"` is escaped twice. Its quotes
|
||||
* would otherwise open and close regions when the script reads it again, and leave the
|
||||
* arguments after it outside the quotes.
|
||||
*
|
||||
* cmd.exe ends a command at a line break whatever the quoting, so an argument with one throws.
|
||||
*/
|
||||
export function quoteWindowsArgument(argument: string): string {
|
||||
return escapeWindowsCmdValue(argument);
|
||||
export function windowsCommandLine(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
{ commandScript }: { commandScript: boolean },
|
||||
): string {
|
||||
const escaped = args.map((argument) => {
|
||||
if (/[\r\n]/u.test(argument)) {
|
||||
throw new Error(`cmd.exe cannot pass an argument with a line break to ${command}`);
|
||||
}
|
||||
if (argument !== "" && !NEEDS_ESCAPE.test(argument)) return argument;
|
||||
return escapeCmdArgument(argument, commandScript && argument.includes('"'));
|
||||
});
|
||||
return `"${[quoteWindowsCommand(command), ...escaped].join(" ")}"`;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { execCommand, spawnProcess } from "./index.js";
|
||||
import { resolveSpawnInvocation } from "./process.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
@@ -26,8 +27,8 @@ const argumentsToPreserve = [
|
||||
"feature^bugfix",
|
||||
];
|
||||
|
||||
// A bare extensionless command selects the Windows shell; an absolute node.exe path would
|
||||
// skip that path. The real child checks quoting through the public process capabilities.
|
||||
// A real child checks quoting through the public process capabilities. On Windows the bare name
|
||||
// resolves on PATH to node.exe, which starts directly.
|
||||
test("execCommand delivers shell arguments to the real child unchanged", async () => {
|
||||
const script = await writeArgumentReader();
|
||||
const { stdout } = await execCommand("node", [script, ...argumentsToPreserve]);
|
||||
@@ -51,3 +52,299 @@ test("spawnProcess delivers shell arguments to the real child unchanged", async
|
||||
});
|
||||
expect(JSON.parse(stdout)).toEqual(argumentsToPreserve);
|
||||
});
|
||||
|
||||
// A Windows environment with an empty PATH, so a bare name is never found on the test host.
|
||||
const windowsEnv = { ComSpec: "C:\\Windows\\System32\\cmd.exe", PATH: "" };
|
||||
|
||||
function onWindows(command: string, args: string[], shell?: boolean | string) {
|
||||
return resolveSpawnInvocation(command, args, shell, "win32", windowsEnv);
|
||||
}
|
||||
|
||||
// A launch wrap prepends a Windows script wrapper to the provider launch; spawnProcess starts it as
|
||||
// one verbatim cmd.exe line.
|
||||
test("a Windows script launch wrap starts as one verbatim cmd.exe line", () => {
|
||||
const wrapped = [
|
||||
"C:\\Program Files\\Sandbox\\run.cmd",
|
||||
"--profile",
|
||||
"work profile",
|
||||
"",
|
||||
"C:\\tools\\agy.cmd",
|
||||
"acp",
|
||||
];
|
||||
expect(onWindows(wrapped[0]!, wrapped.slice(1))).toEqual({
|
||||
command: "C:\\Windows\\System32\\cmd.exe",
|
||||
args: [
|
||||
"/d",
|
||||
"/s",
|
||||
"/c",
|
||||
'""C:\\Program Files\\Sandbox\\run.cmd" --profile ^"work^ profile^" ^"^" C:\\tools\\agy.cmd acp"',
|
||||
],
|
||||
shell: false,
|
||||
windowsVerbatimArguments: true,
|
||||
});
|
||||
expect(resolveSpawnInvocation(wrapped[0]!, wrapped.slice(1), undefined, "linux")).toEqual({
|
||||
command: wrapped[0],
|
||||
args: wrapped.slice(1),
|
||||
shell: false,
|
||||
});
|
||||
});
|
||||
|
||||
// cmd.exe ends a command at a line break, and the text after it would run as a second command.
|
||||
test("a Windows cmd.exe launch refuses an argument with a line break before it starts", () => {
|
||||
for (const argument of ["line one\nline two", "line one\r\n& calc"]) {
|
||||
expect(() => onWindows("C:\\Sandbox\\run.cmd", ["--", argument])).toThrow(
|
||||
"cmd.exe cannot pass an argument with a line break to C:\\Sandbox\\run.cmd",
|
||||
);
|
||||
expect(() => onWindows("codex", [argument])).toThrow(
|
||||
"cmd.exe cannot pass an argument with a line break to codex",
|
||||
);
|
||||
}
|
||||
expect(onWindows("C:\\tools\\node.exe", ["a\nb"]).args).toEqual(["a\nb"]);
|
||||
expect(resolveSpawnInvocation("/usr/bin/sandbox", ["a\nb"], undefined, "linux").args).toEqual([
|
||||
"a\nb",
|
||||
]);
|
||||
});
|
||||
|
||||
// Only cmd.exe reads cmd.exe quoting. A shell the caller names parses the line by its own rules.
|
||||
test("a Windows launch quotes for cmd.exe only when cmd.exe parses the command line", () => {
|
||||
// `shell: true` runs the child's ComSpec; a cmd.exe the caller names runs as named.
|
||||
for (const [shell, cmd] of [
|
||||
[true, windowsEnv.ComSpec],
|
||||
["cmd.exe", "cmd.exe"],
|
||||
["D:\\Tools\\CMD.EXE", "D:\\Tools\\CMD.EXE"],
|
||||
] as const) {
|
||||
expect(onWindows("echo", ["hello", "a & b"], shell)).toEqual({
|
||||
command: cmd,
|
||||
args: ["/d", "/s", "/c", '"echo hello ^"a^ ^&^ b^""'],
|
||||
shell: false,
|
||||
windowsVerbatimArguments: true,
|
||||
});
|
||||
}
|
||||
for (const shell of ["bash.exe", "C:\\Program Files\\Git\\bin\\bash.exe", "pwsh"]) {
|
||||
expect(onWindows("echo", ["'a & b'", "line\nbreak"], shell)).toEqual({
|
||||
command: "echo",
|
||||
args: ["'a & b'", "line\nbreak"],
|
||||
shell,
|
||||
});
|
||||
}
|
||||
// A program starts directly, and `shell: false` keeps a bare name that is not on PATH direct.
|
||||
expect(onWindows("C:\\tools\\node.exe", ["a & b"])).toEqual({
|
||||
command: "C:\\tools\\node.exe",
|
||||
args: ["a & b"],
|
||||
shell: false,
|
||||
});
|
||||
expect(onWindows("missing", ["a & b"], false)).toEqual({
|
||||
command: "missing",
|
||||
args: ["a & b"],
|
||||
shell: false,
|
||||
});
|
||||
});
|
||||
|
||||
// The daemon runs git with `shell: false` on hot paths that must not block on synchronous IO, so
|
||||
// an explicit `shell: false` starts a bare name directly and leaves the PATH search to Windows.
|
||||
test("a Windows bare name searches PATH for a script only when the caller allows a shell", async () => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin-path-shim-"));
|
||||
roots.push(directory);
|
||||
await writeFile(path.join(directory, "tool.CMD"), "");
|
||||
const env = { ...windowsEnv, PATH: directory };
|
||||
expect(resolveSpawnInvocation("tool", ["a & b"], false, "win32", env)).toEqual({
|
||||
command: "tool",
|
||||
args: ["a & b"],
|
||||
shell: false,
|
||||
});
|
||||
expect(resolveSpawnInvocation("tool", ["a & b"], undefined, "win32", env)).toEqual({
|
||||
command: windowsEnv.ComSpec,
|
||||
args: ["/d", "/s", "/c", `"${path.join(directory, "tool.CMD")} ^"a^ ^&^ b^""`],
|
||||
shell: false,
|
||||
windowsVerbatimArguments: true,
|
||||
});
|
||||
});
|
||||
|
||||
// Real Git Bash on Windows: the arguments reach Bash as given, without cmd.exe escapes.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"execCommand passes arguments as given to a Windows shell other than cmd.exe",
|
||||
async () => {
|
||||
const bash = path.join(
|
||||
process.env.ProgramFiles ?? "C:\\Program Files",
|
||||
"Git",
|
||||
"bin",
|
||||
"bash.exe",
|
||||
);
|
||||
const { stdout } = await execCommand("printf", ["'%s|'", "hello", "'a & b'"], {
|
||||
shell: bash,
|
||||
});
|
||||
expect(stdout).toBe("hello|a & b|");
|
||||
},
|
||||
);
|
||||
|
||||
// A launch wrap starts its executable with the command and its arguments after the wrap's own.
|
||||
// The caller's shell choice belongs to the unwrapped command, so a wrap ignores it.
|
||||
test("spawnProcess starts a wrap's executable with the command after the wrap arguments", async () => {
|
||||
const launcher = await writeArgumentReader();
|
||||
const child = spawnProcess("harness", ["--flag", ...argumentsToPreserve], {
|
||||
wrap: [process.execPath, launcher, "--sandbox profile"],
|
||||
shell: true,
|
||||
stdio: "pipe",
|
||||
});
|
||||
let stdout = "";
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk: string) => {
|
||||
stdout += chunk;
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("close", (code) => {
|
||||
if (code === 0) resolve();
|
||||
else reject(new Error(`Launcher exited with ${code}`));
|
||||
});
|
||||
});
|
||||
expect(JSON.parse(stdout)).toEqual([
|
||||
"--sandbox profile",
|
||||
"harness",
|
||||
"--flag",
|
||||
...argumentsToPreserve,
|
||||
]);
|
||||
});
|
||||
|
||||
// Arguments that cmd.exe reads as syntax unless they are escaped for it. A `.cmd` launcher reads
|
||||
// its arguments a second time when it forwards them with `%*`.
|
||||
const commandScriptArguments = [
|
||||
...argumentsToPreserve,
|
||||
'say "hi"',
|
||||
'"quoted"',
|
||||
"",
|
||||
"a & b",
|
||||
"(parenthesized) arg",
|
||||
"100% done",
|
||||
"%PATH%",
|
||||
"!bang!",
|
||||
"C:\\path with space\\",
|
||||
'mixed "a & b" quote',
|
||||
"--profile=restricted",
|
||||
"a,b;c",
|
||||
// cmd.exe expands a set variable inside a quoted region, so this checks that none opens.
|
||||
"value with %PATH% inside",
|
||||
'quote "then %PATH%" & more',
|
||||
];
|
||||
|
||||
async function writeCommandScriptLauncher(): Promise<string> {
|
||||
const reader = await writeArgumentReader();
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin wrap (x86) & launcher "));
|
||||
roots.push(directory);
|
||||
const launcher = path.join(directory, "sandbox run.cmd");
|
||||
await writeFile(launcher, `@"${process.execPath}" "${reader}" %*\r\n`);
|
||||
return launcher;
|
||||
}
|
||||
|
||||
async function readStdout(child: ReturnType<typeof spawnProcess>): Promise<string> {
|
||||
let stdout = "";
|
||||
child.stdout?.setEncoding("utf8");
|
||||
child.stdout?.on("data", (chunk: string) => {
|
||||
stdout += chunk;
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("close", (code) => {
|
||||
if (code === 0) resolve();
|
||||
else reject(new Error(`Child exited with ${code}`));
|
||||
});
|
||||
});
|
||||
return stdout;
|
||||
}
|
||||
|
||||
// Real cmd.exe: a `.cmd` launch wrap in a directory with spaces and cmd.exe syntax forwards the
|
||||
// harness command and every argument to the program it starts, unchanged.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"a .cmd launch wrap forwards the command and its arguments unchanged on Windows",
|
||||
async () => {
|
||||
const launcher = await writeCommandScriptLauncher();
|
||||
const child = spawnProcess("harness", commandScriptArguments, {
|
||||
wrap: [launcher, "--sandbox profile", 'say "hi"', ""],
|
||||
stdio: "pipe",
|
||||
});
|
||||
expect(JSON.parse(await readStdout(child))).toEqual([
|
||||
"--sandbox profile",
|
||||
'say "hi"',
|
||||
"",
|
||||
"harness",
|
||||
...commandScriptArguments,
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
test.runIf(process.platform === "win32")(
|
||||
"execCommand runs a .cmd script with its arguments unchanged on Windows",
|
||||
async () => {
|
||||
const launcher = await writeCommandScriptLauncher();
|
||||
const { stdout } = await execCommand(launcher, commandScriptArguments);
|
||||
expect(JSON.parse(stdout)).toEqual(commandScriptArguments);
|
||||
},
|
||||
);
|
||||
|
||||
// Real cmd.exe: a script that reads `%~1` gets each argument as given, without escapes.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"a .cmd script that reads its arguments one by one gets each one as given on Windows",
|
||||
async () => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin script reader "));
|
||||
roots.push(directory);
|
||||
const script = path.join(directory, "read.cmd");
|
||||
// `set /p` without input exits 1, so the script exits 0 on its own.
|
||||
await writeFile(
|
||||
script,
|
||||
'@echo off\r\n<nul set /p "=%~1|%~2|%~3|%~4|%~5|%~6|%~7|%~8|%~9"\r\nexit /b 0\r\n',
|
||||
);
|
||||
const { stdout } = await execCommand(script, [
|
||||
"plain",
|
||||
"with space",
|
||||
"feature&bugfix",
|
||||
"100%",
|
||||
"--profile=restricted",
|
||||
"a,b",
|
||||
"a;b",
|
||||
"value with %PATH% inside",
|
||||
"",
|
||||
]);
|
||||
expect(stdout).toBe(
|
||||
"plain|with space|feature&bugfix|100%|--profile=restricted|a,b|a;b|value with %PATH% inside|",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
// Real cmd.exe: a bare name is found on PATH like cmd.exe finds it. A `.cmd` shim that forwards
|
||||
// `%*`, as npm writes them, passes every argument on unchanged; a program starts directly.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"a bare command name found on PATH gets its arguments unchanged on Windows",
|
||||
async () => {
|
||||
const reader = await writeArgumentReader();
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "plugin bare shim "));
|
||||
roots.push(directory);
|
||||
await writeFile(
|
||||
path.join(directory, "paseo-forward.cmd"),
|
||||
`@"${process.execPath}" "${reader}" %*\r\n`,
|
||||
);
|
||||
// Windows env names ignore case, so drop the inherited `Path` before setting the new one.
|
||||
const inherited = Object.entries(process.env).filter(([key]) => key.toLowerCase() !== "path");
|
||||
const env = {
|
||||
...Object.fromEntries(inherited),
|
||||
PATH: `${directory};${process.env.PATH ?? ""}`,
|
||||
};
|
||||
const shim = await execCommand("paseo-forward", commandScriptArguments, { env });
|
||||
expect(JSON.parse(shim.stdout)).toEqual(commandScriptArguments);
|
||||
const program = await execCommand("node", [reader, ...commandScriptArguments], { env });
|
||||
expect(JSON.parse(program.stdout)).toEqual(commandScriptArguments);
|
||||
},
|
||||
);
|
||||
|
||||
// Real cmd.exe: a caller that formats its own cmd.exe line asks Node to pass it verbatim.
|
||||
test.runIf(process.platform === "win32")(
|
||||
"spawnProcess passes a caller's verbatim cmd.exe line unchanged on Windows",
|
||||
async () => {
|
||||
const reader = await writeArgumentReader();
|
||||
const child = spawnProcess(
|
||||
process.env.ComSpec ?? "cmd.exe",
|
||||
["/d", "/s", "/c", `""${process.execPath}" "${reader}" "a b" c"`],
|
||||
{ shell: false, windowsVerbatimArguments: true, stdio: "pipe" },
|
||||
);
|
||||
expect(JSON.parse(await readStdout(child))).toEqual(["a b", "c"]);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -8,10 +8,12 @@ import {
|
||||
import { extname } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import {
|
||||
findWindowsCommand,
|
||||
isWindowsCommandScript,
|
||||
quoteWindowsArgument,
|
||||
quoteWindowsCommand,
|
||||
windowsCommandLine,
|
||||
windowsCommandShell,
|
||||
} from "./process-internal/windows-command.js";
|
||||
import type { PluginLaunchWrap } from "./lifecycle.js";
|
||||
const execFileAsync = promisify(execFile);
|
||||
export interface ExecCommandOptions {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
@@ -20,6 +22,10 @@ export interface ExecCommandOptions {
|
||||
killSignal?: NodeJS.Signals;
|
||||
timeout?: number;
|
||||
maxBuffer?: number;
|
||||
/**
|
||||
* `true` runs the command through cmd.exe on Windows, quoted for it. A shell named here other
|
||||
* than cmd.exe gets the command and arguments as given, on every platform; quote for it.
|
||||
*/
|
||||
shell?: boolean | string;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
@@ -27,47 +33,96 @@ interface ExecCommandResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}
|
||||
function hasPathSeparator(value: string): boolean {
|
||||
return value.includes("/") || value.includes("\\");
|
||||
|
||||
export interface SpawnInvocation {
|
||||
command: string;
|
||||
args: string[];
|
||||
shell: boolean | string;
|
||||
/** The args are one cmd.exe line that Node must pass as given. */
|
||||
windowsVerbatimArguments?: boolean;
|
||||
}
|
||||
|
||||
function shouldUseWindowsShell(
|
||||
function namesCmd(shell: boolean | string | undefined): boolean {
|
||||
return (
|
||||
shell === true || (typeof shell === "string" && /^(?:.*[\\/])?cmd(?:\.exe)?$/iu.test(shell))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* How `spawnProcess` and `execCommand` start `command` on `platform`.
|
||||
*
|
||||
* On Windows a bare name is first found on `PATH`, as cmd.exe would find it, unless the caller
|
||||
* passes `shell: false`. A program then starts directly. A `.cmd` or `.bat` script, a name that is not on `PATH` (a cmd.exe builtin), or a
|
||||
* `shell: true` launch runs as `cmd.exe /d /s /c "..."`, quoted by `windowsCommandLine`. A shell
|
||||
* the caller names other than cmd.exe gets the command and arguments as given.
|
||||
*/
|
||||
export function resolveSpawnInvocation(
|
||||
command: string,
|
||||
requestedShell?: boolean | string,
|
||||
): boolean | string {
|
||||
if (isWindowsCommandScript(command)) {
|
||||
return true;
|
||||
args: readonly string[],
|
||||
requestedShell: boolean | string | undefined,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): SpawnInvocation {
|
||||
if (platform !== "win32") return { command, args: [...args], shell: requestedShell ?? false };
|
||||
if (typeof requestedShell === "string" && !namesCmd(requestedShell)) {
|
||||
return { command, args: [...args], shell: requestedShell };
|
||||
}
|
||||
if (requestedShell !== undefined) {
|
||||
return requestedShell;
|
||||
const bareName = !/[\\/]/u.test(command) && !extname(command);
|
||||
// `shell: false` starts a bare name directly, and Windows searches PATH without blocking Node.
|
||||
const found = bareName && requestedShell !== false ? findWindowsCommand(command, env) : undefined;
|
||||
const target = found ?? command;
|
||||
const commandScript = isWindowsCommandScript(target, platform);
|
||||
// Only cmd.exe knows a builtin, so a bare name off `PATH` goes to it unless the caller said no shell.
|
||||
const builtin = bareName && !found && requestedShell === undefined;
|
||||
if (!commandScript && !namesCmd(requestedShell) && !builtin) {
|
||||
return { command: target, args: [...args], shell: false };
|
||||
}
|
||||
return process.platform === "win32" && !hasPathSeparator(command) && !extname(command);
|
||||
// A cmd.exe the caller names runs the line; otherwise the child's ComSpec does.
|
||||
return {
|
||||
command: typeof requestedShell === "string" ? requestedShell : windowsCommandShell(env),
|
||||
args: ["/d", "/s", "/c", windowsCommandLine(target, args, { commandScript })],
|
||||
shell: false,
|
||||
windowsVerbatimArguments: true,
|
||||
};
|
||||
}
|
||||
|
||||
export interface SpawnProcessOptions extends SpawnOptions {
|
||||
/**
|
||||
* Start `[...wrap, command, ...args]`: the wrap's executable runs the command. `shell` is then
|
||||
* ignored; the wrap's executable runs through cmd.exe only when it is a `.cmd` or `.bat` file.
|
||||
*/
|
||||
wrap?: PluginLaunchWrap;
|
||||
}
|
||||
|
||||
/** Launch a CLI with Windows command-script handling and argv quoting. The caller owns env. */
|
||||
export function spawnProcess(
|
||||
command: string,
|
||||
args: string[],
|
||||
options: SpawnOptions & { stdio: "pipe" },
|
||||
options: SpawnProcessOptions & { stdio: "pipe" },
|
||||
): ChildProcessWithoutNullStreams;
|
||||
export function spawnProcess(command: string, args: string[], options?: SpawnOptions): ChildProcess;
|
||||
export function spawnProcess(
|
||||
command: string,
|
||||
args: string[],
|
||||
options?: SpawnOptions,
|
||||
options?: SpawnProcessOptions,
|
||||
): ChildProcess;
|
||||
export function spawnProcess(
|
||||
command: string,
|
||||
args: string[],
|
||||
options?: SpawnProcessOptions,
|
||||
): ChildProcess {
|
||||
const spawnOptions = options ?? {};
|
||||
const isWindows = process.platform === "win32";
|
||||
const shell = shouldUseWindowsShell(command, spawnOptions.shell);
|
||||
const { wrap, ...spawnOptions } = options ?? {};
|
||||
const env = options?.env ?? process.env;
|
||||
const invocation = wrap
|
||||
? resolveSpawnInvocation(wrap[0], [...wrap.slice(1), command, ...args], false, undefined, env)
|
||||
: resolveSpawnInvocation(command, args, spawnOptions.shell, undefined, env);
|
||||
|
||||
const shouldQuoteForShell = isWindows && shell !== false;
|
||||
const resolvedCommand = shouldQuoteForShell ? quoteWindowsCommand(command) : command;
|
||||
const resolvedArgs = shouldQuoteForShell ? args.map(quoteWindowsArgument) : args;
|
||||
|
||||
return spawn(resolvedCommand, resolvedArgs, {
|
||||
return spawn(invocation.command, invocation.args, {
|
||||
...spawnOptions,
|
||||
env: options?.env,
|
||||
shell,
|
||||
shell: invocation.shell,
|
||||
// Paseo's own cmd.exe line is verbatim; a direct launch keeps the caller's choice.
|
||||
windowsVerbatimArguments:
|
||||
invocation.windowsVerbatimArguments ?? spawnOptions.windowsVerbatimArguments,
|
||||
signal: options?.signal,
|
||||
windowsHide: true,
|
||||
});
|
||||
@@ -78,13 +133,15 @@ export async function execCommand(
|
||||
args: string[],
|
||||
options?: ExecCommandOptions,
|
||||
): Promise<ExecCommandResult> {
|
||||
const isWindows = process.platform === "win32";
|
||||
const shell = shouldUseWindowsShell(command, options?.shell);
|
||||
const shouldQuoteForShell = isWindows && shell !== false;
|
||||
const resolvedCommand = shouldQuoteForShell ? quoteWindowsCommand(command) : command;
|
||||
const resolvedArgs = shouldQuoteForShell ? args.map(quoteWindowsArgument) : args;
|
||||
const invocation = resolveSpawnInvocation(
|
||||
command,
|
||||
args,
|
||||
options?.shell,
|
||||
undefined,
|
||||
options?.env ?? process.env,
|
||||
);
|
||||
|
||||
return execFileAsync(resolvedCommand, resolvedArgs, {
|
||||
return execFileAsync(invocation.command, invocation.args, {
|
||||
cwd: options?.cwd,
|
||||
env: options?.env,
|
||||
encoding: options?.encoding ?? "utf8",
|
||||
@@ -92,7 +149,8 @@ export async function execCommand(
|
||||
killSignal: options?.killSignal,
|
||||
timeout: options?.timeout,
|
||||
maxBuffer: options?.maxBuffer,
|
||||
shell,
|
||||
shell: invocation.shell,
|
||||
windowsVerbatimArguments: invocation.windowsVerbatimArguments,
|
||||
windowsHide: true,
|
||||
}) as Promise<ExecCommandResult>;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
ProviderEventSchema,
|
||||
ProviderInputSchema,
|
||||
negotiateProviderCapabilities,
|
||||
requireProviderCapabilities,
|
||||
type ProviderEvent,
|
||||
type ProviderInput,
|
||||
type ProviderMetric,
|
||||
@@ -125,3 +126,38 @@ describe("Provider metrics", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Provider launch wrap", () => {
|
||||
const open = (wrap?: readonly [string, ...string[]]): ProviderInput =>
|
||||
ProviderInputSchema.parse({
|
||||
type: "session.open",
|
||||
requestId: "open",
|
||||
sessionId: "session-1",
|
||||
history: "skip",
|
||||
config: {
|
||||
cwd: "/workspace",
|
||||
env: {},
|
||||
mcpServers: {},
|
||||
settings: {},
|
||||
persist: true,
|
||||
...(wrap ? { wrap } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
it("requires session.launch_wrap only for an open that carries a wrap", () => {
|
||||
expect(() => requireProviderCapabilities([], open(["/bin/sandbox", "a b"]))).toThrow(
|
||||
"session.launch_wrap",
|
||||
);
|
||||
expect(() =>
|
||||
requireProviderCapabilities(["session.launch_wrap"], open(["/bin/sandbox"])),
|
||||
).not.toThrow();
|
||||
expect(() => requireProviderCapabilities([], open())).not.toThrow();
|
||||
});
|
||||
|
||||
it("keeps each wrap element whole and rejects an empty wrap", () => {
|
||||
expect(open(["/bin/sandbox", "a b"])).toMatchObject({
|
||||
config: { wrap: ["/bin/sandbox", "a b"] },
|
||||
});
|
||||
expect(() => open([] as unknown as [string])).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ export const PROVIDER_CAPABILITIES = [
|
||||
"session.can_stop_runtime",
|
||||
"session.archive",
|
||||
"session.configure",
|
||||
"session.launch_wrap",
|
||||
"session.list",
|
||||
"session.metrics",
|
||||
"session.persistence",
|
||||
@@ -34,6 +35,12 @@ export interface ProviderRegistration {
|
||||
getCatalogCacheKey?(options: ProviderCatalogOptions): Promise<string | undefined>;
|
||||
/** Default executable and arguments; the daemon resolves overrides before status/connect. */
|
||||
command?: readonly [string, ...string[]];
|
||||
/**
|
||||
* Sessions can run behind an `agent.open.before` wrap: the connection offers `session.launch_wrap`
|
||||
* and spawns each session as `[...config.wrap, command, ...args]`. Paseo publishes it on the
|
||||
* provider snapshot before the first connection.
|
||||
*/
|
||||
launchWrap?: boolean;
|
||||
status?(request: ProviderStatusRequest): Promise<ProviderStatus>;
|
||||
id: string;
|
||||
label: string;
|
||||
@@ -212,6 +219,8 @@ export interface ProviderSessionConfig {
|
||||
providerOptions?: Readonly<Record<string, unknown>>;
|
||||
title?: string;
|
||||
persist: boolean;
|
||||
/** Spawn the session as `[...wrap, command, ...args]`. Sent only with `session.launch_wrap`. */
|
||||
wrap?: readonly [string, ...string[]];
|
||||
}
|
||||
|
||||
export interface ProviderConfigChanges {
|
||||
@@ -804,6 +813,7 @@ export function requiredProviderCapabilities(input: ProviderInput): readonly Pro
|
||||
const capabilities: ProviderCapability[] = [];
|
||||
if (input.persistence) capabilities.push("session.persistence");
|
||||
if (input.config.toolPolicy) capabilities.push("permission.tool_policy");
|
||||
if (input.config.wrap) capabilities.push("session.launch_wrap");
|
||||
return capabilities;
|
||||
}
|
||||
case "session.prompt":
|
||||
@@ -907,6 +917,7 @@ const sessionConfigSchema = z
|
||||
providerOptions: z.record(z.string(), z.unknown()).optional(),
|
||||
title: z.string().optional(),
|
||||
persist: z.boolean(),
|
||||
wrap: z.tuple([z.string().min(1)], z.string()).optional(),
|
||||
})
|
||||
.strict();
|
||||
const externalResourceSchema = z
|
||||
|
||||
@@ -5,7 +5,11 @@ import ts from "typescript";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const repository = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
const skill = readFileSync(path.join(repository, "skills/paseo-plugin/SKILL.md"), "utf8");
|
||||
// A Windows checkout writes CRLF line endings.
|
||||
const skill = readFileSync(
|
||||
path.join(repository, "skills/paseo-plugin/SKILL.md"),
|
||||
"utf8",
|
||||
).replaceAll("\r\n", "\n");
|
||||
const pluginRoot = path.join(repository, "plugin-examples/skill-example");
|
||||
|
||||
interface SkillExample {
|
||||
|
||||
@@ -136,6 +136,8 @@ export interface ProviderSnapshotEntry {
|
||||
/** The page that helps users set up and troubleshoot this provider. */
|
||||
docsUrl?: string;
|
||||
defaultModeId?: string | null;
|
||||
/** The provider can run a session behind an `agent.open.before` wrap. Absent means it cannot. */
|
||||
launchWrap?: boolean;
|
||||
}
|
||||
|
||||
export interface AgentFeatureToggle {
|
||||
|
||||
@@ -50,6 +50,12 @@ describe("provider snapshot message schemas", () => {
|
||||
expect(parsed.source).toBe("custom");
|
||||
});
|
||||
|
||||
test("keeps launch-wrap support and leaves it absent when not reported", () => {
|
||||
const entry = { provider: "codex", status: "loading", label: "Codex" };
|
||||
expect(ProviderSnapshotEntrySchema.parse({ ...entry, launchWrap: true }).launchWrap).toBe(true);
|
||||
expect(ProviderSnapshotEntrySchema.parse(entry)).not.toHaveProperty("launchWrap");
|
||||
});
|
||||
|
||||
test("defaults missing enabled state in providers snapshot response entries", () => {
|
||||
const parsed = GetProvidersSnapshotResponseMessageSchema.parse({
|
||||
type: "get_providers_snapshot_response",
|
||||
|
||||
@@ -432,6 +432,7 @@ export const ProviderSnapshotEntrySchema = z.object({
|
||||
iconSvg: z.string().optional(),
|
||||
docsUrl: z.string().optional(),
|
||||
defaultModeId: z.string().nullable().optional(),
|
||||
launchWrap: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const CompactProviderSnapshotModelSchema = AgentModelDefinitionSchema.omit({
|
||||
|
||||
@@ -90,7 +90,7 @@
|
||||
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
|
||||
"test": "npm run test:unit && npm run test:integration",
|
||||
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
|
||||
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
|
||||
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/agent-configuration.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts src/server/plugins/agent-tools.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history|changes the launch wrap\"",
|
||||
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
|
||||
"test:integration:all": "npm run test:e2e",
|
||||
"test:integration:real": "vitest run real.e2e.test.ts",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { PluginSessionsRuntime } from "../plugins/agent-tools.js";
|
||||
import type { AttachedAgentTool, PluginSessionsRuntime } from "../plugins/agent-tools.js";
|
||||
import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js";
|
||||
import {
|
||||
prepareAgentMessage,
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
} from "./agent-messages/index.js";
|
||||
import { expect, test, vi, onTestFinished } from "vitest";
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { randomUUID } from "node:crypto";
|
||||
@@ -23,7 +23,11 @@ import {
|
||||
import { AgentStorage, parseStoredAgentRecord } from "./agent-storage.js";
|
||||
import { AgentTurnStartCanceledError } from "./agent-sdk-types.js";
|
||||
import { ForegroundPromptStart } from "./agent-run-state.js";
|
||||
import { CodexAppServerAgentSession } from "./providers/codex-app-server-agent.js";
|
||||
import {
|
||||
CodexAppServerAgentClient,
|
||||
CodexAppServerAgentSession,
|
||||
} from "./providers/codex-app-server-agent.js";
|
||||
import { spawnProcess } from "../../utils/spawn.js";
|
||||
import { createFakeCodexAppServer } from "./providers/codex/test-utils/fake-app-server.js";
|
||||
import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
|
||||
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
|
||||
@@ -16268,3 +16272,232 @@ test("importProviderSession keeps the stats the provider reported with its histo
|
||||
["assistant_message", null],
|
||||
]);
|
||||
});
|
||||
|
||||
class LaunchWrapRecordingClient extends TestAgentClient {
|
||||
readonly sessions: CloseRecordingTestAgentSession[] = [];
|
||||
readonly launchContexts: Array<AgentLaunchContext | undefined> = [];
|
||||
calls = { create: 0, resume: 0, import: 0 };
|
||||
|
||||
constructor(supportsLaunchWrap: boolean) {
|
||||
super("codex");
|
||||
if (supportsLaunchWrap) this.supportsLaunchWrap = true;
|
||||
}
|
||||
|
||||
supportsLaunchWrap?: boolean;
|
||||
|
||||
override async createSession(
|
||||
config: AgentSessionConfig,
|
||||
launchContext?: AgentLaunchContext,
|
||||
): Promise<AgentSession> {
|
||||
this.calls.create += 1;
|
||||
this.launchContexts.push(launchContext);
|
||||
const session = new CloseRecordingTestAgentSession(config);
|
||||
this.sessions.push(session);
|
||||
return session;
|
||||
}
|
||||
|
||||
override async resumeSession(
|
||||
handle: AgentPersistenceHandle,
|
||||
config?: Partial<AgentSessionConfig>,
|
||||
launchContext?: AgentLaunchContext,
|
||||
): Promise<AgentSession> {
|
||||
this.calls.resume += 1;
|
||||
this.launchContexts.push(launchContext);
|
||||
return await super.resumeSession(handle, config, launchContext);
|
||||
}
|
||||
|
||||
async importSession(input: ImportProviderSessionInput, context: ImportProviderSessionContext) {
|
||||
this.calls.import += 1;
|
||||
return {
|
||||
session: new TestAgentSession(context.config),
|
||||
config: context.storedConfig,
|
||||
persistence: { provider: this.provider, sessionId: input.providerHandleId },
|
||||
timeline: [],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
type TestLaunchWrap = [string, ...string[]];
|
||||
|
||||
/**
|
||||
* A session-open plugin that selects `wrap()` and attaches one tool while it does. Like the real runtime, an open's
|
||||
* tools take over only once its launch does, and a failed launch leaves the running session's tools.
|
||||
*/
|
||||
function launchWrapPluginSessions(wrap: () => TestLaunchWrap | undefined) {
|
||||
const pending = new Map<string, AttachedAgentTool[]>();
|
||||
const running = new Map<string, AttachedAgentTool[]>();
|
||||
const failedLaunches: string[] = [];
|
||||
const sessions: PluginSessionsRuntime = {
|
||||
openSession: async (request) => {
|
||||
const selected = wrap();
|
||||
const tools: AttachedAgentTool[] = selected
|
||||
? [
|
||||
{
|
||||
name: "sandbox_status",
|
||||
description: "Report the sandbox",
|
||||
inputSchema: {},
|
||||
pluginId: "sandbox",
|
||||
pluginInstanceId: "sandbox-1",
|
||||
},
|
||||
]
|
||||
: [];
|
||||
if (request.purpose === "interactive") pending.set(request.agentId, tools);
|
||||
return { ...request, ...(selected ? { wrap: selected } : {}), tools, mcpServerOwners: {} };
|
||||
},
|
||||
sessionLaunched: (agentId) => {
|
||||
const tools = pending.get(agentId);
|
||||
pending.delete(agentId);
|
||||
if (tools) running.set(agentId, tools);
|
||||
},
|
||||
sessionLaunchFailed: (agentId) => {
|
||||
pending.delete(agentId);
|
||||
failedLaunches.push(agentId);
|
||||
},
|
||||
refreshSession: async () => ({ stale: false }),
|
||||
sessionTools: (agentId) => running.get(agentId) ?? [],
|
||||
closeSession: (agentId) => {
|
||||
pending.delete(agentId);
|
||||
running.delete(agentId);
|
||||
},
|
||||
callTool: async () => ({ isError: true, text: "No plugin tools" }),
|
||||
};
|
||||
return { sessions, failedLaunches };
|
||||
}
|
||||
|
||||
function createLaunchWrapManager(client: LaunchWrapRecordingClient) {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-launch-wrap-"));
|
||||
onTestFinished(() => rmSync(workdir, { recursive: true, force: true }));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const hook: { wrap: TestLaunchWrap | undefined } = { wrap: undefined };
|
||||
const { sessions, failedLaunches } = launchWrapPluginSessions(() => hook.wrap);
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: client },
|
||||
registry: storage,
|
||||
logger,
|
||||
pluginSessions: sessions,
|
||||
});
|
||||
return { manager, storage, workdir, failedLaunches, hook };
|
||||
}
|
||||
|
||||
test("a wrapped open rejects on every path for a provider that does not apply wraps", async () => {
|
||||
const client = new LaunchWrapRecordingClient(false);
|
||||
const { manager, storage, workdir, failedLaunches, hook } = createLaunchWrapManager(client);
|
||||
const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const existing = client.sessions[0]!;
|
||||
hook.wrap = ["/opt/sandbox/bin/run", "--profile", "a b"];
|
||||
const calls = { ...client.calls };
|
||||
const unsupported = { code: "launch_wrap_unsupported", provider: "codex" };
|
||||
|
||||
await expect(
|
||||
manager.createAgent({ provider: "codex", cwd: workdir }, undefined, { workspaceId: undefined }),
|
||||
).rejects.toMatchObject(unsupported);
|
||||
await expect(
|
||||
manager.resumeAgentFromPersistence({ provider: "codex", sessionId: "saved" }, { cwd: workdir }),
|
||||
).rejects.toMatchObject(unsupported);
|
||||
await expect(
|
||||
manager.importProviderSession({
|
||||
provider: "codex",
|
||||
providerHandleId: "native",
|
||||
cwd: workdir,
|
||||
workspaceId: "import",
|
||||
}),
|
||||
).rejects.toMatchObject(unsupported);
|
||||
await expect(manager.reloadAgentSession(created.id)).rejects.toMatchObject(unsupported);
|
||||
|
||||
expect(client.calls).toEqual(calls);
|
||||
expect(existing.closed).toBe(false);
|
||||
expect(manager.getAgent(created.id)?.session).toBe(existing);
|
||||
// Each refused open is discarded, so the running session keeps the tools it launched with.
|
||||
expect(failedLaunches).toHaveLength(4);
|
||||
expect(failedLaunches.at(-1)).toBe(created.id);
|
||||
expect(manager.getPluginTools(created.id)).toEqual([]);
|
||||
await manager.flush();
|
||||
expect(JSON.stringify(await storage.get(created.id))).not.toContain("/opt/sandbox");
|
||||
await manager.closeAgent(created.id);
|
||||
});
|
||||
|
||||
test("a supporting provider receives the wrap at launch and the record never stores it", async () => {
|
||||
const client = new LaunchWrapRecordingClient(true);
|
||||
const { manager, storage, workdir, hook } = createLaunchWrapManager(client);
|
||||
hook.wrap = ["/opt/sandbox/bin/run", "--profile", "a b"];
|
||||
const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
expect(client.launchContexts[0]?.wrap).toEqual(["/opt/sandbox/bin/run", "--profile", "a b"]);
|
||||
await manager.flush();
|
||||
expect(JSON.stringify(await storage.get(created.id))).not.toContain("/opt/sandbox");
|
||||
await manager.closeAgent(created.id);
|
||||
});
|
||||
|
||||
// Records its argv, then answers as the Codex app server, so the provider command is only an
|
||||
// argument: a Windows script name there must reach the wrapper as is.
|
||||
const RECORDING_CODEX_APP_SERVER = `
|
||||
const { appendFileSync } = require("node:fs");
|
||||
const [log, ...rest] = process.argv.slice(2);
|
||||
appendFileSync(log, JSON.stringify(rest) + "\\n");
|
||||
const results = {
|
||||
"collaborationMode/list": { data: [] },
|
||||
"config/read": { config: {} },
|
||||
getUserSavedConfig: { config: {} },
|
||||
"model/list": { data: [{ id: "gpt-5.4", isDefault: true, defaultReasoningEffort: "medium" }] },
|
||||
"skills/list": { data: [] },
|
||||
"thread/start": { thread: { id: "thread-1" } },
|
||||
"thread/resume": { thread: { id: "thread-1" } },
|
||||
"thread/loaded/list": { data: [] },
|
||||
"thread/backgroundTerminals/list": { data: [], nextCursor: null },
|
||||
};
|
||||
let buffer = "";
|
||||
process.stdin.on("data", (chunk) => {
|
||||
buffer += chunk.toString();
|
||||
for (let index = buffer.indexOf("\\n"); index !== -1; index = buffer.indexOf("\\n")) {
|
||||
const line = buffer.slice(0, index).trim();
|
||||
buffer = buffer.slice(index + 1);
|
||||
if (!line) continue;
|
||||
const message = JSON.parse(line);
|
||||
if (message.id === undefined || !message.method) continue;
|
||||
process.stdout.write(JSON.stringify({ id: message.id, result: results[message.method] ?? {} }) + "\\n");
|
||||
}
|
||||
});
|
||||
`;
|
||||
|
||||
test("a wrapped refresh passes a Windows script provider command to the wrapper through the real spawn", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-launch-wrap-refresh-"));
|
||||
onTestFinished(() => rmSync(workdir, { recursive: true, force: true }));
|
||||
const launcher = join(workdir, "recording-app-server.cjs");
|
||||
const launches = join(workdir, "launches.jsonl");
|
||||
writeFileSync(launcher, RECORDING_CODEX_APP_SERVER);
|
||||
// The version probes run `node --version`; sessions spawn through the production spawnProcess.
|
||||
const codex = new CodexAppServerAgentClient(
|
||||
logger,
|
||||
{ command: { mode: "replace", argv: [process.execPath] } },
|
||||
{
|
||||
appServerProcess: {
|
||||
resolvePrefix: async () => ({ command: "C:\\codex\\codex.cmd", args: [] }),
|
||||
spawn: ({ command, args, options }) => spawnProcess(command, args, options),
|
||||
},
|
||||
},
|
||||
);
|
||||
const client: AgentClient = Object.assign(codex, { supportsLaunchWrap: true });
|
||||
const manager = new AgentManager({
|
||||
clients: { codex: client },
|
||||
logger,
|
||||
pluginSessions: launchWrapPluginSessions(() => [process.execPath, launcher, launches]).sessions,
|
||||
});
|
||||
const created = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
|
||||
await manager.reloadAgentSession(created.id);
|
||||
|
||||
const argv = readFileSync(launches, "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => JSON.parse(line) as string[]);
|
||||
expect(argv).toHaveLength(2);
|
||||
for (const launched of argv)
|
||||
expect(launched.slice(0, 2)).toEqual(["C:\\codex\\codex.cmd", "app-server"]);
|
||||
expect(manager.getAgent(created.id)?.lifecycle).not.toBe("error");
|
||||
await manager.closeAgent(created.id);
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@ import type {
|
||||
PluginSessionsRuntime,
|
||||
SessionOpenAgentFacts,
|
||||
} from "../plugins/agent-tools.js";
|
||||
import { ProviderOptionsValidationError } from "./provider-options.js";
|
||||
import { LaunchWrapUnsupportedError, 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";
|
||||
@@ -1721,6 +1721,7 @@ export class AgentManager {
|
||||
config: sent,
|
||||
env: options.env,
|
||||
metadata: options.metadata ?? {},
|
||||
workspaceId: options.workspaceId ?? null,
|
||||
});
|
||||
// COMPAT(featureValues): added in v0.15.0, remove after 2027-05-01. A plugin written
|
||||
// against the previous SDK edits `config.featureValues`.
|
||||
@@ -6644,6 +6645,7 @@ export class AgentManager {
|
||||
let appendSystemPrompt: string[] | undefined;
|
||||
let mcpServers: AgentSessionConfig["mcpServers"];
|
||||
let mcpServerOwners: Record<string, string> | undefined;
|
||||
let wrap: AgentLaunchContext["wrap"];
|
||||
if (this.pluginSessions) {
|
||||
const request = {
|
||||
agentId,
|
||||
@@ -6661,14 +6663,18 @@ export class AgentManager {
|
||||
};
|
||||
const transformed = await this.pluginSessions.openSession(request);
|
||||
env = transformed.env;
|
||||
wrap = transformed.wrap;
|
||||
if (request.purpose === "interactive") {
|
||||
appendSystemPrompt = transformed.appendSystemPrompt;
|
||||
mcpServers = transformed.mcpServers;
|
||||
mcpServerOwners = transformed.mcpServerOwners;
|
||||
}
|
||||
// launchAgent discards this open when the wrap is refused, so a running session keeps its tools.
|
||||
if (wrap) await requireLaunchWrap(client);
|
||||
}
|
||||
const context: AgentLaunchContext = {
|
||||
agentId,
|
||||
wrap,
|
||||
...pluginPromptContext(appendSystemPrompt),
|
||||
mcpServers,
|
||||
mcpServerOwners,
|
||||
@@ -6855,3 +6861,8 @@ function pluginPromptContext(
|
||||
): Pick<AgentLaunchContext, "appendSystemPrompt"> {
|
||||
return appendSystemPrompt?.length ? { appendSystemPrompt } : {};
|
||||
}
|
||||
|
||||
async function requireLaunchWrap(client: AgentClient): Promise<void> {
|
||||
if (client.supportsLaunchWrap !== true) throw new LaunchWrapUnsupportedError(client.provider);
|
||||
await client.requireLaunchWrap?.();
|
||||
}
|
||||
|
||||
@@ -147,6 +147,7 @@ export interface ProviderSnapshotEntry {
|
||||
/** The page that helps users set up and troubleshoot this provider. */
|
||||
docsUrl?: string;
|
||||
defaultModeId?: string | null;
|
||||
launchWrap?: boolean;
|
||||
}
|
||||
|
||||
export interface AgentCreateConfigParent {
|
||||
@@ -677,6 +678,8 @@ export interface AgentLaunchContext {
|
||||
mcpServerOwners?: Record<string, string>;
|
||||
agentId?: string;
|
||||
env?: Record<string, string>;
|
||||
/** Spawn the harness as `[...wrap, command, ...args]`. Selected by a plugin hook; never persisted. */
|
||||
wrap?: readonly [string, ...string[]];
|
||||
/**
|
||||
* Runtime-only internal Paseo tools. This must never be persisted into
|
||||
* AgentSessionConfig; providers may adapt it to their native tool surface.
|
||||
@@ -884,6 +887,10 @@ export interface AgentClient {
|
||||
>;
|
||||
readonly provider: AgentProvider;
|
||||
readonly capabilities: AgentCapabilityFlags;
|
||||
/** Sessions honor `AgentLaunchContext.wrap`. The provider registry sets it from the provider contract. */
|
||||
supportsLaunchWrap?: boolean;
|
||||
/** Throw unless the live provider runtime can apply a wrap. Plugin providers connect to learn it. */
|
||||
requireLaunchWrap?(): Promise<void>;
|
||||
/**
|
||||
* Create the agent with `config.providerOptions` (defaults already merged in). Emit nothing
|
||||
* about options while creating. If the agent ended up different from the options, say so in the
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { PluginLifecycle } from "../plugins/lifecycle/index.js";
|
||||
import type { CreatePaseoWorktreeInput } from "../paseo-worktree-service.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type pino from "pino";
|
||||
@@ -47,6 +48,7 @@ interface CreateAgentLifecycleDispatchDependencies {
|
||||
clearWorkspaceArchiving: (workspaceIds: Iterable<string>) => void;
|
||||
killTerminalsForWorkspace: (workspaceId: string) => Promise<void>;
|
||||
logger: pino.Logger;
|
||||
lifecycle: Pick<PluginLifecycle, "before"> | null;
|
||||
}
|
||||
|
||||
export interface LifecycleRegistration {
|
||||
@@ -192,6 +194,7 @@ export class CreateAgentLifecycleDispatch {
|
||||
|
||||
await archiveByScope(
|
||||
{
|
||||
lifecycle: this.dependencies.lifecycle,
|
||||
paseoHome: this.dependencies.paseoHome,
|
||||
paseoWorktreesBaseRoot: this.dependencies.worktreesRoot,
|
||||
worktreeManagers: this.dependencies.worktreeManagers,
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
import { CallToolResultSchema, type Tool } from "@modelcontextprotocol/sdk/types.js";
|
||||
import type { McpServerConfig } from "./agent-sdk-types.js";
|
||||
import type { PaseoToolResult } from "./tools/types.js";
|
||||
import { applyLaunchWrap, type LaunchWrap } from "../../utils/launch-wrap.js";
|
||||
|
||||
const SERVER_TIMEOUT_MS = 10_000;
|
||||
const TERMINATE_TIMEOUT_MS = 2_000;
|
||||
@@ -36,6 +37,8 @@ export interface ConnectMcpServerInput {
|
||||
cwd: string;
|
||||
/** Complete environment for a stdio server; the server's own `env` overlays it. */
|
||||
env: NodeJS.ProcessEnv;
|
||||
/** Start a stdio server as `[...wrap, command, ...args]`. */
|
||||
wrap?: LaunchWrap;
|
||||
clientName: string;
|
||||
}
|
||||
|
||||
@@ -165,11 +168,12 @@ async function withDeadline<T>(
|
||||
}
|
||||
}
|
||||
|
||||
function createTransport({ config, cwd, env }: ConnectMcpServerInput) {
|
||||
function createTransport({ config, cwd, env, wrap }: ConnectMcpServerInput) {
|
||||
if (config.type === "stdio") {
|
||||
const launch = applyLaunchWrap({ command: config.command, args: config.args ?? [] }, wrap);
|
||||
return new StdioClientTransport({
|
||||
command: config.command,
|
||||
args: config.args,
|
||||
command: launch.command,
|
||||
args: launch.args,
|
||||
cwd,
|
||||
env: definedEnvironment({ ...env, ...config.env }),
|
||||
stderr: "ignore",
|
||||
|
||||
@@ -8,6 +8,7 @@ import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { runAcpProvider, type AcpStreamMessage } from "@getpaseo/plugin/server/acp";
|
||||
import type {
|
||||
ProviderCapability,
|
||||
ProviderConnection,
|
||||
ProviderLaunch,
|
||||
ProviderEvent,
|
||||
@@ -313,6 +314,7 @@ function createRewindProviderHarness(
|
||||
reuseAnswerId?: boolean;
|
||||
forkOnRevert?: boolean;
|
||||
handleInput?: ProviderHarnessOptions["handleInput"];
|
||||
extraCapabilities?: ProviderCapability[];
|
||||
} = {},
|
||||
) {
|
||||
const nativeMessages: string[] = [];
|
||||
@@ -324,6 +326,7 @@ function createRewindProviderHarness(
|
||||
"session.revert.conversation",
|
||||
"session.revert.files",
|
||||
"session.revert.both",
|
||||
...(options.extraCapabilities ?? []),
|
||||
],
|
||||
async handleInput(input, emit) {
|
||||
if (await options.handleInput?.(input, emit)) return true;
|
||||
@@ -3680,3 +3683,54 @@ test("bounds settings wait when Stop is queued behind an unanswered steer", asyn
|
||||
await plugins.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test("a declared launch wrap still needs session.launch_wrap on the live connection", async () => {
|
||||
const harness = createProviderHarness();
|
||||
const registry = new PluginAgentClientRegistry(createTestLogger());
|
||||
registry.replace([{ ...harness.registration, launchWrap: true }]);
|
||||
expect(registry.definitions()[harness.registration.id]?.supportsLaunchWrap).toBe(true);
|
||||
const client = registry.clients()[harness.registration.id]!;
|
||||
expect(client.supportsLaunchWrap).toBe(true);
|
||||
|
||||
await expect(client.requireLaunchWrap?.()).rejects.toMatchObject({
|
||||
code: "launch_wrap_unsupported",
|
||||
});
|
||||
await expect(
|
||||
client.createSession(
|
||||
{ provider: harness.registration.id, cwd: tmpdir() },
|
||||
{ wrap: ["/opt/sandbox/bin/run"] },
|
||||
),
|
||||
).rejects.toThrow("session.launch_wrap");
|
||||
expect(harness.inputs.some((input) => input.type === "session.open")).toBe(false);
|
||||
await registry.shutdown();
|
||||
});
|
||||
|
||||
test("a provider that declares no launch wrap is not marked as supporting it", () => {
|
||||
const harness = createProviderHarness();
|
||||
const registry = new PluginAgentClientRegistry(createTestLogger());
|
||||
registry.replace([harness.registration]);
|
||||
expect(registry.definitions()[harness.registration.id]?.supportsLaunchWrap).toBe(false);
|
||||
expect(registry.clients()[harness.registration.id]!.supportsLaunchWrap).toBe(false);
|
||||
});
|
||||
|
||||
test("a plugin session reopen sends the wrap the session opened with", async () => {
|
||||
const harness = createRewindProviderHarness({ extraCapabilities: ["session.launch_wrap"] });
|
||||
const registry = new PluginAgentClientRegistry(createTestLogger());
|
||||
registry.replace([{ ...harness.registration, launchWrap: true }]);
|
||||
const client = registry.clients()[harness.registration.id]!;
|
||||
await expect(client.requireLaunchWrap?.()).resolves.toBeUndefined();
|
||||
const wrap: [string, ...string[]] = ["/opt/sandbox/bin/run", "--profile", "a b"];
|
||||
const session = await client.createSession(
|
||||
{ provider: harness.registration.id, cwd: tmpdir() },
|
||||
{ wrap },
|
||||
);
|
||||
await session.run("A");
|
||||
|
||||
await session.revertConversation!({ messageId: "user-A" });
|
||||
|
||||
const opens = harness.inputs.filter((input) => input.type === "session.open");
|
||||
expect(opens.length).toBeGreaterThanOrEqual(2);
|
||||
for (const open of opens) expect(open.config.wrap).toEqual(wrap);
|
||||
await session.close();
|
||||
await registry.shutdown();
|
||||
});
|
||||
|
||||
@@ -81,6 +81,7 @@ import {
|
||||
formatProviderDiagnostic,
|
||||
type DiagnosticEntry,
|
||||
} from "./providers/diagnostic-utils.js";
|
||||
import { LaunchWrapUnsupportedError } from "./provider-options.js";
|
||||
import type { RegisteredProviderDefinition } from "./provider-registry.js";
|
||||
import { runProviderTurn } from "./providers/provider-runner.js";
|
||||
import { StaleProviderSessionError } from "./stale-provider-session-error.js";
|
||||
@@ -296,6 +297,11 @@ class ProviderRuntime {
|
||||
return this.connection?.capabilities ?? [];
|
||||
}
|
||||
|
||||
/** The live connection's capabilities, connecting first when no connection exists yet. */
|
||||
async connectedCapabilities(): Promise<readonly string[]> {
|
||||
return (await this.getConnection()).capabilities;
|
||||
}
|
||||
|
||||
get isClosed(): boolean {
|
||||
return this.closed;
|
||||
}
|
||||
@@ -1052,6 +1058,7 @@ function createPluginProviderDefinition(
|
||||
defaultModeId: null,
|
||||
modes: [],
|
||||
supportsExactMcpPreapproval: true,
|
||||
supportsLaunchWrap: registration.launchWrap === true,
|
||||
createClient,
|
||||
};
|
||||
}
|
||||
@@ -1070,10 +1077,12 @@ class PluginAgentClient implements AgentClient {
|
||||
|
||||
readonly getCatalogCacheKey?: AgentClient["getCatalogCacheKey"];
|
||||
readonly installation?: AgentClientInstallation;
|
||||
readonly supportsLaunchWrap: boolean;
|
||||
|
||||
constructor(registration: ProviderRegistration, runtimeSettings?: ProviderRuntimeSettings) {
|
||||
this.provider = registration.id;
|
||||
this.label = registration.label;
|
||||
this.supportsLaunchWrap = registration.launchWrap === true;
|
||||
this.runtime = new ProviderRuntime(registration, runtimeSettings);
|
||||
if (registration.getCatalogCacheKey)
|
||||
this.getCatalogCacheKey = (options) => this.runtime.catalogCacheKey(options);
|
||||
@@ -1101,6 +1110,15 @@ class PluginAgentClient implements AgentClient {
|
||||
return agentCapabilities(this.runtime.negotiatedCapabilities);
|
||||
}
|
||||
|
||||
async requireLaunchWrap(): Promise<void> {
|
||||
if (!(await this.runtime.connectedCapabilities()).includes("session.launch_wrap")) {
|
||||
throw new LaunchWrapUnsupportedError(
|
||||
this.provider,
|
||||
`Provider '${this.provider}' declares launch wrap support, but its connection does not offer session.launch_wrap`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async createSession(
|
||||
config: AgentSessionConfig,
|
||||
launchContext?: AgentLaunchContext,
|
||||
@@ -2143,6 +2161,7 @@ function mapSessionConfig(
|
||||
providerOptions: config.providerOptions,
|
||||
title: config.title ?? undefined,
|
||||
persist,
|
||||
...(launchContext?.wrap ? { wrap: launchContext.wrap } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -37,6 +37,18 @@ export class ToolPolicyUnsupportedError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export class LaunchWrapUnsupportedError extends Error {
|
||||
readonly code = "launch_wrap_unsupported" as const;
|
||||
|
||||
constructor(
|
||||
readonly provider: string,
|
||||
reason?: string,
|
||||
) {
|
||||
super(reason ?? `Provider '${provider}' cannot run a session behind a launch wrap`);
|
||||
this.name = "LaunchWrapUnsupportedError";
|
||||
}
|
||||
}
|
||||
|
||||
export function validateProviderOptions<T extends ProviderOptions>(
|
||||
provider: string,
|
||||
schema: z.ZodType<T>,
|
||||
|
||||
@@ -645,6 +645,32 @@ test("new provider extending codex archives and unarchives its native sessions",
|
||||
]);
|
||||
});
|
||||
|
||||
test("launch-wrap support comes from the provider contract and follows extends", () => {
|
||||
const registry = buildProviderRegistry(logger, {
|
||||
isDev: true,
|
||||
providerOverrides: {
|
||||
"my-claude": { extends: "claude", label: "My Claude" },
|
||||
"my-acp": { extends: "acp", label: "My ACP", command: ["my-acp", "--acp"] },
|
||||
},
|
||||
});
|
||||
|
||||
const support = Object.fromEntries(
|
||||
Object.keys(registry).map((id) => [id, registry[id].createClient(logger).supportsLaunchWrap]),
|
||||
);
|
||||
expect(support).toEqual({
|
||||
claude: true,
|
||||
codex: true,
|
||||
copilot: true,
|
||||
opencode: true,
|
||||
pi: true,
|
||||
omp: true,
|
||||
mock: false,
|
||||
"mock-slow": false,
|
||||
"my-claude": true,
|
||||
"my-acp": true,
|
||||
});
|
||||
});
|
||||
|
||||
test("built-in OMP override keeps the real OMP adapter enabled and launchable", async () => {
|
||||
const omp = new FakeOmp(["custom-omp"]);
|
||||
const registry = buildProviderRegistry(logger, {
|
||||
|
||||
@@ -78,6 +78,7 @@ export interface ProviderDefinition extends AgentProviderDefinition {
|
||||
*/
|
||||
derivedFromProviderId: string | null;
|
||||
supportsExactMcpPreapproval: boolean;
|
||||
supportsLaunchWrap: boolean;
|
||||
applyToolPolicy: (
|
||||
config: AgentSessionConfig,
|
||||
toolPolicy: ToolPolicy | undefined,
|
||||
@@ -101,6 +102,7 @@ export interface RegisteredProviderDefinition extends AgentProviderDefinition {
|
||||
requiresConfiguration?: boolean;
|
||||
iconSvg?: string;
|
||||
supportsExactMcpPreapproval: boolean;
|
||||
supportsLaunchWrap: boolean;
|
||||
createClient: (logger: Logger, runtimeSettings?: ProviderRuntimeSettings) => AgentClient;
|
||||
}
|
||||
|
||||
@@ -148,25 +150,38 @@ interface ResolvedProvider {
|
||||
|
||||
interface ProviderContract {
|
||||
supportsExactMcpPreapproval: boolean;
|
||||
/** Sessions spawn their harness behind an `agent.open.before` wrap. */
|
||||
supportsLaunchWrap?: boolean;
|
||||
applyToolPolicy?: (provider: string, toolPolicy: ToolPolicy) => ToolPolicy;
|
||||
}
|
||||
|
||||
// Every built-in provider that starts a local harness honors a wrap; the mock providers start none.
|
||||
const PROVIDER_CONTRACTS: Record<string, ProviderContract> = {
|
||||
claude: { supportsExactMcpPreapproval: true },
|
||||
codex: { supportsExactMcpPreapproval: true },
|
||||
opencode: { supportsExactMcpPreapproval: true },
|
||||
claude: { supportsExactMcpPreapproval: true, supportsLaunchWrap: true },
|
||||
codex: { supportsExactMcpPreapproval: true, supportsLaunchWrap: true },
|
||||
copilot: { supportsExactMcpPreapproval: false, supportsLaunchWrap: true },
|
||||
opencode: { supportsExactMcpPreapproval: true, supportsLaunchWrap: true },
|
||||
pi: { supportsExactMcpPreapproval: false, supportsLaunchWrap: true },
|
||||
omp: { supportsExactMcpPreapproval: false, supportsLaunchWrap: true },
|
||||
};
|
||||
|
||||
const UNSUPPORTED_PROVIDER_CONTRACT: ProviderContract = {
|
||||
supportsExactMcpPreapproval: false,
|
||||
};
|
||||
|
||||
// A user-defined ACP provider is a local command, which starts behind the wrap.
|
||||
const CUSTOM_ACP_PROVIDER_CONTRACT: ProviderContract = {
|
||||
supportsExactMcpPreapproval: false,
|
||||
supportsLaunchWrap: true,
|
||||
};
|
||||
|
||||
const HUB_E2E_PROVIDER_ID = "hub-e2e";
|
||||
const HUB_E2E_MCP_SERVER = "hub";
|
||||
const HUB_E2E_TOOL_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/u;
|
||||
// The cross-repository Hub harness owns this synthetic provider ID. It exercises the production
|
||||
// registry path without extending exact-preapproval support to user-defined ACP providers.
|
||||
const HUB_E2E_PROVIDER_CONTRACT: ProviderContract = {
|
||||
...CUSTOM_ACP_PROVIDER_CONTRACT,
|
||||
supportsExactMcpPreapproval: true,
|
||||
applyToolPolicy: (provider, toolPolicy) => {
|
||||
for (const grant of toolPolicy.preapproved) {
|
||||
@@ -498,6 +513,7 @@ function wrapClientProvider(
|
||||
additionalModels: ProviderProfileModel[],
|
||||
profileModelsAreAdditive: boolean,
|
||||
configuredOptions: ProviderOptions | undefined,
|
||||
supportsLaunchWrap: boolean,
|
||||
): AgentClient {
|
||||
const listImportableSessions = inner.listImportableSessions?.bind(inner);
|
||||
const importSession = inner.importSession?.bind(inner);
|
||||
@@ -517,6 +533,7 @@ function wrapClientProvider(
|
||||
get capabilities() {
|
||||
return inner.capabilities;
|
||||
},
|
||||
supportsLaunchWrap,
|
||||
shutdown: inner.shutdown?.bind(inner),
|
||||
createSession: async (config, launchContext, options) =>
|
||||
wrapSessionProvider(
|
||||
@@ -626,6 +643,7 @@ function wrapClientProvider(
|
||||
? async (handle) => await unarchiveNativeSession({ ...handle, provider: inner.provider })
|
||||
: undefined,
|
||||
resolveUsageLaunch: inner.resolveUsageLaunch?.bind(inner),
|
||||
requireLaunchWrap: inner.requireLaunchWrap?.bind(inner),
|
||||
getCatalogCacheKey: inner.getCatalogCacheKey?.bind(inner),
|
||||
isAvailable: (signal, options) => inner.isAvailable(signal, options),
|
||||
getDiagnostic: inner.getDiagnostic?.bind(inner),
|
||||
@@ -670,6 +688,7 @@ function createRegistryEntry(
|
||||
enabled: resolved.enabled,
|
||||
derivedFromProviderId: resolved.derivedFromProviderId,
|
||||
supportsExactMcpPreapproval: resolved.contract.supportsExactMcpPreapproval,
|
||||
supportsLaunchWrap: resolved.contract.supportsLaunchWrap === true,
|
||||
applyToolPolicy: (config, toolPolicy) => {
|
||||
if (toolPolicy && !resolved.contract.supportsExactMcpPreapproval) {
|
||||
throw new ToolPolicyUnsupportedError(provider);
|
||||
@@ -747,6 +766,7 @@ function createResolvedProviderClient(
|
||||
additionalModels,
|
||||
resolved.profileModelsAreAdditive,
|
||||
resolved.providerOptions,
|
||||
resolved.contract.supportsLaunchWrap === true,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -880,7 +900,7 @@ function addDerivedProviders(
|
||||
contract:
|
||||
providerId === HUB_E2E_PROVIDER_ID
|
||||
? HUB_E2E_PROVIDER_CONTRACT
|
||||
: UNSUPPORTED_PROVIDER_CONTRACT,
|
||||
: CUSTOM_ACP_PROVIDER_CONTRACT,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
@@ -962,6 +982,7 @@ export function buildProviderRegistry(
|
||||
createClient: definition.createClient,
|
||||
contract: {
|
||||
supportsExactMcpPreapproval: definition.supportsExactMcpPreapproval,
|
||||
supportsLaunchWrap: definition.supportsLaunchWrap,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -542,6 +542,23 @@ describe("ProviderSnapshotManager public surface", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("loading entries already report launch-wrap support, before any discovery", () => {
|
||||
const manager = new ProviderSnapshotManager({
|
||||
logger: createTestLogger(),
|
||||
providerOverrides: { "my-codex": { extends: "codex", label: "My Codex" } },
|
||||
});
|
||||
try {
|
||||
const snapshot = manager.getSnapshot("/tmp/project").records.map(({ entry }) => entry);
|
||||
const byProvider = (provider: string) =>
|
||||
snapshot.find((entry) => entry.provider === provider);
|
||||
expect(byProvider("codex")).toMatchObject({ status: "loading", launchWrap: true });
|
||||
expect(byProvider("my-codex")).toMatchObject({ status: "loading", launchWrap: true });
|
||||
expect(byProvider("claude")).toMatchObject({ status: "loading", launchWrap: true });
|
||||
} finally {
|
||||
manager.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test("providerOverrides with enabled:false marks the provider as unavailable without probing", async () => {
|
||||
const isAvailable = vi.fn(async () => true);
|
||||
const fetchCatalog = vi.fn(async () => ({
|
||||
|
||||
@@ -1044,6 +1044,7 @@ export class ProviderSnapshotManager {
|
||||
iconSvg: definition.iconSvg,
|
||||
docsUrl: definition.docsUrl,
|
||||
defaultModeId: definition.defaultModeId ?? null,
|
||||
...(definition.supportsLaunchWrap ? { launchWrap: true } : {}),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5864,3 +5864,64 @@ describe("custom ACP provider with configured models", () => {
|
||||
expect((await created.getRuntimeInfo()).model).toBe("advertised-default");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ACPAgentSession launch wrap against an ACP agent", () => {
|
||||
const fakeAgentPath = fileURLToPath(new URL("./test-utils/fake-acp-agent.mjs", import.meta.url));
|
||||
|
||||
test("starts the agent and its terminals behind the session's wrap", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-acp-wrap-"));
|
||||
const record = path.join(root, "launches.jsonl");
|
||||
const launcher = path.join(root, "launcher.cjs");
|
||||
await writeFile(
|
||||
launcher,
|
||||
`
|
||||
const [, , ...argv] = process.argv;
|
||||
require("node:fs").appendFileSync(${JSON.stringify(record)}, JSON.stringify(argv) + "\\n");
|
||||
const child = require("node:child_process").spawn(argv[0], argv.slice(1), { stdio: "inherit" });
|
||||
child.on("exit", (code) => process.exit(code ?? 1));
|
||||
`,
|
||||
);
|
||||
const session = new ACPAgentSession(
|
||||
{ provider: "acp", cwd: root },
|
||||
{
|
||||
provider: "acp",
|
||||
logger: createTestLogger(),
|
||||
defaultCommand: [process.execPath, fakeAgentPath, "{}"],
|
||||
defaultModes: [],
|
||||
capabilities: {
|
||||
supportsStreaming: true,
|
||||
supportsSessionPersistence: true,
|
||||
supportsDynamicModes: true,
|
||||
supportsMcpServers: true,
|
||||
supportsReasoningStream: true,
|
||||
supportsToolInvocations: true,
|
||||
},
|
||||
wrap: [process.execPath, launcher],
|
||||
},
|
||||
);
|
||||
try {
|
||||
await session.initializeNewSession();
|
||||
const { terminalId } = await session.createTerminal({
|
||||
sessionId: "session-1",
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.exit(0)"],
|
||||
cwd: root,
|
||||
});
|
||||
await expect(
|
||||
session.waitForTerminalExit({ sessionId: "session-1", terminalId }),
|
||||
).resolves.toMatchObject({ exitCode: 0 });
|
||||
|
||||
const launches = (await readFile(record, "utf8"))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => JSON.parse(line));
|
||||
expect(launches).toEqual([
|
||||
[process.execPath, fakeAgentPath, "{}"],
|
||||
[process.execPath, "-e", "process.exit(0)"],
|
||||
]);
|
||||
} finally {
|
||||
await session.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -548,6 +548,8 @@ interface ACPAgentSessionOptions {
|
||||
configuredModelIds?: readonly string[];
|
||||
agentId?: string;
|
||||
launchEnv?: Record<string, string>;
|
||||
/** Start the agent, and every terminal it asks for, as `[...wrap, command, ...args]`. */
|
||||
wrap?: AgentLaunchContext["wrap"];
|
||||
waitForInitialCommands?: boolean;
|
||||
initialCommandsWaitTimeoutMs?: number;
|
||||
terminateProcess?: ProcessTerminator;
|
||||
@@ -1152,6 +1154,7 @@ export class ACPAgentClient implements AgentClient {
|
||||
configuredModelIds: options?.configuredModelIds,
|
||||
agentId: launchContext?.agentId,
|
||||
launchEnv: launchContext?.env,
|
||||
wrap: launchContext?.wrap,
|
||||
extensionCommandsParser: this.extensionCommandsParser,
|
||||
waitForInitialCommands: this.waitForInitialCommands,
|
||||
initialCommandsWaitTimeoutMs: this.initialCommandsWaitTimeoutMs,
|
||||
@@ -1212,6 +1215,7 @@ export class ACPAgentClient implements AgentClient {
|
||||
configuredModelIds: options?.configuredModelIds,
|
||||
agentId: launchContext?.agentId,
|
||||
launchEnv: launchContext?.env,
|
||||
wrap: launchContext?.wrap,
|
||||
extensionCommandsParser: this.extensionCommandsParser,
|
||||
waitForInitialCommands: this.waitForInitialCommands,
|
||||
initialCommandsWaitTimeoutMs: this.initialCommandsWaitTimeoutMs,
|
||||
@@ -1951,6 +1955,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
) => Promise<void>;
|
||||
private readonly agentId?: string;
|
||||
private readonly launchEnv?: Record<string, string>;
|
||||
private readonly wrap?: AgentLaunchContext["wrap"];
|
||||
private readonly usageProvider?: string;
|
||||
private readonly usageSessionKey = randomUUID();
|
||||
private readonly harnessEnvironment: Record<string, string>;
|
||||
@@ -2023,6 +2028,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
this.availableModes = options.defaultModes;
|
||||
this.agentId = options.agentId;
|
||||
this.launchEnv = options.launchEnv;
|
||||
this.wrap = options.wrap;
|
||||
this.usageProvider = options.usageProvider;
|
||||
this.harnessEnvironment = createProviderEnv({
|
||||
runtimeSettings: options.runtimeSettings,
|
||||
@@ -3117,7 +3123,9 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
terminalCommand.shell === false
|
||||
? [this.launchEnv, env, createStringCommandShellEnvOverlay()]
|
||||
: [this.launchEnv, env];
|
||||
// A terminal runs commands for the agent, so it runs behind the agent's wrap too.
|
||||
const child = spawnProcess(terminalCommand.command, terminalCommand.args, {
|
||||
wrap: this.wrap,
|
||||
cwd: params.cwd ?? this.config.cwd,
|
||||
...createProviderEnvSpec({
|
||||
runtimeSettings: this.runtimeSettings,
|
||||
@@ -3222,6 +3230,7 @@ export class ACPAgentSession implements AgentSession, ACPClient {
|
||||
const command = prefix.command;
|
||||
const args = [...prefix.args, ...this.defaultCommand.slice(1)];
|
||||
const child = spawnProcess(command, args, {
|
||||
wrap: this.wrap,
|
||||
cwd: await this.resolveProcessCwd(),
|
||||
...createProviderEnvSpec({
|
||||
runtimeSettings: this.runtimeSettings,
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { PassThrough } from "node:stream";
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import {
|
||||
@@ -173,4 +176,49 @@ describe("Claude spawn override", () => {
|
||||
expect(launchArgs?.join(" ")).not.toContain("secret-token");
|
||||
expect(launchArgs).not.toContain("--mcp-config");
|
||||
});
|
||||
|
||||
test("starts Claude Code behind the session's launch wrap", async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "claude-launch-wrap-"));
|
||||
const launcher = path.join(root, "launcher.mjs");
|
||||
await writeFile(launcher, "process.stdout.write(JSON.stringify(process.argv.slice(2)));\n");
|
||||
let capturedOptions: Options | undefined;
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
queryFactory: ({ options }: ClaudeQueryInput) => {
|
||||
capturedOptions = options;
|
||||
return createQueryMock([]);
|
||||
},
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
resolveVersion: async () => "2.1.326",
|
||||
});
|
||||
const session = await client.createSession(
|
||||
{ provider: "claude", cwd: root },
|
||||
{ wrap: [process.execPath, launcher, "--sandbox"] },
|
||||
);
|
||||
try {
|
||||
await (session as unknown as { ensureQuery(): Promise<unknown> }).ensureQuery();
|
||||
const child = capturedOptions?.spawnClaudeCodeProcess?.({
|
||||
command: "/test/claude/bin",
|
||||
args: ["--output-format", "stream-json"],
|
||||
cwd: root,
|
||||
env: {},
|
||||
signal: new AbortController().signal,
|
||||
}) as ChildProcess | undefined;
|
||||
if (!child?.stdout) throw new Error("Claude Code was not spawned");
|
||||
let stdout = "";
|
||||
child.stdout.on("data", (chunk: Buffer) => {
|
||||
stdout += chunk.toString("utf8");
|
||||
});
|
||||
await new Promise((resolve) => child.once("close", resolve));
|
||||
expect(JSON.parse(stdout)).toEqual([
|
||||
"--sandbox",
|
||||
"/test/claude/bin",
|
||||
"--output-format",
|
||||
"stream-json",
|
||||
]);
|
||||
} finally {
|
||||
await session.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -515,6 +515,7 @@ interface ClaudeAgentSessionOptions {
|
||||
handle?: AgentPersistenceHandle;
|
||||
agentId?: string;
|
||||
launchEnv?: Record<string, string>;
|
||||
wrap?: AgentLaunchContext["wrap"];
|
||||
persistSession?: boolean;
|
||||
logger: Logger;
|
||||
queryFactory?: ClaudeQueryFactory;
|
||||
@@ -1713,6 +1714,7 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
runtimeSettings: this.runtimeSettings,
|
||||
agentId: launchContext?.agentId,
|
||||
launchEnv: launchContext?.env,
|
||||
wrap: launchContext?.wrap,
|
||||
persistSession: options?.persistSession,
|
||||
logger: this.logger,
|
||||
queryFactory: this.queryFactory,
|
||||
@@ -1745,6 +1747,7 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
handle,
|
||||
agentId: launchContext?.agentId,
|
||||
launchEnv: launchContext?.env,
|
||||
wrap: launchContext?.wrap,
|
||||
logger: this.logger,
|
||||
queryFactory: this.queryFactory,
|
||||
resolveBinary: this.resolveBinary,
|
||||
@@ -2457,6 +2460,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
|
||||
private readonly config: ClaudeAgentConfig;
|
||||
private readonly launchEnv?: Record<string, string>;
|
||||
private readonly wrap?: AgentLaunchContext["wrap"];
|
||||
private readonly agentId?: string;
|
||||
private readonly defaults?: { agents?: Record<string, AgentDefinition> };
|
||||
private readonly runtimeSettings?: ProviderRuntimeSettings;
|
||||
@@ -2596,6 +2600,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
this.config = config;
|
||||
assertClaudeThinkingOptionSupported(config.model, config.thinkingOptionId);
|
||||
this.launchEnv = options.launchEnv;
|
||||
this.wrap = options.wrap;
|
||||
this.agentId = options.agentId;
|
||||
this.defaults = options.defaults;
|
||||
this.runtimeSettings = options.runtimeSettings;
|
||||
@@ -3887,6 +3892,7 @@ class ClaudeAgentSession implements AgentSession {
|
||||
{
|
||||
runtimeSettings: this.runtimeSettings,
|
||||
launchEnv: this.launchEnv,
|
||||
wrap: this.wrap,
|
||||
queryFactory: this.queryFactory,
|
||||
onChildProcess: (child) => {
|
||||
this.childProcess = child;
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from "../../provider-launch-config.js";
|
||||
import { buildSelfNodeCommand, createExternalProcessEnv } from "../../../paseo-env.js";
|
||||
import { execCommand, spawnProcess } from "../../../../utils/spawn.js";
|
||||
import type { AgentLaunchContext } from "../../agent-sdk-types.js";
|
||||
|
||||
// Keep the raw SDK query import in this module only. Claude process launch behavior
|
||||
// must stay shared between production and tests so Windows .cmd/.bat handling cannot
|
||||
@@ -19,6 +20,8 @@ export type ClaudeQueryFactory = (input: ClaudeQueryInput) => Query;
|
||||
export interface ClaudeQueryContext {
|
||||
runtimeSettings?: ProviderRuntimeSettings;
|
||||
launchEnv?: Record<string, string>;
|
||||
/** Start Claude Code as `[...wrap, command, ...args]`. */
|
||||
wrap?: AgentLaunchContext["wrap"];
|
||||
queryFactory?: ClaudeQueryFactory;
|
||||
/** Called with the spawned child process so the caller can tree-kill it on close. */
|
||||
onChildProcess?: (child: ChildProcess) => void;
|
||||
@@ -90,7 +93,7 @@ function applyRuntimeSettingsToClaudeOptions(
|
||||
options: ClaudeOptions,
|
||||
context: ClaudeQueryContext,
|
||||
): ClaudeOptions {
|
||||
const { runtimeSettings, onChildProcess } = context;
|
||||
const { runtimeSettings, onChildProcess, wrap } = context;
|
||||
return {
|
||||
...options,
|
||||
spawnClaudeCodeProcess: (spawnOptions) => {
|
||||
@@ -109,6 +112,7 @@ function applyRuntimeSettingsToClaudeOptions(
|
||||
const command = selfNodeCommand?.command ?? resolved.command;
|
||||
const args = selfNodeCommand?.args ?? resolved.args;
|
||||
const child = spawnProcess(command, args, {
|
||||
wrap,
|
||||
cwd: spawnOptions.cwd,
|
||||
...(selfNodeCommand
|
||||
? { env: selfNodeCommand.env, envMode: "internal" as const }
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { spawnProcess } from "../../../utils/spawn.js";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
import { CodexAppServerAgentClient } from "./codex-app-server-agent.js";
|
||||
@@ -80,4 +81,35 @@ describe("CodexAppServerAgentClient spawn error handling", () => {
|
||||
process.off("uncaughtException", onUncaught);
|
||||
}
|
||||
});
|
||||
test("a missing launch wrap fails the open and never starts the bare codex command", async () => {
|
||||
const spawned: Array<{ command: string; args: string[]; wrap?: readonly string[] }> = [];
|
||||
const client = new CodexAppServerAgentClient(logger, undefined, {
|
||||
appServerProcess: {
|
||||
resolvePrefix: async () => ({ command: process.execPath, args: ["codex.js"] }),
|
||||
spawn: ({ command, args, options }) => {
|
||||
spawned.push({ command, args, wrap: options.wrap });
|
||||
return spawnProcess(command, args, options);
|
||||
},
|
||||
},
|
||||
});
|
||||
// Skip the host-side version probes; they are not session spawns.
|
||||
Object.assign(client, {
|
||||
goalsEnabledPromise: Promise.resolve(false),
|
||||
autoReviewEnabledPromise: Promise.resolve(false),
|
||||
});
|
||||
|
||||
await expect(
|
||||
client.createSession(
|
||||
{ provider: "codex", cwd: "/tmp/codex-wrap" },
|
||||
{ wrap: ["/nonexistent/launch-wrap-that-does-not-exist", "--flag"] },
|
||||
),
|
||||
).rejects.toThrow(/ENOENT/u);
|
||||
expect(spawned).toEqual([
|
||||
{
|
||||
command: process.execPath,
|
||||
args: ["codex.js", "app-server"],
|
||||
wrap: ["/nonexistent/launch-wrap-that-does-not-exist", "--flag"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2492,6 +2492,60 @@ describe("Codex app-server provider", () => {
|
||||
appServer.assertNoErrors();
|
||||
});
|
||||
|
||||
test.each(["interactive", "history"] as const)(
|
||||
"spawns a wrapped %s resume through the launch wrap",
|
||||
async (purpose) => {
|
||||
const spawned: Array<{ command: string; args: string[]; wrap?: readonly string[] }> = [];
|
||||
let resumes = 0;
|
||||
// History reads the archived thread; an interactive resume unarchives it and resumes again.
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"thread/loaded/list": () => ({ data: [] }),
|
||||
"thread/resume": () =>
|
||||
resumes++ === 0
|
||||
? Promise.reject(new Error(archivedThreadErrorMessage("archived-thread-id")))
|
||||
: { thread: { id: "archived-thread-id" } },
|
||||
"thread/unarchive": () => ({ thread: { id: "archived-thread-id" } }),
|
||||
"thread/read": () => ({ thread: { turns: [] } }),
|
||||
});
|
||||
const provider = new CodexAppServerAgentClient(createTestLogger(), undefined, {
|
||||
appServerProcess: {
|
||||
resolvePrefix: async () => ({
|
||||
command: "/opt/codex/bin/codex",
|
||||
args: ["--profile", "x"],
|
||||
}),
|
||||
spawn: ({ command, args, options }) => {
|
||||
spawned.push({ command, args, wrap: options.wrap });
|
||||
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,
|
||||
{ wrap: ["/opt/sandbox/bin/run", "--profile", "a b"] },
|
||||
{ purpose },
|
||||
);
|
||||
|
||||
expect(spawned.length).toBeGreaterThan(0);
|
||||
for (const input of spawned) {
|
||||
expect(input).toEqual({
|
||||
command: "/opt/codex/bin/codex",
|
||||
args: ["--profile", "x", "app-server"],
|
||||
wrap: ["/opt/sandbox/bin/run", "--profile", "a b"],
|
||||
});
|
||||
}
|
||||
await session.close();
|
||||
appServer.assertNoErrors();
|
||||
},
|
||||
);
|
||||
|
||||
test("unarchives Codex when an active Paseo agent resumes an archived thread", async () => {
|
||||
const threadRequests: string[] = [];
|
||||
let resumeAttempts = 0;
|
||||
|
||||
@@ -8272,6 +8272,7 @@ export class CodexAppServerAgentClient implements AgentClient {
|
||||
environment: Record<string, string>;
|
||||
goalsEnabled?: boolean;
|
||||
agentId?: string;
|
||||
wrap?: AgentLaunchContext["wrap"];
|
||||
}): Promise<() => ChildProcessWithoutNullStreams> {
|
||||
const processPort = this.deps.appServerProcess ?? defaultCodexAppServerProcess;
|
||||
const launchPrefix = await processPort.resolvePrefix({ runtimeSettings: this.runtimeSettings });
|
||||
@@ -8285,14 +8286,17 @@ export class CodexAppServerAgentClient implements AgentClient {
|
||||
agentId: options.agentId,
|
||||
provider: CODEX_PROVIDER,
|
||||
launchPrefix,
|
||||
wrap: options.wrap,
|
||||
goalsEnabled: options.goalsEnabled === true,
|
||||
},
|
||||
"provider.codex.spawn",
|
||||
);
|
||||
// Every spawn from this closure, including reconnects and startup retries, carries the wrap.
|
||||
const child = processPort.spawn({
|
||||
command: launchPrefix.command,
|
||||
args,
|
||||
options: {
|
||||
wrap: options.wrap,
|
||||
detached: process.platform !== "win32",
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
baseEnv: options.environment,
|
||||
@@ -8339,6 +8343,7 @@ export class CodexAppServerAgentClient implements AgentClient {
|
||||
environment,
|
||||
goalsEnabled,
|
||||
agentId: launchContext?.agentId,
|
||||
wrap: launchContext?.wrap,
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
sessionConfig,
|
||||
@@ -8376,6 +8381,7 @@ export class CodexAppServerAgentClient implements AgentClient {
|
||||
environment,
|
||||
goalsEnabled,
|
||||
agentId: launchContext?.agentId,
|
||||
wrap: launchContext?.wrap,
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
merged,
|
||||
|
||||
@@ -23,6 +23,8 @@ export interface JsonlRpcLaunch {
|
||||
args: string[];
|
||||
cwd: string;
|
||||
env?: Record<string, string>;
|
||||
/** Start the process as `[...wrap, command, ...args]`. */
|
||||
wrap?: readonly [string, ...string[]];
|
||||
}
|
||||
|
||||
interface JsonlRpcResponse {
|
||||
@@ -64,6 +66,7 @@ function assertChildWithPipes(
|
||||
|
||||
function spawnJsonlRpcProcess(launch: JsonlRpcLaunch): ChildProcessWithoutNullStreams {
|
||||
const child = spawnProcess(launch.command, launch.args, {
|
||||
wrap: launch.wrap,
|
||||
cwd: launch.cwd,
|
||||
envOverlay: launch.env,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
|
||||
@@ -433,6 +433,7 @@ function buildResumeStartInput(input: {
|
||||
cwd: input.resumeConfig.cwd,
|
||||
protocolMode: "rpc-ui",
|
||||
env: input.launchContext?.env,
|
||||
wrap: input.launchContext?.wrap,
|
||||
session: input.sessionFile,
|
||||
thinkingOptionId: normalizeOmpThinkingOption(input.resumeConfig.thinkingOptionId) ?? undefined,
|
||||
...(input.launchMode.modeId ? { modeId: input.launchMode.modeId } : {}),
|
||||
@@ -2356,15 +2357,18 @@ export class OmpAgentClient implements AgentClient {
|
||||
runtimeSession: OmpRuntimeSession,
|
||||
catalog: PaseoToolCatalog | undefined,
|
||||
config: AgentSessionConfig,
|
||||
launchEnv?: NodeJS.ProcessEnv,
|
||||
launch: Pick<OmpStartSessionInput, "env" | "wrap">,
|
||||
): Promise<OmpHostToolRouter | undefined> {
|
||||
if (!catalog && !config.mcpServers) {
|
||||
return;
|
||||
}
|
||||
const bridge = await OmpMcpBridge.connect(config.mcpServers, config.cwd, this.logger, {
|
||||
...process.env,
|
||||
...this.runtimeSettings?.env,
|
||||
...launchEnv,
|
||||
// Paseo starts stdio MCP servers for OMP, so they run behind the agent's wrap as OMP does.
|
||||
const bridge = await OmpMcpBridge.connect({
|
||||
servers: config.mcpServers,
|
||||
cwd: config.cwd,
|
||||
logger: this.logger,
|
||||
env: { ...process.env, ...this.runtimeSettings?.env, ...launch.env },
|
||||
wrap: launch.wrap,
|
||||
});
|
||||
const router = new OmpHostToolRouter({ runtimeSession, catalog, bridge, logger: this.logger });
|
||||
try {
|
||||
@@ -2407,6 +2411,7 @@ export class OmpAgentClient implements AgentClient {
|
||||
...(config.pluginAppendSystemPrompt ?? []),
|
||||
),
|
||||
env: launchContext?.env,
|
||||
wrap: launchContext?.wrap,
|
||||
};
|
||||
const runtimeSession = await this.resolveRuntime(config.providerOptions).startSession(
|
||||
startInput,
|
||||
@@ -2417,7 +2422,7 @@ export class OmpAgentClient implements AgentClient {
|
||||
runtimeSession,
|
||||
launchContext?.paseoTools,
|
||||
config,
|
||||
startInput.env,
|
||||
startInput,
|
||||
);
|
||||
const initialState = await this.restoreFastMode(
|
||||
runtimeSession,
|
||||
@@ -2487,7 +2492,7 @@ export class OmpAgentClient implements AgentClient {
|
||||
runtimeSession,
|
||||
launchContext?.paseoTools,
|
||||
resumeConfig.config,
|
||||
startInput.env,
|
||||
startInput,
|
||||
);
|
||||
const resumedState = await this.applyResumeModel(runtimeSession, resumeConfig.model);
|
||||
const config = {
|
||||
@@ -2566,7 +2571,7 @@ export class OmpAgentClient implements AgentClient {
|
||||
next,
|
||||
launchContext?.paseoTools,
|
||||
config,
|
||||
startInput.env,
|
||||
startInput,
|
||||
);
|
||||
const state = await next.getState();
|
||||
await this.restoreFastMode(next, config, state);
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import type { ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { PassThrough } from "node:stream";
|
||||
import pino from "pino";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
@@ -121,6 +124,54 @@ function withoutRequestId(command: Record<string, unknown>): Record<string, unkn
|
||||
}
|
||||
|
||||
describe("OMP CLI runtime", () => {
|
||||
test("starts OMP behind the session's launch wrap and negotiates through the wrap", async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "omp-launch-wrap-"));
|
||||
try {
|
||||
const fakeOmp = path.join(root, "fake-omp.mjs");
|
||||
await writeFile(
|
||||
fakeOmp,
|
||||
[
|
||||
'import { createInterface } from "node:readline";',
|
||||
'const ready = { type: "ready", protocolVersion: 1, supportedProtocolVersions: [1], maxFrameBytes: 1048576, maxReassembledFrameBytes: 67108864 };',
|
||||
'process.stdout.write(JSON.stringify(ready) + "\\n");',
|
||||
'createInterface({ input: process.stdin }).on("line", () => undefined);',
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
const launcher = path.join(root, "launcher.mjs");
|
||||
await writeFile(
|
||||
launcher,
|
||||
[
|
||||
'import { spawn } from "node:child_process";',
|
||||
'import { writeFileSync } from "node:fs";',
|
||||
"const [command, ...args] = process.argv.slice(2);",
|
||||
'writeFileSync(new URL("./wrapped.json", import.meta.url), JSON.stringify([command, ...args]));',
|
||||
'const child = spawn(command, args, { stdio: "inherit" });',
|
||||
'child.on("exit", (code) => process.exit(code ?? 1));',
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
const runtime = new OmpCliRuntime({
|
||||
logger: pino({ level: "silent" }),
|
||||
command: [process.execPath, fakeOmp],
|
||||
});
|
||||
|
||||
const session = await runtime.startSession({
|
||||
cwd: root,
|
||||
wrap: [process.execPath, launcher],
|
||||
});
|
||||
try {
|
||||
expect(
|
||||
JSON.parse(await readFile(path.join(root, "wrapped.json"), "utf8")).slice(0, 2),
|
||||
).toEqual([process.execPath, fakeOmp]);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("steer waits for OMP's response and surfaces rejection", async () => {
|
||||
const child = createOmpChild();
|
||||
let pending: Record<string, unknown> | null = null;
|
||||
|
||||
@@ -83,6 +83,7 @@ export class OmpCliRuntime implements OmpRuntime {
|
||||
args,
|
||||
cwd: launch.cwd,
|
||||
env: launch.env,
|
||||
wrap: launch.wrap,
|
||||
};
|
||||
const spawn = this.spawnProcess;
|
||||
const processOptions = {
|
||||
|
||||
@@ -22,12 +22,15 @@ export class OmpMcpBridge {
|
||||
private readonly connections: McpClientConnection[] = [];
|
||||
private closed = false;
|
||||
|
||||
static async connect(
|
||||
servers: Record<string, McpServerConfig> | undefined,
|
||||
cwd: string,
|
||||
logger: Logger,
|
||||
env: NodeJS.ProcessEnv,
|
||||
): Promise<OmpMcpBridge> {
|
||||
static async connect(input: {
|
||||
servers: Record<string, McpServerConfig> | undefined;
|
||||
cwd: string;
|
||||
logger: Logger;
|
||||
env: NodeJS.ProcessEnv;
|
||||
/** Start each stdio server as `[...wrap, command, ...args]`. */
|
||||
wrap?: readonly [string, ...string[]];
|
||||
}): Promise<OmpMcpBridge> {
|
||||
const { servers, cwd, logger, env, wrap } = input;
|
||||
const bridge = new OmpMcpBridge();
|
||||
const connections = await Promise.all(
|
||||
Object.entries(servers ?? {}).map(async ([serverName, config]) => {
|
||||
@@ -36,6 +39,7 @@ export class OmpMcpBridge {
|
||||
config,
|
||||
cwd,
|
||||
env,
|
||||
wrap,
|
||||
clientName: "paseo-omp-mcp",
|
||||
});
|
||||
return { serverName, connection };
|
||||
|
||||
@@ -18,6 +18,8 @@ export interface OmpRuntimeLaunch {
|
||||
cwd: string;
|
||||
argv: string[];
|
||||
env?: Record<string, string>;
|
||||
/** Start OMP as `[...wrap, ...argv]`. */
|
||||
wrap?: readonly [string, ...string[]];
|
||||
protocolMode?: "rpc" | "rpc-ui";
|
||||
model?: string;
|
||||
thinkingOptionId?: string;
|
||||
@@ -32,6 +34,8 @@ export interface OmpStartSessionInput {
|
||||
cwd: string;
|
||||
signal?: AbortSignal;
|
||||
env?: Record<string, string>;
|
||||
/** The agent's launch wrap; every OMP process started for the agent runs behind it. */
|
||||
wrap?: readonly [string, ...string[]];
|
||||
protocolMode?: "rpc" | "rpc-ui";
|
||||
model?: string;
|
||||
thinkingOptionId?: string;
|
||||
@@ -114,6 +118,7 @@ export function buildOmpLaunch(input: {
|
||||
...input.session.env,
|
||||
}
|
||||
: undefined,
|
||||
wrap: input.session.wrap,
|
||||
model: input.session.model,
|
||||
thinkingOptionId: input.session.thinkingOptionId,
|
||||
protocolMode,
|
||||
|
||||
@@ -4563,6 +4563,47 @@ describe("OpenCode persisted sessions", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("importSession reads a wrapped session on a server started behind the wrap", async () => {
|
||||
const runtime = new TestOpenCodeHarness();
|
||||
const metadataClient = new TestOpenCodeClient();
|
||||
const resumedClient = new TestOpenCodeClient();
|
||||
const cwd = "/workspace/repo";
|
||||
const selectedSession = {
|
||||
id: "ses_selected",
|
||||
directory: cwd,
|
||||
title: "Selected session",
|
||||
time: { created: 2000, updated: 3000 },
|
||||
};
|
||||
metadataClient.sessionGetResponse = { data: selectedSession };
|
||||
metadataClient.sessionMessagesResponse = { data: [] };
|
||||
resumedClient.sessionGetResponse = { data: selectedSession };
|
||||
resumedClient.sessionMessagesResponse = { data: [] };
|
||||
runtime.enqueueClient(metadataClient);
|
||||
runtime.enqueueClient(resumedClient);
|
||||
const client = new OpenCodeAgentClient(createTestLogger(), undefined, {
|
||||
serverManager: runtime,
|
||||
createClient: runtime.createClient,
|
||||
});
|
||||
const wrap = ["/opt/sandbox/bin/run", "--profile", "import"] as const;
|
||||
|
||||
const imported = await client.importSession(
|
||||
{ providerHandleId: "ses_selected", cwd },
|
||||
{
|
||||
config: { provider: "opencode", cwd },
|
||||
storedConfig: { provider: "opencode", cwd },
|
||||
launchContext: { env: { PASEO_AGENT_ID: "imported" }, wrap },
|
||||
},
|
||||
);
|
||||
await imported.session.close();
|
||||
|
||||
expect(runtime.acquisitions.map((acquisition) => [acquisition.kind, acquisition.wrap])).toEqual(
|
||||
[
|
||||
["dedicated", wrap],
|
||||
["dedicated", wrap],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test("listImportableSessions matches Windows cwd paths with forward slashes", async () => {
|
||||
const runtime = new TestOpenCodeHarness();
|
||||
const openCodeClient = new TestOpenCodeClient();
|
||||
@@ -4749,6 +4790,52 @@ describe("OpenCode provider subagent contract", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("resumes a wrapped child on its own server behind the wrap, not the parent's server", async () => {
|
||||
const runtime = new TestOpenCodeHarness();
|
||||
const parentClient = new TestOpenCodeClient();
|
||||
const childClient = new TestOpenCodeClient();
|
||||
parentClient.sessionCreateResponse = { data: { id: "ses_parent_wrapped" } };
|
||||
runtime.enqueueClient(parentClient);
|
||||
runtime.enqueueClient(childClient);
|
||||
const client = new OpenCodeAgentClient(createTestLogger(), undefined, {
|
||||
serverManager: runtime,
|
||||
createClient: runtime.createClient,
|
||||
});
|
||||
const parent = await client.createSession(
|
||||
{ provider: "opencode", cwd: "/workspace/repo" },
|
||||
{ env: { PASEO_AGENT_ID: "parent-agent" } },
|
||||
);
|
||||
parentClient.emitEvent({
|
||||
type: "session.created",
|
||||
properties: {
|
||||
info: { id: "ses_child_wrapped", parentID: "ses_parent_wrapped", title: "Live child" },
|
||||
},
|
||||
});
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
const wrap = ["/opt/sandbox/bin/run", "--profile", "child"] as const;
|
||||
|
||||
const child = await client.resumeSession(
|
||||
{
|
||||
provider: "opencode",
|
||||
sessionId: "ses_child_wrapped",
|
||||
nativeHandle: "ses_child_wrapped",
|
||||
metadata: { cwd: "/workspace/repo" },
|
||||
},
|
||||
undefined,
|
||||
{ env: { PASEO_AGENT_ID: "child-agent" }, wrap },
|
||||
);
|
||||
await child.close();
|
||||
await parent.close();
|
||||
|
||||
expect(runtime.acquisitions.map((acquisition) => [acquisition.kind, acquisition.wrap])).toEqual(
|
||||
[
|
||||
["dedicated", undefined],
|
||||
["dedicated", wrap],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test("synthesizes an autonomous turn for adopted child timeline events", async () => {
|
||||
const { child, childClient, parent } = await createAdoptedChildSession();
|
||||
const completed = createTestDeferred<void>();
|
||||
|
||||
@@ -79,6 +79,7 @@ import {
|
||||
} from "../provider-launch-config.js";
|
||||
import { withTimeout } from "../../../utils/promise-timeout.js";
|
||||
import { execCommand } from "../../../utils/spawn.js";
|
||||
import type { LaunchWrap } from "../../../utils/launch-wrap.js";
|
||||
import { mapOpencodeToolCall } from "./opencode/tool-call-mapper.js";
|
||||
import {
|
||||
OPENCODE_EVENT_STREAM_READY_TIMEOUT_MS,
|
||||
@@ -1537,7 +1538,10 @@ export class OpenCodeAgentClient implements AgentClient {
|
||||
cwd,
|
||||
};
|
||||
const openCodeConfig = this.assertConfig(config);
|
||||
const registeredServerUrl = getOpenCodeChildSessionServerUrl(handle.sessionId);
|
||||
// A registered parent server runs outside this launch's wrap, so a wrapped resume starts its own.
|
||||
const registeredServerUrl = launchContext?.wrap
|
||||
? undefined
|
||||
: getOpenCodeChildSessionServerUrl(handle.sessionId);
|
||||
const registeredAcquisition = registeredServerUrl
|
||||
? this.serverManager.acquireExisting(registeredServerUrl)
|
||||
: null;
|
||||
@@ -1617,14 +1621,25 @@ export class OpenCodeAgentClient implements AgentClient {
|
||||
config: OpenCodeAgentConfig,
|
||||
launchContext?: AgentLaunchContext,
|
||||
): Promise<OpenCodeServerAcquisition> {
|
||||
if (!this.bridge || requiresDedicatedOpenCodeServer(config, launchContext)) {
|
||||
return launchContext?.env
|
||||
? this.serverManager.acquireDedicated(launchContext.env)
|
||||
: this.serverManager.acquireCurrent();
|
||||
if (launchContext?.wrap)
|
||||
return this.acquireWrappedServer(launchContext.wrap, launchContext.env);
|
||||
if (
|
||||
launchContext?.env &&
|
||||
(!this.bridge || requiresDedicatedOpenCodeServer(config, launchContext))
|
||||
) {
|
||||
return this.serverManager.acquireDedicated({ env: launchContext.env });
|
||||
}
|
||||
return this.serverManager.acquireCurrent();
|
||||
}
|
||||
|
||||
/** A wrapped session gets its own server, so it never shares one that runs outside its wrap. */
|
||||
private acquireWrappedServer(
|
||||
wrap: LaunchWrap,
|
||||
env: Record<string, string> = {},
|
||||
): Promise<OpenCodeServerAcquisition> {
|
||||
return this.serverManager.acquireDedicated({ env, wrap });
|
||||
}
|
||||
|
||||
private bindBridgeSession(
|
||||
sessionId: string,
|
||||
launchContext?: AgentLaunchContext,
|
||||
@@ -1712,7 +1727,11 @@ export class OpenCodeAgentClient implements AgentClient {
|
||||
}
|
||||
|
||||
async importSession(input: ImportProviderSessionInput, context: ImportProviderSessionContext) {
|
||||
const acquisition = await this.serverManager.acquireCurrent();
|
||||
const wrap = context.launchContext?.wrap;
|
||||
// A wrapped import reads the session behind its wrap too, so it never starts a server outside it.
|
||||
const acquisition = wrap
|
||||
? await this.acquireWrappedServer(wrap, context.launchContext?.env)
|
||||
: await this.serverManager.acquireCurrent();
|
||||
const { url } = acquisition.server;
|
||||
const client = this.createOpenCodeClient({
|
||||
baseUrl: url,
|
||||
|
||||
@@ -115,6 +115,44 @@ describe("OpenCode bridge adapter", () => {
|
||||
await customEnv.close();
|
||||
await customMcp.close();
|
||||
});
|
||||
|
||||
test("starts a wrapped session on its own server behind the wrap", async () => {
|
||||
const paseoHome = await mkdtemp(path.join(os.tmpdir(), "paseo-opencode-adapter-"));
|
||||
const bridge = new OpenCodeBridge({ paseoHome, logger: createTestLogger() });
|
||||
await bridge.start();
|
||||
cleanups.push(async () => {
|
||||
await bridge.close();
|
||||
await rm(paseoHome, { recursive: true, force: true });
|
||||
});
|
||||
const runtime = new TestOpenCodeHarness();
|
||||
const wrappedClient = new TestOpenCodeClient();
|
||||
const sharedClient = new TestOpenCodeClient();
|
||||
wrappedClient.sessionCreateResponse = { data: { id: "ses_wrapped" } };
|
||||
sharedClient.sessionCreateResponse = { data: { id: "ses_shared" } };
|
||||
runtime.enqueueClient(wrappedClient);
|
||||
runtime.enqueueClient(sharedClient);
|
||||
const client = new OpenCodeAgentClient(createTestLogger(), undefined, {
|
||||
serverManager: runtime,
|
||||
createClient: runtime.createClient,
|
||||
bridge,
|
||||
});
|
||||
|
||||
const wrapped = await client.createSession(
|
||||
{ provider: "opencode", cwd: "/workspace/one" },
|
||||
{ env: { PASEO_AGENT_ID: "one" }, wrap: ["/opt/sandbox/bin/run", "--profile", "a b"] },
|
||||
);
|
||||
const shared = await client.createSession(
|
||||
{ provider: "opencode", cwd: "/workspace/two" },
|
||||
{ env: { PASEO_AGENT_ID: "two" } },
|
||||
);
|
||||
|
||||
expect(runtime.acquisitions.map(({ kind, wrap }) => ({ kind, wrap }))).toEqual([
|
||||
{ kind: "dedicated", wrap: ["/opt/sandbox/bin/run", "--profile", "a b"] },
|
||||
{ kind: "current", wrap: undefined },
|
||||
]);
|
||||
await wrapped.close();
|
||||
await shared.close();
|
||||
});
|
||||
});
|
||||
|
||||
async function readBridgeContext(bridge: OpenCodeBridge, sessionId: string): Promise<unknown> {
|
||||
|
||||
@@ -296,7 +296,7 @@ describe("OpenCodeServerManager generations", () => {
|
||||
runtime.processForPort(4473).announceListening();
|
||||
const currentAcquisition = await currentStart;
|
||||
|
||||
const dedicatedStart = manager.acquireDedicated({ TEST_ENV: "custom" });
|
||||
const dedicatedStart = manager.acquireDedicated({ env: { TEST_ENV: "custom" } });
|
||||
await runtime.settle();
|
||||
|
||||
await currentAcquisition.release();
|
||||
@@ -311,10 +311,29 @@ describe("OpenCodeServerManager generations", () => {
|
||||
expect(runtime.terminatedPorts).toEqual([4473, 4474]);
|
||||
});
|
||||
|
||||
test("a dedicated server starts behind its session's wrap and the shared server does not", async () => {
|
||||
const { manager, runtime } = createTestManager([4477, 4478]);
|
||||
|
||||
const shared = await manager.acquireCurrent();
|
||||
const wrapped = await manager.acquireDedicated({
|
||||
env: { PASEO_AGENT_ID: "wrapped" },
|
||||
wrap: ["/opt/sandbox/bin/run", "--profile", "a b"],
|
||||
});
|
||||
|
||||
expect(runtime.spawnCalls.map(({ args, options }) => ({ args, wrap: options.wrap }))).toEqual([
|
||||
{ args: ["serve", "--port", "4477"], wrap: undefined },
|
||||
{ args: ["serve", "--port", "4478"], wrap: ["/opt/sandbox/bin/run", "--profile", "a b"] },
|
||||
]);
|
||||
await shared.release();
|
||||
await wrapped.release();
|
||||
});
|
||||
|
||||
test("acquireExisting keeps a retired dedicated server alive until every reference releases", async () => {
|
||||
const { manager, runtime } = createTestManager([4475]);
|
||||
|
||||
const dedicatedAcquisition = await manager.acquireDedicated({ PASEO_AGENT_ID: "parent" });
|
||||
const dedicatedAcquisition = await manager.acquireDedicated({
|
||||
env: { PASEO_AGENT_ID: "parent" },
|
||||
});
|
||||
const existingAcquisition = manager.acquireExisting(dedicatedAcquisition.server.url);
|
||||
|
||||
expect(existingAcquisition?.server.url).toBe("http://127.0.0.1:4475");
|
||||
@@ -329,7 +348,7 @@ describe("OpenCodeServerManager generations", () => {
|
||||
test("acquireExisting returns null for unknown or dead server urls", async () => {
|
||||
const { manager, runtime } = createTestManager([4476]);
|
||||
|
||||
const acquisition = await manager.acquireDedicated({ PASEO_AGENT_ID: "parent" });
|
||||
const acquisition = await manager.acquireDedicated({ env: { PASEO_AGENT_ID: "parent" } });
|
||||
const url = acquisition.server.url;
|
||||
|
||||
expect(manager.acquireExisting("http://127.0.0.1:9999")).toBe(null);
|
||||
|
||||
@@ -7,6 +7,7 @@ import path from "node:path";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import { findExecutable } from "../../../../executable-resolution/executable-resolution.js";
|
||||
import type { LaunchWrap } from "../../../../utils/launch-wrap.js";
|
||||
import { spawnProcess, type SpawnProcessOptions } from "../../../../utils/spawn.js";
|
||||
import { terminateWithTreeKill, type ProcessTerminator } from "../../../../utils/tree-kill.js";
|
||||
import type { ManagedProcessRegistry } from "../../../managed-processes/managed-processes.js";
|
||||
@@ -36,10 +37,16 @@ export interface OpenCodeServerAcquisition {
|
||||
release: () => Promise<void>;
|
||||
}
|
||||
|
||||
/** How a session's own server starts: the session's environment, behind the session's wrap. */
|
||||
export interface OpenCodeDedicatedLaunch {
|
||||
env: Record<string, string>;
|
||||
wrap?: LaunchWrap;
|
||||
}
|
||||
|
||||
export interface OpenCodeServerManagerLike {
|
||||
acquireCurrent(signal?: AbortSignal): Promise<OpenCodeServerAcquisition>;
|
||||
acquireNew(signal?: AbortSignal): Promise<OpenCodeServerAcquisition>;
|
||||
acquireDedicated(env: Record<string, string>): Promise<OpenCodeServerAcquisition>;
|
||||
acquireDedicated(launch: OpenCodeDedicatedLaunch): Promise<OpenCodeServerAcquisition>;
|
||||
acquireExisting(url: string): OpenCodeServerAcquisition | null;
|
||||
shutdown(): Promise<void>;
|
||||
}
|
||||
@@ -180,8 +187,8 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike {
|
||||
return this.acquireServer(server);
|
||||
}
|
||||
|
||||
async acquireDedicated(env: Record<string, string>): Promise<OpenCodeServerAcquisition> {
|
||||
const server = await this.startServer({ launchEnv: env, epoch: this.epoch });
|
||||
async acquireDedicated(launch: OpenCodeDedicatedLaunch): Promise<OpenCodeServerAcquisition> {
|
||||
const server = await this.startServer({ launch, epoch: this.epoch });
|
||||
server.retired = true;
|
||||
this.retiredServers.add(server);
|
||||
const acquisition = this.acquireServer(server);
|
||||
@@ -325,7 +332,7 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike {
|
||||
}
|
||||
|
||||
private startServer(options: {
|
||||
launchEnv?: Record<string, string>;
|
||||
launch?: OpenCodeDedicatedLaunch;
|
||||
epoch: number;
|
||||
}): Promise<OpenCodeServerGeneration> {
|
||||
const start = this.spawnServer(options);
|
||||
@@ -336,10 +343,10 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike {
|
||||
}
|
||||
|
||||
private async spawnServer(options: {
|
||||
launchEnv?: Record<string, string>;
|
||||
launch?: OpenCodeDedicatedLaunch;
|
||||
epoch: number;
|
||||
}): Promise<OpenCodeServerGeneration> {
|
||||
const { launchEnv } = options;
|
||||
const launchEnv = options.launch?.env;
|
||||
const port = await this.portAllocator();
|
||||
const url = `http://127.0.0.1:${port}`;
|
||||
const launchPrefix = await this.resolveCommandPrefix();
|
||||
@@ -370,6 +377,7 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike {
|
||||
detached: process.platform !== "win32",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
baseEnv: environment,
|
||||
wrap: options.launch?.wrap,
|
||||
});
|
||||
const managedProcessRecord = this.recordManagedServerProcess({
|
||||
process: serverProcess,
|
||||
@@ -404,7 +412,7 @@ export class OpenCodeServerManager implements OpenCodeServerManagerLike {
|
||||
managedProcessRecord,
|
||||
};
|
||||
this.logger.info(
|
||||
{ ...generationLogContext(server), dedicated: launchEnv !== undefined },
|
||||
{ ...generationLogContext(server), dedicated: options.launch !== undefined },
|
||||
"OpenCode server generation started",
|
||||
);
|
||||
void managedProcessRecord.then((record) => {
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import type { OpenCodeServerAcquisition, OpenCodeServerManagerLike } from "./server-manager.js";
|
||||
import type {
|
||||
OpenCodeDedicatedLaunch,
|
||||
OpenCodeServerAcquisition,
|
||||
OpenCodeServerManagerLike,
|
||||
} from "./server-manager.js";
|
||||
|
||||
const events = {
|
||||
ready: async () => undefined,
|
||||
@@ -24,8 +28,8 @@ export class TestOpenCodeServerManager implements OpenCodeServerManagerLike {
|
||||
return this.recordAcquisition({ kind: "new" });
|
||||
}
|
||||
|
||||
async acquireDedicated(env: Record<string, string>): Promise<OpenCodeServerAcquisition> {
|
||||
return this.recordAcquisition({ kind: "dedicated", env });
|
||||
async acquireDedicated(launch: OpenCodeDedicatedLaunch): Promise<OpenCodeServerAcquisition> {
|
||||
return this.recordAcquisition({ kind: "dedicated", env: launch.env });
|
||||
}
|
||||
|
||||
acquireExisting(url: string): OpenCodeServerAcquisition | null {
|
||||
|
||||
+10
-3
@@ -1,7 +1,11 @@
|
||||
import type { OpencodeClient } from "@opencode-ai/sdk/v2/client";
|
||||
|
||||
import type { OpenCodeEventSourceInput } from "../event-consumer.js";
|
||||
import type { OpenCodeServerAcquisition, OpenCodeServerManagerLike } from "../server-manager.js";
|
||||
import type {
|
||||
OpenCodeDedicatedLaunch,
|
||||
OpenCodeServerAcquisition,
|
||||
OpenCodeServerManagerLike,
|
||||
} from "../server-manager.js";
|
||||
|
||||
interface OpenCodeResponse {
|
||||
data?: unknown;
|
||||
@@ -13,6 +17,7 @@ export class TestOpenCodeHarness implements OpenCodeServerManagerLike {
|
||||
readonly acquisitions: Array<{
|
||||
kind: "current" | "new" | "dedicated" | "existing";
|
||||
env?: Record<string, string>;
|
||||
wrap?: OpenCodeDedicatedLaunch["wrap"];
|
||||
url?: string;
|
||||
releaseCount: number;
|
||||
}> = [];
|
||||
@@ -51,8 +56,8 @@ export class TestOpenCodeHarness implements OpenCodeServerManagerLike {
|
||||
return this.recordAcquisition({ kind: "new" });
|
||||
}
|
||||
|
||||
async acquireDedicated(env: Record<string, string>): Promise<OpenCodeServerAcquisition> {
|
||||
return this.recordAcquisition({ kind: "dedicated", env });
|
||||
async acquireDedicated(launch: OpenCodeDedicatedLaunch): Promise<OpenCodeServerAcquisition> {
|
||||
return this.recordAcquisition({ kind: "dedicated", env: launch.env, wrap: launch.wrap });
|
||||
}
|
||||
|
||||
acquireExisting(url: string): OpenCodeServerAcquisition | null {
|
||||
@@ -62,12 +67,14 @@ export class TestOpenCodeHarness implements OpenCodeServerManagerLike {
|
||||
private recordAcquisition(input: {
|
||||
kind: "current" | "new" | "dedicated" | "existing";
|
||||
env?: Record<string, string>;
|
||||
wrap?: OpenCodeDedicatedLaunch["wrap"];
|
||||
url?: string;
|
||||
}): OpenCodeServerAcquisition {
|
||||
const acquisition = {
|
||||
kind: input.kind,
|
||||
releaseCount: 0,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
...(input.wrap ? { wrap: input.wrap } : {}),
|
||||
...(input.url ? { url: input.url } : {}),
|
||||
};
|
||||
this.acquisitions.push(acquisition);
|
||||
|
||||
@@ -6,6 +6,7 @@ import { describe, expect, test } from "vitest";
|
||||
import { createTestLogger } from "../../../../../test-utils/test-logger.js";
|
||||
import type { AgentStreamEvent } from "../../../agent-sdk-types.js";
|
||||
import { ProviderSubagentStore } from "../../../provider-subagents/store.js";
|
||||
import type { V2RuntimeAcquireOptions } from "./runtime.js";
|
||||
import { OpenCodeV2AgentClient } from "./agent.js";
|
||||
import { V2Harness } from "../test-utils/v2-harness.js";
|
||||
import type { V2Api } from "./api.js";
|
||||
@@ -1270,6 +1271,72 @@ describe("OpenCode v2 session lifecycle", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("asks the runtime for a server behind the wrap and the launch environment when creating and resuming", async () => {
|
||||
const servers = [new V2Harness(), new V2Harness()];
|
||||
const requests: unknown[] = [];
|
||||
const runtime = {
|
||||
acquire: async (input?: V2RuntimeAcquireOptions) => {
|
||||
requests.push(input?.dedicated);
|
||||
const server = servers[requests.length - 1];
|
||||
if (!server) throw new Error("No OpenCode test server left");
|
||||
return server.connection;
|
||||
},
|
||||
shutdown: async () => undefined,
|
||||
};
|
||||
const client = new OpenCodeV2AgentClient({ logger: createTestLogger(), runtime });
|
||||
const wrap = ["/opt/sandbox/bin/run", "--profile", "a b"] as const;
|
||||
const env = { SANDBOX_PROFILE: "agent" };
|
||||
const created = await client.createSession(
|
||||
{ provider: "opencode", cwd: "/tmp/project" },
|
||||
{ agentId: "agent", wrap, env },
|
||||
);
|
||||
try {
|
||||
// The created session's connection is live, and a wrapped resume still asks for its own.
|
||||
const resumed = await client.resumeSession(
|
||||
{
|
||||
provider: "opencode",
|
||||
sessionId: "session",
|
||||
nativeHandle: "session",
|
||||
metadata: { cwd: "/tmp/project" },
|
||||
},
|
||||
undefined,
|
||||
{ agentId: "agent", wrap, env },
|
||||
{ purpose: "history" },
|
||||
);
|
||||
await resumed.close();
|
||||
expect(requests).toEqual([
|
||||
{ wrap, env },
|
||||
{ wrap, env },
|
||||
]);
|
||||
} finally {
|
||||
await created.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("imports a wrapped session through one wrapped server, from the first session lookup", async () => {
|
||||
const server = new V2Harness();
|
||||
// Import restores the session's agent.
|
||||
server.api.session.switchAgent = async () => undefined;
|
||||
const requests: unknown[] = [];
|
||||
const runtime = {
|
||||
acquire: async (input?: V2RuntimeAcquireOptions) => {
|
||||
requests.push(input?.dedicated);
|
||||
return server.connection;
|
||||
},
|
||||
shutdown: async () => undefined,
|
||||
};
|
||||
const client = new OpenCodeV2AgentClient({ logger: createTestLogger(), runtime });
|
||||
const wrap = ["/opt/sandbox/bin/run", "--profile", "import"] as const;
|
||||
const env = { SANDBOX_PROFILE: "import" };
|
||||
const config = { provider: "opencode", cwd: "/tmp/project" } as const;
|
||||
const imported = await client.importSession(
|
||||
{ providerHandleId: "session", cwd: "/tmp/project" },
|
||||
{ config, storedConfig: config, launchContext: { agentId: "agent", wrap, env } },
|
||||
);
|
||||
await imported.session.close();
|
||||
expect(requests).toEqual([{ wrap, env }]);
|
||||
});
|
||||
|
||||
test("rejects MCP servers without the Paseo bridge before creating an OpenCode session", async () => {
|
||||
const harness = new V2Harness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
|
||||
@@ -36,10 +36,23 @@ import { importSessionFromPersistence } from "../../../provider-session-import.j
|
||||
|
||||
import type { OpenCodeBridge } from "../bridge.js";
|
||||
import { resolveOpenCodeHomeDir } from "../paths.js";
|
||||
import { V2Runtime, type V2Connection } from "./runtime.js";
|
||||
import { V2Runtime, type V2Connection, type V2DedicatedLaunch } from "./runtime.js";
|
||||
import type { OpenCodeServiceSelection } from "./service-selection.js";
|
||||
import { modelRef, modesFromV2, modelsFromV2 } from "./mapping.js";
|
||||
|
||||
/**
|
||||
* A wrapped launch gets a server of its own, started behind the wrap with the launch's environment,
|
||||
* so it never shares a server that runs outside its wrap.
|
||||
*/
|
||||
function dedicatedLaunch(launch: AgentLaunchContext | undefined): V2DedicatedLaunch | undefined {
|
||||
return launch?.wrap ? { wrap: launch.wrap, env: launch.env } : undefined;
|
||||
}
|
||||
interface ResumeTarget {
|
||||
handle: AgentPersistenceHandle;
|
||||
overrides: Partial<AgentSessionConfig> | undefined;
|
||||
launch: AgentLaunchContext | undefined;
|
||||
historyOnly: boolean;
|
||||
}
|
||||
interface PreparedLaunch {
|
||||
launch: AgentLaunchContext | undefined;
|
||||
/** The complete shell environment, when the launch sets one. */
|
||||
@@ -116,7 +129,7 @@ export class OpenCodeV2AgentClient implements AgentClient {
|
||||
): Promise<AgentSession> {
|
||||
const prepared = await this.prepareLaunch(config, launch, false);
|
||||
try {
|
||||
const connection = await this.runtime.acquire();
|
||||
const connection = await this.runtime.acquire({ dedicated: dedicatedLaunch(launch) });
|
||||
try {
|
||||
const info = await connection.client.session.create({
|
||||
location: { directory: config.cwd },
|
||||
@@ -146,6 +159,21 @@ export class OpenCodeV2AgentClient implements AgentClient {
|
||||
overrides?: Partial<AgentSessionConfig>,
|
||||
launch?: AgentLaunchContext,
|
||||
options?: AgentResumeSessionOptions,
|
||||
): Promise<AgentSession> {
|
||||
return this.resumeOn(
|
||||
async () => {
|
||||
// A live connection may run outside this launch's wrap, so a wrapped resume starts its own.
|
||||
const live = launch?.wrap
|
||||
? undefined
|
||||
: this.connections.get(handle.nativeHandle ?? handle.sessionId)?.retain();
|
||||
return live ?? (await this.runtime.acquire({ dedicated: dedicatedLaunch(launch) }));
|
||||
},
|
||||
{ handle, overrides, launch, historyOnly: options?.purpose === "history" },
|
||||
);
|
||||
}
|
||||
private async resumeOn(
|
||||
connect: () => Promise<V2Connection>,
|
||||
{ handle, overrides, launch, historyOnly }: ResumeTarget,
|
||||
): Promise<AgentSession> {
|
||||
const cwd = overrides?.cwd ?? handle.metadata?.cwd;
|
||||
if (typeof cwd !== "string")
|
||||
@@ -156,12 +184,9 @@ export class OpenCodeV2AgentClient implements AgentClient {
|
||||
provider: "opencode",
|
||||
cwd,
|
||||
};
|
||||
const historyOnly = options?.purpose === "history";
|
||||
const prepared = await this.prepareLaunch(config, launch, historyOnly);
|
||||
try {
|
||||
const connection =
|
||||
this.connections.get(handle.nativeHandle ?? handle.sessionId)?.retain() ??
|
||||
(await this.runtime.acquire());
|
||||
const connection = await connect();
|
||||
try {
|
||||
const info = await connection.client.session.get({
|
||||
sessionID: handle.nativeHandle ?? handle.sessionId,
|
||||
@@ -197,6 +222,7 @@ export class OpenCodeV2AgentClient implements AgentClient {
|
||||
servers,
|
||||
cwd: config.cwd,
|
||||
env: environment ?? createProviderEnv({ runtimeSettings: this.options.settings }),
|
||||
wrap: launch?.wrap,
|
||||
});
|
||||
return { launch, environment, mcp };
|
||||
}
|
||||
@@ -257,7 +283,7 @@ export class OpenCodeV2AgentClient implements AgentClient {
|
||||
mcp,
|
||||
unbind: releaseBindings,
|
||||
bindChild,
|
||||
acquire: () => this.runtime.acquire(),
|
||||
acquire: () => this.runtime.acquire({ dedicated: dedicatedLaunch(launch) }),
|
||||
moved,
|
||||
historyOnly,
|
||||
});
|
||||
@@ -312,14 +338,24 @@ export class OpenCodeV2AgentClient implements AgentClient {
|
||||
}
|
||||
}
|
||||
async importSession(input: ImportProviderSessionInput, context: ImportProviderSessionContext) {
|
||||
const connection = await this.runtime.acquire();
|
||||
// The lookup and the resume share one connection, so a wrapped import never starts a server
|
||||
// outside its wrap.
|
||||
const connection = await this.runtime.acquire({
|
||||
dedicated: dedicatedLaunch(context.launchContext),
|
||||
});
|
||||
try {
|
||||
const info = await connection.client.session.get({ sessionID: input.providerHandleId });
|
||||
return await importSessionFromPersistence({
|
||||
provider: "opencode",
|
||||
request: input,
|
||||
context,
|
||||
resumeSession: this.resumeSession.bind(this),
|
||||
resumeSession: (handle, overrides, launch) =>
|
||||
this.resumeOn(async () => connection.retain(), {
|
||||
handle,
|
||||
overrides,
|
||||
launch,
|
||||
historyOnly: false,
|
||||
}),
|
||||
config: {
|
||||
title: info.title,
|
||||
modeId: info.agent,
|
||||
|
||||
@@ -75,3 +75,76 @@ test("reports a bridge port change that has not been applied", async () => {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a wrapped caller gets its own helper behind the wrap, and other callers keep the shared one", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-opencode-wrap-"));
|
||||
const script = path.join(root, "server.cjs");
|
||||
const launcher = path.join(root, "launcher.cjs");
|
||||
const record = path.join(root, "argv.json");
|
||||
await writeFile(
|
||||
script,
|
||||
`
|
||||
const http = require('node:http');
|
||||
const server = http.createServer((_request, response) => {
|
||||
response.writeHead(200, { 'content-type': 'application/json' });
|
||||
response.end(JSON.stringify({ version: '2.0.10', pid: process.pid, urls: [], paths: { tmp: '/tmp' } }));
|
||||
});
|
||||
server.listen(0, '127.0.0.1', () => console.log('server listening on http://127.0.0.1:' + server.address().port));
|
||||
`,
|
||||
);
|
||||
await writeFile(
|
||||
launcher,
|
||||
`
|
||||
const [, , ...argv] = process.argv;
|
||||
// A launcher that needs its profile from the open hook's environment.
|
||||
if (!process.env.SANDBOX_PROFILE) process.exit(17);
|
||||
require('node:fs').writeFileSync(${JSON.stringify(record)}, JSON.stringify({ argv, profile: process.env.SANDBOX_PROFILE }));
|
||||
const child = require('node:child_process').spawn(argv[1], argv.slice(2), { stdio: 'inherit' });
|
||||
child.on('exit', (code) => process.exit(code ?? 1));
|
||||
`,
|
||||
);
|
||||
const runtime = new V2Runtime({
|
||||
logger: createTestLogger(),
|
||||
selection: { kind: "owned" },
|
||||
settings: { command: { mode: "replace", argv: [process.execPath, script] } },
|
||||
});
|
||||
try {
|
||||
const shared = await runtime.acquire();
|
||||
const wrapped = await runtime.acquire({
|
||||
dedicated: {
|
||||
wrap: [process.execPath, launcher, "--profile"],
|
||||
env: { SANDBOX_PROFILE: "agent" },
|
||||
},
|
||||
});
|
||||
const sharedAgain = await runtime.acquire();
|
||||
|
||||
const sharedPid = (await shared.client.server.info()).pid;
|
||||
expect((await wrapped.client.server.info()).pid).not.toBe(sharedPid);
|
||||
expect((await sharedAgain.client.server.info()).pid).toBe(sharedPid);
|
||||
const launched = JSON.parse(await readFile(record, "utf8"));
|
||||
expect(launched.profile).toBe("agent");
|
||||
expect(launched.argv.slice(0, 4)).toEqual(["--profile", process.execPath, script, "serve"]);
|
||||
|
||||
await wrapped.release();
|
||||
await expect(wrapped.exited).resolves.toBeInstanceOf(Error);
|
||||
await shared.release();
|
||||
await sharedAgain.release();
|
||||
} finally {
|
||||
await runtime.shutdown();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 15_000);
|
||||
|
||||
test("refuses to wrap a configured existing server", async () => {
|
||||
const runtime = new V2Runtime({
|
||||
logger: createTestLogger(),
|
||||
selection: { kind: "explicit", server: { url: "http://127.0.0.1:1" } },
|
||||
});
|
||||
try {
|
||||
await expect(
|
||||
runtime.acquire({ dedicated: { wrap: ["/opt/sandbox/bin/run"], env: {} } }),
|
||||
).rejects.toThrow("cannot start it behind a launch wrap");
|
||||
} finally {
|
||||
await runtime.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { V2Api } from "./api.js";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import type { Logger } from "pino";
|
||||
import type { LaunchWrap } from "../../../../../utils/launch-wrap.js";
|
||||
import { spawnProcess } from "../../../../../utils/spawn.js";
|
||||
import { terminateWithTreeKill } from "../../../../../utils/tree-kill.js";
|
||||
import {
|
||||
@@ -59,9 +60,17 @@ export interface V2RuntimeOptions {
|
||||
bridge?: OpenCodeBridge;
|
||||
}
|
||||
|
||||
/** A server started for one caller alone, behind its wrap and with its launch environment. */
|
||||
export interface V2DedicatedLaunch {
|
||||
wrap: LaunchWrap;
|
||||
env: Record<string, string> | undefined;
|
||||
}
|
||||
|
||||
export interface V2RuntimeAcquireOptions {
|
||||
fresh?: boolean;
|
||||
signal?: AbortSignal;
|
||||
/** Start a server for this caller alone. Other callers never share it. */
|
||||
dedicated?: V2DedicatedLaunch;
|
||||
}
|
||||
|
||||
// The runtime owns a credential for each subprocess; sessions only receive its authenticated client.
|
||||
@@ -92,8 +101,9 @@ export class V2Runtime {
|
||||
this.assertBridgePort();
|
||||
const selection = await raceProviderRefreshAbort(input.signal, this.selection);
|
||||
if (selection.kind === "explicit") this.assertExplicitConfiguration();
|
||||
this.current ??= this.startTracked();
|
||||
const pending = this.current;
|
||||
const pending = input.dedicated
|
||||
? this.startTracked(input.dedicated)
|
||||
: (this.current ??= this.startTracked());
|
||||
let generation: Generation;
|
||||
try {
|
||||
generation = await raceProviderRefreshAbort(input.signal, pending);
|
||||
@@ -179,8 +189,8 @@ export class V2Runtime {
|
||||
this.current = null;
|
||||
}
|
||||
|
||||
private startTracked(): Promise<Generation> {
|
||||
const pending = this.start();
|
||||
private startTracked(dedicated?: V2DedicatedLaunch): Promise<Generation> {
|
||||
const pending = this.start(dedicated);
|
||||
this.starts.add(pending);
|
||||
void pending.then(
|
||||
(generation) =>
|
||||
@@ -197,9 +207,14 @@ export class V2Runtime {
|
||||
return pending;
|
||||
}
|
||||
|
||||
private async start(): Promise<Generation> {
|
||||
private async start(dedicated: V2DedicatedLaunch | undefined): Promise<Generation> {
|
||||
const selection = await this.selection;
|
||||
if (selection.kind !== "owned") {
|
||||
if (dedicated && selection.kind === "explicit")
|
||||
throw new Error(
|
||||
"OpenCode is configured to use an existing server, so Paseo cannot start it behind a launch wrap",
|
||||
);
|
||||
// A discovered server is only a preference; a wrapped caller gets a server Paseo starts.
|
||||
if (selection.kind !== "owned" && !dedicated) {
|
||||
const generation: Generation = {
|
||||
...(await connectSharedService(selection, this.options)),
|
||||
users: 0,
|
||||
@@ -220,6 +235,7 @@ export class V2Runtime {
|
||||
const configured = {
|
||||
...(inheritedConfig ? { OPENCODE_CONFIG_CONTENT: inheritedConfig } : {}),
|
||||
...settings?.env,
|
||||
...dedicated?.env,
|
||||
};
|
||||
const bridge = this.options.bridge;
|
||||
const plugin = bridge
|
||||
@@ -240,6 +256,7 @@ export class V2Runtime {
|
||||
cwd,
|
||||
detached: globalThis.process.platform !== "win32",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
wrap: dedicated?.wrap,
|
||||
...createProviderEnvSpec({
|
||||
runtimeSettings: settings,
|
||||
overlays: [{ ...decorated, OPENCODE_PASSWORD: password }],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { McpServerConfig } from "../../../agent-sdk-types.js";
|
||||
import { connectMcpServer, type McpClientConnection } from "../../../mcp-client-connection.js";
|
||||
import type { LaunchWrap } from "../../../../../utils/launch-wrap.js";
|
||||
import type { PaseoToolResult } from "../../../tools/types.js";
|
||||
import type { OpenCodeBridgeMcpTool } from "../bridge.js";
|
||||
|
||||
@@ -22,6 +23,8 @@ interface ConnectSessionMcpInput {
|
||||
cwd: string;
|
||||
/** The agent's complete launch environment, which stdio servers inherit. */
|
||||
env: NodeJS.ProcessEnv;
|
||||
/** The agent's wrap, which stdio servers run behind. */
|
||||
wrap?: LaunchWrap;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -44,6 +47,7 @@ export class SessionMcp {
|
||||
config,
|
||||
cwd: input.cwd,
|
||||
env: input.env,
|
||||
wrap: input.wrap,
|
||||
clientName: "paseo-opencode",
|
||||
});
|
||||
return { name, connection };
|
||||
|
||||
@@ -498,6 +498,7 @@ function buildResumeStartInput(input: {
|
||||
return {
|
||||
cwd: input.processCwd,
|
||||
env: input.launchContext?.env,
|
||||
wrap: input.launchContext?.wrap,
|
||||
session: input.sessionFile,
|
||||
thinkingOptionId: normalizePiThinkingOption(input.resumeConfig.thinkingOptionId) ?? undefined,
|
||||
mcpConfigPath: input.mcpConfigFile?.path,
|
||||
@@ -2660,11 +2661,13 @@ export class PiRpcAgentClient implements AgentClient {
|
||||
): Promise<AgentSession> {
|
||||
const providerOptions = PiProviderOptionsSchema.parse(config.providerOptions ?? {});
|
||||
const runtime = this.resolveRuntime(providerOptions.rpcTimeoutMs);
|
||||
const mcpEnv = {
|
||||
...this.runtimeSettings?.env,
|
||||
...launchContext?.env,
|
||||
};
|
||||
const mcp = await this.prepareMcpInjection(config.cwd, config.mcpServers, mcpEnv, runtime);
|
||||
const { env, wrap } = launchContext ?? {};
|
||||
const mcpEnv = { ...this.runtimeSettings?.env, ...env };
|
||||
const mcp = await this.prepareMcpInjection(
|
||||
{ cwd: config.cwd, env: mcpEnv, wrap },
|
||||
config.mcpServers,
|
||||
runtime,
|
||||
);
|
||||
const mcpConfigFile = mcp?.kind === "adapter" ? mcp.configFile : null;
|
||||
const paseoExtension = createPiPaseoExtensionFile({
|
||||
systemPrompt: composeAgentSystemPrompt(config),
|
||||
@@ -2677,7 +2680,8 @@ export class PiRpcAgentClient implements AgentClient {
|
||||
model: config.model,
|
||||
thinkingOptionId: normalizePiThinkingOption(config.thinkingOptionId) ?? undefined,
|
||||
noSession: config.internal === true,
|
||||
env: launchContext?.env,
|
||||
env,
|
||||
wrap,
|
||||
mcpConfigPath: mcpConfigFile?.path,
|
||||
extensionPaths: paseoExtension ? [paseoExtension.path] : undefined,
|
||||
});
|
||||
@@ -2729,9 +2733,8 @@ export class PiRpcAgentClient implements AgentClient {
|
||||
...launchContext?.env,
|
||||
};
|
||||
const mcp = await this.prepareMcpInjection(
|
||||
processCwd,
|
||||
{ cwd: processCwd, env: mcpEnv, wrap: launchContext?.wrap },
|
||||
resumeConfig.config.mcpServers,
|
||||
mcpEnv,
|
||||
runtime,
|
||||
);
|
||||
const mcpConfigFile = mcp?.kind === "adapter" ? mcp.configFile : null;
|
||||
@@ -2930,16 +2933,17 @@ export class PiRpcAgentClient implements AgentClient {
|
||||
return this.runtime ?? createRuntime(this.logger, this.runtimeSettings, rpcTimeoutMs);
|
||||
}
|
||||
|
||||
/** `probe` starts the Pi process that detects MCP support, as the agent's own process starts. */
|
||||
private async prepareMcpInjection(
|
||||
cwd: string,
|
||||
probe: Pick<PiStartSessionInput, "cwd" | "env" | "wrap">,
|
||||
servers: Record<string, McpServerConfig> | undefined,
|
||||
env: Record<string, string> | undefined,
|
||||
runtime: PiRuntime,
|
||||
): Promise<PiMcpInjection | null> {
|
||||
if (!servers || Object.keys(servers).length === 0) {
|
||||
return null;
|
||||
}
|
||||
const mcpSupport = await this.detectMcpSupport(cwd, env, runtime);
|
||||
const { env } = probe;
|
||||
const mcpSupport = await this.detectMcpSupport(probe, runtime);
|
||||
if (mcpSupport === "builtin") {
|
||||
return { kind: "builtin", servers: toPiBuiltinMcpServers(servers) };
|
||||
}
|
||||
@@ -2953,12 +2957,11 @@ export class PiRpcAgentClient implements AgentClient {
|
||||
}
|
||||
|
||||
private async detectMcpSupport(
|
||||
cwd: string,
|
||||
env: Record<string, string> | undefined,
|
||||
probe: Pick<PiStartSessionInput, "cwd" | "env" | "wrap">,
|
||||
runtime: PiRuntime,
|
||||
): Promise<PiMcpInjection["kind"] | null> {
|
||||
const runtimeSession = await runtime.startSession({ cwd, env }).catch((error) => {
|
||||
this.logger.debug({ err: error, cwd }, "Pi MCP probe failed to start");
|
||||
const runtimeSession = await runtime.startSession(probe).catch((error) => {
|
||||
this.logger.debug({ err: error, cwd: probe.cwd }, "Pi MCP probe failed to start");
|
||||
return null;
|
||||
});
|
||||
if (!runtimeSession) {
|
||||
@@ -2971,7 +2974,7 @@ export class PiRpcAgentClient implements AgentClient {
|
||||
}
|
||||
return commands.some(isPiBuiltinMcpCommand) ? "builtin" : null;
|
||||
} catch (error) {
|
||||
this.logger.debug({ err: error, cwd }, "Pi MCP probe failed");
|
||||
this.logger.debug({ err: error, cwd: probe.cwd }, "Pi MCP probe failed");
|
||||
return null;
|
||||
} finally {
|
||||
await runtimeSession.close().catch(() => undefined);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { mkdir, mkdtemp, writeFile, readFile, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import type { ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { EventEmitter } from "node:events";
|
||||
@@ -167,6 +168,63 @@ describe("PiCliRuntime", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("starts Pi behind the session's launch wrap and talks to it through the wrap", async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "pi-launch-wrap-"));
|
||||
try {
|
||||
const fakePi = path.join(root, "fake-pi.mjs");
|
||||
await writeFile(
|
||||
fakePi,
|
||||
[
|
||||
'import { createInterface } from "node:readline";',
|
||||
'createInterface({ input: process.stdin }).on("line", (line) => {',
|
||||
" const command = JSON.parse(line);",
|
||||
' const data = { sessionId: "wrapped", argv: process.argv.slice(2) };',
|
||||
' process.stdout.write(JSON.stringify({ type: "response", id: command.id, command: command.type, success: true, data }) + "\\n");',
|
||||
"});",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
const launcher = path.join(root, "launcher.mjs");
|
||||
await writeFile(
|
||||
launcher,
|
||||
[
|
||||
'import { spawn } from "node:child_process";',
|
||||
'import { writeFileSync } from "node:fs";',
|
||||
"const [command, ...args] = process.argv.slice(2);",
|
||||
'writeFileSync(new URL("./wrapped.json", import.meta.url), JSON.stringify([command, ...args]));',
|
||||
'const child = spawn(command, args, { stdio: "inherit" });',
|
||||
'child.on("exit", (code) => process.exit(code ?? 1));',
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
const runtime = new PiCliRuntime({
|
||||
logger: pino({ level: "silent" }),
|
||||
command: [process.execPath, fakePi],
|
||||
});
|
||||
|
||||
const session = await runtime.startSession({
|
||||
cwd: root,
|
||||
wrap: [process.execPath, launcher],
|
||||
});
|
||||
try {
|
||||
await expect(session.getState()).resolves.toMatchObject({
|
||||
sessionId: "wrapped",
|
||||
argv: ["--mode", "rpc"],
|
||||
});
|
||||
expect(JSON.parse(await readFile(path.join(root, "wrapped.json"), "utf8"))).toEqual([
|
||||
process.execPath,
|
||||
fakePi,
|
||||
"--mode",
|
||||
"rpc",
|
||||
]);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("passes an MCP config path to Pi", async () => {
|
||||
const child = createPiChild();
|
||||
replyToCommands(child, () => ({}));
|
||||
|
||||
@@ -65,6 +65,7 @@ export class PiCliRuntime implements PiRuntime {
|
||||
args,
|
||||
cwd: launch.cwd,
|
||||
env: launch.env,
|
||||
wrap: launch.wrap,
|
||||
};
|
||||
const spawn = this.spawnProcess;
|
||||
const processOptions = {
|
||||
|
||||
@@ -13,6 +13,8 @@ export interface PiRuntimeLaunch {
|
||||
cwd: string;
|
||||
argv: string[];
|
||||
env?: Record<string, string>;
|
||||
/** Start Pi as `[...wrap, ...argv]`. */
|
||||
wrap?: readonly [string, ...string[]];
|
||||
protocolMode?: "rpc" | "rpc-ui";
|
||||
model?: string;
|
||||
thinkingOptionId?: string;
|
||||
@@ -28,6 +30,8 @@ export interface PiStartSessionInput {
|
||||
cwd: string;
|
||||
signal?: AbortSignal;
|
||||
env?: Record<string, string>;
|
||||
/** The agent's launch wrap; every Pi process started for the agent runs behind it. */
|
||||
wrap?: readonly [string, ...string[]];
|
||||
protocolMode?: "rpc" | "rpc-ui";
|
||||
model?: string;
|
||||
thinkingOptionId?: string;
|
||||
@@ -102,6 +106,7 @@ export function buildPiLaunch(input: {
|
||||
...input.session.env,
|
||||
}
|
||||
: undefined,
|
||||
wrap: input.session.wrap,
|
||||
model: input.session.model,
|
||||
thinkingOptionId: input.session.thinkingOptionId,
|
||||
protocolMode,
|
||||
|
||||
@@ -161,6 +161,7 @@ export interface PaseoToolHostDependencies {
|
||||
workspaceScripts?: Pick<WorkspaceScriptsService, "list" | "launch" | "stop">;
|
||||
markWorkspaceArchiving?: ArchiveDependencies["markWorkspaceArchiving"];
|
||||
clearWorkspaceArchiving?: ArchiveDependencies["clearWorkspaceArchiving"];
|
||||
lifecycle?: ArchiveDependencies["lifecycle"];
|
||||
createPaseoWorktree?: CreatePaseoWorktreeWorkflowFn;
|
||||
// Mints a fresh directory workspace for a cwd and returns its id.
|
||||
ensureWorkspaceForCreate?: (
|
||||
@@ -2565,6 +2566,7 @@ function createToolCatalog(
|
||||
const workspaceId = await resolveTerminalWorkspaceId(resolvedCwd);
|
||||
|
||||
const terminal = await terminalManager.createTerminal({
|
||||
origin: { source: "agent" },
|
||||
cwd: resolvedCwd,
|
||||
workspaceId,
|
||||
...(name?.trim() ? { name: name.trim() } : {}),
|
||||
@@ -3463,6 +3465,7 @@ function archiveWorktreeDependencies(
|
||||
throw new Error("Checkout trust lookup is required to archive worktrees");
|
||||
}
|
||||
return {
|
||||
lifecycle: options.lifecycle ?? null,
|
||||
paseoHome: options.paseoHome,
|
||||
paseoWorktreesBaseRoot: options.worktreesRoot,
|
||||
worktreeManagers: options.worktreeManagers,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { PluginLifecycle } from "../plugins/lifecycle/index.js";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import type { AgentManager } from "../agent/agent-manager.js";
|
||||
@@ -44,6 +45,7 @@ export interface AutoArchiveArchiveOptions {
|
||||
markWorkspaceArchiving: (workspaceIds: Iterable<string>, archivingAt: string) => void;
|
||||
clearWorkspaceArchiving: (workspaceIds: Iterable<string>) => void;
|
||||
emitWorkspaceUpdatesForWorkspaceIds: (workspaceIds: Iterable<string>) => Promise<void>;
|
||||
lifecycle: Pick<PluginLifecycle, "before"> | null;
|
||||
}
|
||||
|
||||
export interface ArchiveIfSafeDependencies {
|
||||
@@ -104,6 +106,7 @@ export async function archiveIfSafe(input: {
|
||||
|
||||
await deps.archiveByScope(
|
||||
{
|
||||
lifecycle: options.lifecycle,
|
||||
paseoHome: options.paseoHome,
|
||||
paseoWorktreesBaseRoot: options.paseoWorktreesBaseRoot,
|
||||
worktreeManagers: options.worktreeManagers,
|
||||
|
||||
@@ -192,6 +192,7 @@ import { setupAutoArchiveOnMerge } from "./auto-archive-on-merge/index.js";
|
||||
import { wrapSessionMessage, type SessionOutboundMessage } from "./messages.js";
|
||||
import type { TerminalManager } from "../terminal/terminal-manager.js";
|
||||
import { startWorkerTerminalManager } from "../terminal/worker-terminal-manager.js";
|
||||
import { withTerminalCreateHook } from "../terminal/terminal-create-hook.js";
|
||||
import { applyTerminalAgentHookSetting } from "../terminal/agent-hooks/terminal-agent-hook-setting.js";
|
||||
import { loadOrCreateDaemonKeyPair } from "./daemon-keypair.js";
|
||||
import { createRelayRuntime, type RelayRuntime } from "./relay-runtime.js";
|
||||
@@ -739,13 +740,16 @@ export async function createPaseoDaemon(
|
||||
});
|
||||
let boundListenTarget: ListenTarget | null = null;
|
||||
let workspaceRegistry: FileBackedWorkspaceRegistry | null = null;
|
||||
const terminalManager = await startWorkerTerminalManager({
|
||||
paseoHome: config.paseoHome,
|
||||
paseoVersion: daemonVersion,
|
||||
logger,
|
||||
getTerminalActivityUrl: () => createTerminalActivityUrl(boundListenTarget),
|
||||
eagerLaunch: !dependencies.lazyTerminalWorker,
|
||||
});
|
||||
const terminalManager = withTerminalCreateHook(
|
||||
await startWorkerTerminalManager({
|
||||
paseoHome: config.paseoHome,
|
||||
paseoVersion: daemonVersion,
|
||||
logger,
|
||||
getTerminalActivityUrl: () => createTerminalActivityUrl(boundListenTarget),
|
||||
eagerLaunch: !dependencies.lazyTerminalWorker,
|
||||
}),
|
||||
pluginRuntime,
|
||||
);
|
||||
applyTerminalAgentHookSetting({ store: daemonConfigStore, logger });
|
||||
|
||||
const serviceProxyPublicBaseUrl = config.serviceProxy?.publicBaseUrl
|
||||
@@ -1235,6 +1239,7 @@ export async function createPaseoDaemon(
|
||||
});
|
||||
|
||||
setupAutoArchiveOnMerge({
|
||||
lifecycle: pluginRuntime,
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
@@ -1266,6 +1271,7 @@ export async function createPaseoDaemon(
|
||||
) => {
|
||||
return createPaseoWorktreeWorkflow(
|
||||
{
|
||||
lifecycle: pluginRuntime,
|
||||
paseoHome: config.paseoHome,
|
||||
worktreesRoot: config.worktreesRoot,
|
||||
createPaseoWorktree: async (workflowInput, workflowOptions) => {
|
||||
@@ -1330,6 +1336,7 @@ export async function createPaseoDaemon(
|
||||
const archiveWorkspaceByIdExternal = (workspaceId: string, requestId: string) =>
|
||||
archiveByScope(
|
||||
{
|
||||
lifecycle: pluginRuntime,
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
@@ -1357,6 +1364,7 @@ export async function createPaseoDaemon(
|
||||
{ scope: { kind: "workspace", workspaceId }, requestId },
|
||||
);
|
||||
const hubAgentLifecycle = new CreateAgentLifecycleDispatch({
|
||||
lifecycle: pluginRuntime,
|
||||
paseoHome: config.paseoHome,
|
||||
worktreesRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
@@ -1461,6 +1469,7 @@ export async function createPaseoDaemon(
|
||||
const archiveScheduleWorkspaceExternal = async (workspaceId: string) => {
|
||||
await archiveByScope(
|
||||
{
|
||||
lifecycle: pluginRuntime,
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
@@ -1624,6 +1633,7 @@ export async function createPaseoDaemon(
|
||||
listActiveWorkspaces: listActiveWorkspacesExternal,
|
||||
archiveWorkspaceRecord: (workspaceId, archivedAt) =>
|
||||
archiveWorkspaceRecordExternal(workspaceId, undefined, archivedAt),
|
||||
lifecycle: pluginRuntime,
|
||||
emitWorkspaceUpdatesForWorkspaceIds: emitWorkspaceUpdatesExternal,
|
||||
workspaceRegistry,
|
||||
projectRegistry,
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { PrepareWorktreeLifecycleCommand } from "../utils/worktree.js";
|
||||
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
|
||||
|
||||
/** Runs plugins' `command.run.before` hooks for each setup or teardown command. */
|
||||
export function commandRunHook(
|
||||
lifecycle: Pick<PluginLifecycle, "before"> | null,
|
||||
scope: { workspaceId: string | null; cwd: string; purpose: "setup" | "teardown" },
|
||||
): PrepareWorktreeLifecycleCommand | undefined {
|
||||
if (!lifecycle) return undefined;
|
||||
return async ({ command, env }) => {
|
||||
const request = await lifecycle.before("command.run.before", { ...scope, command, env });
|
||||
return { env: request.env, ...(request.wrap ? { wrap: request.wrap } : {}) };
|
||||
};
|
||||
}
|
||||
@@ -364,13 +364,20 @@ test("terminal collection reports workspace script ownership after runtime regis
|
||||
},
|
||||
});
|
||||
try {
|
||||
expect((await client.startWorkspaceScript(workspaceId, "sleeper")).error).toBeNull();
|
||||
const started = await client.startWorkspaceScript(workspaceId, "sleeper");
|
||||
expect(started.error).toBeNull();
|
||||
const terminalId = started.terminalId;
|
||||
await expect
|
||||
.poll(() =>
|
||||
terminals.some((terminal) => terminal.workspaceId === workspaceId && terminal.isScript),
|
||||
.poll(
|
||||
() =>
|
||||
terminals.map((terminal) => ({
|
||||
id: terminal.id,
|
||||
workspaceId: terminal.workspaceId,
|
||||
isScript: terminal.isScript,
|
||||
})),
|
||||
{ timeout: 10_000 },
|
||||
)
|
||||
.toBe(true);
|
||||
const terminalId = terminals.find((terminal) => terminal.workspaceId === workspaceId)!.id;
|
||||
.toContainEqual({ id: terminalId, workspaceId, isScript: true });
|
||||
const pidFile = path.join(cwd, "sleeper.pid");
|
||||
await expect
|
||||
.poll(async () => Number(await readFile(pidFile, "utf8")), { timeout: 10_000 })
|
||||
|
||||
@@ -140,3 +140,52 @@ export default function contribute(server) {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("a create hook reads launch-wrap support for a plugin provider that never connected", async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-launch-wrap-snapshot-"));
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
daemonVersion: "0.14.0-beta.2",
|
||||
agentClients: { codex: createTestAgentClient("codex") },
|
||||
mcpEnabled: false,
|
||||
});
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
appVersion: "0.14.0-beta.2",
|
||||
});
|
||||
try {
|
||||
await writeFile(
|
||||
path.join(directory, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: "launch-wrap-snapshot", requirements: { paseo: ">=0.14.0-beta.2" } }),
|
||||
);
|
||||
// connect() always fails, so nothing negotiated over a connection can reach the snapshot.
|
||||
await writeFile(
|
||||
path.join(directory, "index.server.ts"),
|
||||
`import { runAcpProvider } from "@getpaseo/plugin/server/acp";
|
||||
let connects = 0;
|
||||
export default function contribute(server) {
|
||||
const acp = runAcpProvider({ id: "wrap-acp", label: "Wrap ACP", command: [process.execPath, "--version"] });
|
||||
server.registerProvider({ ...acp, connect() { connects += 1; throw new Error("not connected in this test"); } });
|
||||
return server.before("agent.create", async ({ request }, { paseo }) => {
|
||||
const snapshot = await paseo.providers.snapshot();
|
||||
const entry = snapshot.entries.find((candidate) => candidate.provider === "wrap-acp");
|
||||
return { ...request, metadata: { ...request.metadata, launchWrapProbe: { launchWrap: entry?.launchWrap ?? null, status: entry?.status ?? null, connects } } };
|
||||
});
|
||||
}
|
||||
`,
|
||||
);
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(directory);
|
||||
const agent = await client.createAgent({ provider: "codex", cwd: directory });
|
||||
expect(daemon.daemon.agentManager.getAgent(agent.id)?.metadata.launchWrapProbe).toMatchObject({
|
||||
launchWrap: true,
|
||||
connects: 0,
|
||||
});
|
||||
await client.archiveAgent(agent.id);
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
@@ -46,6 +46,7 @@ function recordingProvider(native: boolean, callbacks: TestAgentClientOptions =
|
||||
const provider: AgentClient = {
|
||||
provider: inner.provider,
|
||||
capabilities: { ...inner.capabilities, supportsNativePaseoTools: native },
|
||||
supportsLaunchWrap: true,
|
||||
createSession: async (config, context, options) => {
|
||||
launches.push({ config, context });
|
||||
return inner.createSession(config, context, options);
|
||||
@@ -587,6 +588,44 @@ test("an idle agent reopens once before its next prompt after a session-hook plu
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
function wrapPluginSource(profile: string) {
|
||||
return `
|
||||
export default function contribute(server) {
|
||||
server.addHook("agent.open.before", async ({ request }) => ({
|
||||
...request,
|
||||
wrap: [${JSON.stringify(process.execPath)}, "--sandbox-profile", ${JSON.stringify(profile)}],
|
||||
}));
|
||||
return () => {};
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
test("a plugin reload that changes the launch wrap reopens the idle session with the new wrap", async () => {
|
||||
const h = await setup(false, wrapPluginSource("first"));
|
||||
try {
|
||||
const a = await h.create();
|
||||
expect(h.launches.at(-1)!.context?.wrap).toEqual([
|
||||
process.execPath,
|
||||
"--sandbox-profile",
|
||||
"first",
|
||||
]);
|
||||
await writeFile(
|
||||
path.join(h.directory, "tools-test", "index.server.ts"),
|
||||
wrapPluginSource("second"),
|
||||
);
|
||||
await h.client.reloadPlugin("tools-test");
|
||||
await sendAndFinish(h, a.id, "after reload");
|
||||
expect(h.launches).toHaveLength(2);
|
||||
expect(h.launches.at(-1)!.context?.wrap).toEqual([
|
||||
process.execPath,
|
||||
"--sandbox-profile",
|
||||
"second",
|
||||
]);
|
||||
} finally {
|
||||
await h.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("a busy agent is steered after plugin reload and reopens only at its next idle prompt", async () => {
|
||||
let release!: () => void;
|
||||
const blocked = new Promise<void>((resolve) => {
|
||||
|
||||
@@ -19,6 +19,7 @@ import pino from "pino";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { DaemonConfigStore } from "../daemon-config-store.js";
|
||||
import { PluginService } from "./index.js";
|
||||
import { PluginAgentClientRegistry } from "../agent/plugin-provider.js";
|
||||
import { BuiltinPluginLoader } from "./builtin/index.js";
|
||||
import { ManagedPluginSources } from "./managed-source.js";
|
||||
import type { PluginProviderMetadata } from "./plugin-process-protocol.js";
|
||||
@@ -583,6 +584,35 @@ describe("PluginService", () => {
|
||||
await service.stopAllPlugins();
|
||||
});
|
||||
|
||||
it("carries a provider's launch-wrap declaration from the plugin process to its definition", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-"));
|
||||
roots.push(home);
|
||||
const directory = await createPlugin(
|
||||
"provider-launch-wrap",
|
||||
`import { runAcpProvider } from "@getpaseo/plugin/server/acp";
|
||||
export default function contribute(server) {
|
||||
server.registerProvider(runAcpProvider({ id: "wrapped-agent", label: "Wrapped", command: ["agent", "acp"] }));
|
||||
server.registerProvider(runAcpProvider({ id: "connector-agent", label: "Connector", connector() { throw new Error("not opened by this test"); } }));
|
||||
return () => {};
|
||||
}`,
|
||||
);
|
||||
const service = createService(home);
|
||||
|
||||
await service.start();
|
||||
try {
|
||||
await service.installDirectory({ path: directory });
|
||||
const registrations = service.getProviderRegistrations();
|
||||
expect(registrations.find(({ id }) => id === "wrapped-agent")?.launchWrap).toBe(true);
|
||||
expect(registrations.find(({ id }) => id === "connector-agent")?.launchWrap).toBeUndefined();
|
||||
const registry = new PluginAgentClientRegistry(pino({ level: "silent" }));
|
||||
registry.replace(registrations);
|
||||
expect(registry.definitions()["wrapped-agent"]?.supportsLaunchWrap).toBe(true);
|
||||
expect(registry.definitions()["connector-agent"]?.supportsLaunchWrap).toBe(false);
|
||||
} finally {
|
||||
await service.stopAllPlugins();
|
||||
}
|
||||
});
|
||||
|
||||
it("publishes provider registrations only while their plugin is running", async () => {
|
||||
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-home-"));
|
||||
roots.push(home);
|
||||
|
||||
@@ -793,6 +793,7 @@ export class PluginService {
|
||||
description: provider.description,
|
||||
docsUrl: provider.docsUrl,
|
||||
command: provider.command,
|
||||
launchWrap: provider.launchWrap,
|
||||
requiresConfiguration: provider.requiresConfiguration,
|
||||
status: provider.hasStatus
|
||||
? (request) => {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, onTestFinished, test } from "vitest";
|
||||
import { createPaseoClient } from "@getpaseo/client";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { resolveDaemonVersion } from "../daemon-version.js";
|
||||
@@ -523,6 +524,7 @@ test("agent creation hooks change the provider and environment before the sessio
|
||||
acknowledgeClose: true,
|
||||
hooks: `
|
||||
server.addHook("agent.create.before", async ({ request }) => {
|
||||
console.log(JSON.stringify({ hook: "agent.create.before", workspaceId: request.workspaceId }));
|
||||
return { ...request, config: { ...request.config, provider: "${PROVIDER_ID}", model: "shutdown-model" }, env: { ...request.env, HOOK_CREATE: "created" } };
|
||||
});
|
||||
server.addHook("agent.open.before", async ({ request }) => {
|
||||
@@ -554,9 +556,14 @@ test("agent creation hooks change the provider and environment before the sessio
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(pluginDirectory);
|
||||
await client.installDirectoryPlugin(extraPlugin);
|
||||
const workspace = await client.createWorkspace({
|
||||
source: { kind: "directory", path: directory },
|
||||
});
|
||||
const workspaceId = workspace.workspace!.id;
|
||||
const agent = await client.createAgent({
|
||||
provider: "claude",
|
||||
cwd: directory,
|
||||
workspaceId,
|
||||
title: "Hook test",
|
||||
systemPrompt: "Saved instructions",
|
||||
});
|
||||
@@ -577,6 +584,7 @@ test("agent creation hooks change the provider and environment before the sessio
|
||||
});
|
||||
})
|
||||
.toMatchObject([
|
||||
{ hook: "agent.create.before", workspaceId },
|
||||
{
|
||||
hook: "agent.open.before",
|
||||
request: { agentId: agent.id, env: { HOOK_CREATE: "created" } },
|
||||
@@ -617,6 +625,226 @@ test("agent creation hooks change the provider and environment before the sessio
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("plugins wrap or refuse terminals and worktree setup and teardown commands", async () => {
|
||||
const root = await realpath(await mkdtemp(path.join(tmpdir(), "paseo-terminal-hooks-")));
|
||||
const repository = path.join(root, "repository");
|
||||
const pluginDirectory = path.join(root, "plugin");
|
||||
const hookLog = path.join(root, "hooks.jsonl");
|
||||
// Spaces and cmd.exe syntax in the sandbox's install path, as in `C:\Program Files (x86)`.
|
||||
const sandboxDirectory = path.join(root, "sandbox launcher (x86)");
|
||||
await mkdir(sandboxDirectory);
|
||||
const launchLog = path.join(sandboxDirectory, "launches.jsonl");
|
||||
const launcher = path.join(sandboxDirectory, "launcher.cjs");
|
||||
// The sandbox stand-in: records the argv after its own two, marks the environment, runs the rest.
|
||||
await writeFile(
|
||||
launcher,
|
||||
`const { appendFileSync } = require("node:fs");
|
||||
const { spawn } = require("node:child_process");
|
||||
const [log, tag, command, ...args] = process.argv.slice(2);
|
||||
appendFileSync(log, JSON.stringify({ tag, command, args }) + "\\n");
|
||||
const child = spawn(command, args, { stdio: "inherit", env: { ...process.env, WRAPPED: tag } });
|
||||
for (const signal of ["SIGTERM", "SIGHUP", "SIGINT"]) process.on(signal, () => child.kill(signal));
|
||||
child.on("exit", (code) => process.exit(code ?? 1));
|
||||
`,
|
||||
);
|
||||
// Windows sandboxes ship a `.cmd` entry point, which runs through cmd.exe and forwards `%*`.
|
||||
const commandScript = path.join(sandboxDirectory, "sandbox run.cmd");
|
||||
await writeFile(commandScript, `@"${process.execPath}" "${launcher}" %*\r\n`);
|
||||
const wrapPrefix = process.platform === "win32" ? [commandScript] : [process.execPath, launcher];
|
||||
// Node one-liners read the environment the same way under bash, PowerShell, and cmd.exe.
|
||||
const setupCommand = `node -e "require('fs').writeFileSync('setup.txt', 'setup:' + process.env.HOOK_MARK + ':' + process.env.WRAPPED)"`;
|
||||
const teardownCommand = `node -e "require('fs').writeFileSync(require('path').join(process.env.PASEO_SOURCE_CHECKOUT_PATH, '..', 'teardown.txt'), 'teardown:' + process.env.HOOK_MARK + ':' + process.env.WRAPPED)"`;
|
||||
const scriptCommand = `node -e "console.log('script:' + process.env.HOOK_MARK + ':' + process.env.WRAPPED)"`;
|
||||
execFileSync("git", ["init", "-b", "main", repository], { stdio: "pipe" });
|
||||
await writeFile(
|
||||
path.join(repository, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: { setup: setupCommand, teardown: teardownCommand },
|
||||
scripts: { greet: { command: scriptCommand } },
|
||||
}),
|
||||
);
|
||||
execFileSync("git", ["add", "paseo.json"], { cwd: repository, stdio: "pipe" });
|
||||
execFileSync(
|
||||
"git",
|
||||
[
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
].concat(["commit", "-m", "initial"]),
|
||||
{ cwd: repository, stdio: "pipe" },
|
||||
);
|
||||
await mkdir(pluginDirectory);
|
||||
await writeFile(
|
||||
path.join(pluginDirectory, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: "terminal-hooks", requirements: { paseo: ">=0.8.0" } }),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(pluginDirectory, "index.server.ts"),
|
||||
`
|
||||
import { appendFile } from "node:fs/promises";
|
||||
const log = (entry) => appendFile(${JSON.stringify(hookLog)}, JSON.stringify(entry) + "\\n");
|
||||
const wrap = (tag) => [...${JSON.stringify(wrapPrefix)}, ${JSON.stringify(launchLog)}, tag];
|
||||
export default function contribute(server) {
|
||||
server.addHook("terminal.create.before", async ({ request }) => {
|
||||
await log({ hook: "terminal", request });
|
||||
if (request.name === "Refused") throw new Error("terminals named Refused stay closed");
|
||||
return {
|
||||
...request,
|
||||
env: { ...request.env, HOOK_MARK: request.source + ":" + request.workspaceId },
|
||||
wrap: wrap("terminal"),
|
||||
};
|
||||
});
|
||||
server.addHook("command.run.before", async ({ request }) => {
|
||||
await log({ hook: "command", request });
|
||||
return {
|
||||
...request,
|
||||
env: { ...request.env, HOOK_MARK: request.purpose + "-hooked" },
|
||||
wrap: wrap(request.purpose),
|
||||
};
|
||||
});
|
||||
return () => {};
|
||||
}
|
||||
`,
|
||||
);
|
||||
const daemon = await createTestPaseoDaemon({ daemonVersion: "0.8.0" });
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws`, appVersion: "0.8.0" });
|
||||
const sdk = createPaseoClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
try {
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
expect((await client.installDirectoryPlugin(pluginDirectory)).status).toBe("running");
|
||||
await sdk.connect();
|
||||
const created = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, branchName: "hooks", worktreeSlug: "hooks" },
|
||||
});
|
||||
expect(created.error).toBeNull();
|
||||
const workspaceId = created.workspace!.id;
|
||||
const worktree = created.workspace!.workspaceDirectory;
|
||||
|
||||
// Setup runs after creation, behind the wrap, with the hook's environment.
|
||||
await expect
|
||||
.poll(() => readFile(path.join(worktree, "setup.txt"), "utf8").catch(() => ""), {
|
||||
timeout: 30_000,
|
||||
})
|
||||
.toBe("setup:setup-hooked:setup");
|
||||
|
||||
const program = [
|
||||
"-e",
|
||||
"console.log('program:' + process.env.HOOK_MARK + ':' + process.env.WRAPPED); setInterval(() => {}, 1000)",
|
||||
];
|
||||
const wrapped = await sdk.terminals.create({
|
||||
workspaceId,
|
||||
name: "Wrapped",
|
||||
command: process.execPath,
|
||||
args: program,
|
||||
});
|
||||
await expect
|
||||
.poll(async () => (await wrapped.capture({ stripAnsi: true })).lines.join("\n"))
|
||||
.toContain(`program:client:${workspaceId}:terminal`);
|
||||
|
||||
await expect(sdk.terminals.create({ workspaceId, name: "Refused" })).rejects.toThrow(
|
||||
"Plugin terminal-hooks terminal.create.before failed: terminals named Refused stay closed",
|
||||
);
|
||||
|
||||
// A script's command is typed into a default shell, and that shell runs behind the wrap.
|
||||
await client.startWorkspaceScript(workspaceId, "greet");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const script = (await sdk.terminals.list({ workspaceId })).entries.find(
|
||||
(entry) => entry.name === "greet",
|
||||
);
|
||||
if (!script) return "";
|
||||
return (await sdk.terminals.ref(script.id).capture({ stripAnsi: true })).lines.join("\n");
|
||||
})
|
||||
.toContain(`script:script:${workspaceId}:terminal`);
|
||||
|
||||
await client.archiveWorkspace(workspaceId);
|
||||
await expect
|
||||
.poll(() => readFile(path.join(root, "teardown.txt"), "utf8").catch(() => ""), {
|
||||
timeout: 30_000,
|
||||
})
|
||||
.toBe("teardown:teardown-hooked:teardown");
|
||||
|
||||
const readJsonLines = async (file: string) =>
|
||||
(await readFile(file, "utf8"))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => JSON.parse(line));
|
||||
const entries = await readJsonLines(hookLog);
|
||||
expect(entries.filter((entry) => entry.hook === "command")).toEqual([
|
||||
{
|
||||
hook: "command",
|
||||
request: {
|
||||
workspaceId,
|
||||
cwd: worktree,
|
||||
purpose: "setup",
|
||||
command: setupCommand,
|
||||
env: expect.any(Object),
|
||||
},
|
||||
},
|
||||
{
|
||||
hook: "command",
|
||||
request: {
|
||||
workspaceId,
|
||||
cwd: worktree,
|
||||
purpose: "teardown",
|
||||
command: teardownCommand,
|
||||
env: expect.any(Object),
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(entries.filter((entry) => entry.hook === "terminal")).toEqual([
|
||||
{
|
||||
hook: "terminal",
|
||||
request: {
|
||||
workspaceId,
|
||||
cwd: worktree,
|
||||
source: "client",
|
||||
name: "Wrapped",
|
||||
command: process.execPath,
|
||||
args: program,
|
||||
input: null,
|
||||
env: {},
|
||||
},
|
||||
},
|
||||
{
|
||||
hook: "terminal",
|
||||
request: expect.objectContaining({ source: "client", name: "Refused" }),
|
||||
},
|
||||
{
|
||||
hook: "terminal",
|
||||
request: expect.objectContaining({
|
||||
workspaceId,
|
||||
source: "script",
|
||||
name: "greet",
|
||||
command: null,
|
||||
input: scriptCommand,
|
||||
}),
|
||||
},
|
||||
]);
|
||||
// Paseo appended what it would have run: the shell for a command, the program, the default shell.
|
||||
const launches = await readJsonLines(launchLog);
|
||||
expect(launches.map(({ tag, command }) => ({ tag, command }))).toEqual([
|
||||
{ tag: "setup", command: expect.any(String) },
|
||||
{ tag: "terminal", command: process.execPath },
|
||||
{ tag: "terminal", command: expect.any(String) },
|
||||
{ tag: "teardown", command: expect.any(String) },
|
||||
]);
|
||||
expect(launches[0].args.at(-1)).toBe(setupCommand);
|
||||
expect(launches[1].args).toEqual(program);
|
||||
expect(launches[3].args.at(-1)).toBe(teardownCommand);
|
||||
} finally {
|
||||
await sdk.close();
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
test("invalid output from an untyped plugin rejects creation before later callbacks run", async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-invalid-hook-"));
|
||||
const daemon = await createTestPaseoDaemon({ daemonVersion: "0.8.0" });
|
||||
|
||||
@@ -229,7 +229,7 @@ test.each([{ title: "Changed" }, { labels: { changed: "true" } }, { background:
|
||||
paseo,
|
||||
),
|
||||
).rejects.toThrow(
|
||||
"agent.open.before hooks can only change env, tools, mcpServers, and appendSystemPrompt",
|
||||
"agent.open.before hooks can only change env, tools, mcpServers, appendSystemPrompt, and wrap",
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -398,3 +398,209 @@ test("session-open instructions compose, survive old hooks, and are ignored for
|
||||
);
|
||||
expect(history).not.toHaveProperty("appendSystemPrompt");
|
||||
});
|
||||
|
||||
const openInput = {
|
||||
agentId: "agent",
|
||||
workspaceId: null,
|
||||
provider: "codex",
|
||||
cwd: "/project",
|
||||
reason: "resume",
|
||||
purpose: "interactive",
|
||||
env: {},
|
||||
title: null,
|
||||
labels: {},
|
||||
metadata: {},
|
||||
tools: [],
|
||||
mcpServers: {},
|
||||
};
|
||||
|
||||
type OpenHookResult = (request: Record<string, unknown>) => Record<string, unknown>;
|
||||
|
||||
/** Runs `results` as successive `agent.open.before` hooks of one plugin. */
|
||||
async function invokeOpen(results: OpenHookResult[], input: Record<string, unknown> = openInput) {
|
||||
const hooks = new PluginHookHandlers(() => {});
|
||||
for (const result of results) {
|
||||
hooks.addHook("agent.open.before", async ({ request }) => result(request) as never);
|
||||
}
|
||||
return await hooks.invoke("open", "agent.open.before", input, paseo);
|
||||
}
|
||||
|
||||
const withWrap =
|
||||
(...wrap: string[]): OpenHookResult =>
|
||||
(request) => ({ ...request, wrap });
|
||||
|
||||
test("a session-open hook can select a launch wrap", async () => {
|
||||
expect(await invokeOpen([withWrap("/usr/local/bin/sandbox", "--profile", "a b")])).toMatchObject({
|
||||
wrap: ["/usr/local/bin/sandbox", "--profile", "a b"],
|
||||
});
|
||||
});
|
||||
|
||||
test("a session-open hook result with an unknown key fails the open", async () => {
|
||||
await expect(invokeOpen([(request) => ({ ...request, notAHookField: true })])).rejects.toThrow(
|
||||
/notAHookField/,
|
||||
);
|
||||
});
|
||||
|
||||
test.each<[string, OpenHookResult, Record<string, unknown>]>([
|
||||
[
|
||||
"omits it",
|
||||
({ wrap: _wrap, ...request }) => ({ ...request, env: { LATER: "1" } }),
|
||||
{ wrap: ["/usr/local/bin/sandbox"], env: { LATER: "1" } },
|
||||
],
|
||||
["repeats it", withWrap("/usr/local/bin/sandbox"), { wrap: ["/usr/local/bin/sandbox"] }],
|
||||
])("an earlier wrap stays when a later session-open hook %s", async (_case, later, expected) => {
|
||||
expect(await invokeOpen([withWrap("/usr/local/bin/sandbox"), later])).toMatchObject(expected);
|
||||
});
|
||||
|
||||
test.each<[string, OpenHookResult[], string]>([
|
||||
[
|
||||
"a later hook returns a different wrap",
|
||||
[withWrap("/usr/local/bin/sandbox"), withWrap("/usr/local/bin/other")],
|
||||
"cannot change a wrap",
|
||||
],
|
||||
["the executable is relative", [withWrap("sandbox")], "must be an absolute path"],
|
||||
["the executable is empty", [withWrap("")], "must be an absolute path"],
|
||||
])("a session-open wrap fails the open when %s", async (_case, results, message) => {
|
||||
await expect(invokeOpen(results)).rejects.toThrow(message);
|
||||
});
|
||||
|
||||
test("a history open keeps the wrap while tools and MCP servers are stripped", async () => {
|
||||
const history = await invokeOpen(
|
||||
[
|
||||
(request) => ({
|
||||
...request,
|
||||
wrap: ["/usr/local/bin/sandbox"],
|
||||
mcpServers: { extra: { type: "stdio", command: "/bin/server" } },
|
||||
appendSystemPrompt: ["history"],
|
||||
}),
|
||||
],
|
||||
{ ...openInput, purpose: "history" },
|
||||
);
|
||||
expect(history).toMatchObject({ wrap: ["/usr/local/bin/sandbox"], tools: [], mcpServers: {} });
|
||||
expect(history).not.toHaveProperty("appendSystemPrompt");
|
||||
});
|
||||
|
||||
const terminalRequest = {
|
||||
workspaceId: "wks_a",
|
||||
cwd: "/work/a",
|
||||
source: "client" as const,
|
||||
name: "Shell",
|
||||
command: null,
|
||||
args: [],
|
||||
input: null,
|
||||
env: {},
|
||||
};
|
||||
const commandRequest = {
|
||||
workspaceId: null,
|
||||
cwd: "/work/a",
|
||||
purpose: "teardown" as const,
|
||||
command: "make clean && rm -rf build",
|
||||
env: {},
|
||||
};
|
||||
|
||||
test("terminal and command hooks can change env and wrap", async () => {
|
||||
await expect(
|
||||
validateBeforeResult("terminal.create.before", terminalRequest, {
|
||||
...terminalRequest,
|
||||
env: { WRAPPED: "1" },
|
||||
wrap: ["/usr/bin/sandbox", "--workspace", "wks_a"],
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
...terminalRequest,
|
||||
env: { WRAPPED: "1" },
|
||||
wrap: ["/usr/bin/sandbox", "--workspace", "wks_a"],
|
||||
});
|
||||
await expect(
|
||||
validateBeforeResult("command.run.before", commandRequest, {
|
||||
...commandRequest,
|
||||
wrap: ["/usr/bin/sandbox"],
|
||||
}),
|
||||
).resolves.toMatchObject({ command: "make clean && rm -rf build", wrap: ["/usr/bin/sandbox"] });
|
||||
});
|
||||
|
||||
test.each<[string, "terminal.create.before" | "command.run.before", object, object, string]>([
|
||||
[
|
||||
"a terminal's directory",
|
||||
"terminal.create.before",
|
||||
terminalRequest,
|
||||
{ cwd: "/elsewhere" },
|
||||
"terminal.create.before hooks can only change env and wrap",
|
||||
],
|
||||
[
|
||||
"a terminal's program",
|
||||
"terminal.create.before",
|
||||
terminalRequest,
|
||||
{ command: "/usr/bin/sandbox" },
|
||||
"terminal.create.before hooks can only change env and wrap",
|
||||
],
|
||||
[
|
||||
"a command's text",
|
||||
"command.run.before",
|
||||
commandRequest,
|
||||
{ command: "sandbox make clean" },
|
||||
"command.run.before hooks can only change env and wrap",
|
||||
],
|
||||
[
|
||||
"a command's purpose",
|
||||
"command.run.before",
|
||||
commandRequest,
|
||||
{ purpose: "setup" },
|
||||
"command.run.before hooks can only change env and wrap",
|
||||
],
|
||||
[
|
||||
"a relative wrap",
|
||||
"command.run.before",
|
||||
commandRequest,
|
||||
{ wrap: ["sandbox"] },
|
||||
"wrap executable must be an absolute path",
|
||||
],
|
||||
])("a hook cannot change %s", async (_case, name, request, change, message) => {
|
||||
await expect(
|
||||
validateBeforeResult(name, request as never, { ...request, ...change }),
|
||||
).rejects.toThrow(message);
|
||||
});
|
||||
|
||||
test.each(["terminal.create.before", "command.run.before"] as const)(
|
||||
"%s keeps the first wrap and rejects a different one",
|
||||
async (name) => {
|
||||
const initial = name === "terminal.create.before" ? terminalRequest : commandRequest;
|
||||
const hooks = new PluginHookHandlers(() => {});
|
||||
hooks.addHook(
|
||||
name,
|
||||
async ({ request }) => ({ ...request, wrap: ["/usr/bin/sandbox"] }) as never,
|
||||
);
|
||||
hooks.addHook(name, async ({ request }) => {
|
||||
const { wrap: _omitted, ...rest } = request as typeof request & { wrap?: unknown };
|
||||
return { ...rest, env: { LATER: "1" } } as never;
|
||||
});
|
||||
await expect(hooks.invoke("first", name, initial, paseo)).resolves.toMatchObject({
|
||||
wrap: ["/usr/bin/sandbox"],
|
||||
env: { LATER: "1" },
|
||||
});
|
||||
hooks.addHook(name, async ({ request }) => ({ ...request, wrap: ["/usr/bin/other"] }) as never);
|
||||
await expect(hooks.invoke("second", name, initial, paseo)).rejects.toThrow(
|
||||
`${name} hooks cannot change a wrap an earlier hook selected`,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test("agent creation hooks keep the workspace, including from plugins that omit it", async () => {
|
||||
const request = {
|
||||
config: { provider: "claude", cwd: "/work/a" },
|
||||
metadata: { "issues.id": "ENG-1" },
|
||||
workspaceId: "wks_a",
|
||||
};
|
||||
// A result built before either field existed keeps both.
|
||||
await expect(
|
||||
validateBeforeResult("agent.create.before", request, { config: request.config }),
|
||||
).resolves.toEqual(request);
|
||||
await expect(
|
||||
validateBeforeResult("agent.create.before", request, {
|
||||
config: request.config,
|
||||
metadata: { "issues.id": "ENG-2" },
|
||||
}),
|
||||
).resolves.toEqual({ ...request, metadata: { "issues.id": "ENG-2" } });
|
||||
await expect(
|
||||
validateBeforeResult("agent.create.before", request, { ...request, workspaceId: "wks_b" }),
|
||||
).rejects.toThrow("agent.create.before hooks cannot change the workspace");
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
createLifecycleRegistration,
|
||||
pluginHookRegistry,
|
||||
} from "@getpaseo/plugin/internal/lifecycle";
|
||||
import { isAbsolute } from "node:path";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import {
|
||||
serializeAgentTool,
|
||||
@@ -93,13 +94,20 @@ const worktreeRequestSchema = z.discriminatedUnion("kind", [
|
||||
.strict(),
|
||||
]);
|
||||
|
||||
const launchWrapSchema = z
|
||||
.tuple([z.string().refine(isAbsolute, "wrap executable must be an absolute path")], z.string())
|
||||
.optional();
|
||||
|
||||
const beforeSchemas = {
|
||||
"worktree.create.before": worktreeRequestSchema,
|
||||
"agent.create.before": CreateAgentRequestMessageSchema.pick({
|
||||
config: true,
|
||||
env: true,
|
||||
metadata: true,
|
||||
}).strict(),
|
||||
})
|
||||
// A plugin built before the field may omit it from its result; it can't change it.
|
||||
.extend({ workspaceId: z.string().nullable().optional() })
|
||||
.strict(),
|
||||
"agent.open.before": z
|
||||
.object({
|
||||
agentId: z.string(),
|
||||
@@ -118,14 +126,77 @@ const beforeSchemas = {
|
||||
tools: z.array(agentToolMetadataSchema),
|
||||
env: z.record(z.string(), z.string()),
|
||||
mcpServers: CreateAgentRequestMessageSchema.shape.config.shape.mcpServers.unwrap(),
|
||||
wrap: launchWrapSchema,
|
||||
})
|
||||
.strict(),
|
||||
"workspace.create.before": WorkspaceCreateRequestSchema.omit({
|
||||
type: true,
|
||||
requestId: true,
|
||||
}).strict(),
|
||||
"terminal.create.before": z
|
||||
.object({
|
||||
workspaceId: z.string(),
|
||||
cwd: z.string(),
|
||||
source: z.enum(["client", "agent", "script", "worktree"]),
|
||||
name: z.string().nullable(),
|
||||
command: z.string().nullable(),
|
||||
args: z.array(z.string()),
|
||||
input: z.string().nullable(),
|
||||
env: z.record(z.string(), z.string()),
|
||||
wrap: launchWrapSchema,
|
||||
})
|
||||
.strict(),
|
||||
"command.run.before": z
|
||||
.object({
|
||||
workspaceId: z.string().nullable(),
|
||||
cwd: z.string(),
|
||||
purpose: z.enum(["setup", "teardown"]),
|
||||
command: z.string(),
|
||||
env: z.record(z.string(), z.string()),
|
||||
wrap: launchWrapSchema,
|
||||
})
|
||||
.strict(),
|
||||
};
|
||||
|
||||
// Request fields a hook reads but can't change, with the error a changed one gets.
|
||||
const readOnlyRequestFields = {
|
||||
"terminal.create.before": {
|
||||
fields: ["workspaceId", "cwd", "source", "name", "command", "args", "input"],
|
||||
message: "terminal.create.before hooks can only change env and wrap",
|
||||
},
|
||||
"command.run.before": {
|
||||
fields: ["workspaceId", "cwd", "purpose", "command"],
|
||||
message: "command.run.before hooks can only change env and wrap",
|
||||
},
|
||||
} as const;
|
||||
|
||||
function assertReadOnlyFields(name: string, input: unknown, result: unknown): void {
|
||||
if (!Object.hasOwn(readOnlyRequestFields, name)) return;
|
||||
const { fields, message } = readOnlyRequestFields[name as keyof typeof readOnlyRequestFields];
|
||||
const previous = input as Record<string, unknown>;
|
||||
const next = result as Record<string, unknown>;
|
||||
if (fields.some((field) => !isDeepStrictEqual(previous[field], next[field])))
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
type LaunchWrap = z.infer<typeof launchWrapSchema>;
|
||||
|
||||
/**
|
||||
* One wrap per operation: the first hook that selects a wrap owns it. A later hook may omit it or
|
||||
* repeat it; a different wrap fails, so two sandboxes never silently stack or replace each other.
|
||||
*/
|
||||
function keepSelectedWrap(name: string, previous: LaunchWrap, next: LaunchWrap): LaunchWrap {
|
||||
if (previous && next && !isDeepStrictEqual(previous, next)) {
|
||||
throw new Error(`${name} hooks cannot change a wrap an earlier hook selected`);
|
||||
}
|
||||
return previous ?? next;
|
||||
}
|
||||
|
||||
function withWrap<Result extends object>(result: Result, wrap: LaunchWrap): Result {
|
||||
const { wrap: _replaced, ...rest } = result as Result & { wrap?: LaunchWrap };
|
||||
return (wrap ? { ...rest, wrap } : rest) as Result;
|
||||
}
|
||||
|
||||
const sessionOpenLocalResultSchema = beforeSchemas["agent.open.before"].extend({
|
||||
tools: z.array(
|
||||
z.custom<AgentToolDefinition>(
|
||||
@@ -278,11 +349,11 @@ export async function validateBeforeResult<Name extends keyof PluginWireBeforeRe
|
||||
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",
|
||||
"agent.open.before hooks can only change env, tools, mcpServers, appendSystemPrompt, and wrap",
|
||||
);
|
||||
}
|
||||
return {
|
||||
...result,
|
||||
...withWrap(result, keepSelectedWrap(name, previous.wrap, next.wrap)),
|
||||
background: previous.background,
|
||||
metadata: previous.metadata,
|
||||
...(next.appendSystemPrompt === undefined && previous.appendSystemPrompt !== undefined
|
||||
@@ -296,8 +367,15 @@ export async function validateBeforeResult<Name extends keyof PluginWireBeforeRe
|
||||
if (previous.config.cwd !== next.config.cwd) {
|
||||
throw new Error("agent.create.before hooks cannot change the workspace directory");
|
||||
}
|
||||
if ((next.workspaceId ?? previous.workspaceId ?? null) !== (previous.workspaceId ?? null)) {
|
||||
throw new Error("agent.create.before hooks cannot change the workspace");
|
||||
}
|
||||
// Omitted means unchanged: the next hook sees what this one was handed.
|
||||
return { ...result, metadata: next.metadata ?? previous.metadata };
|
||||
return {
|
||||
...result,
|
||||
metadata: next.metadata ?? previous.metadata,
|
||||
workspaceId: previous.workspaceId ?? null,
|
||||
};
|
||||
}
|
||||
if (name === "workspace.create.before") {
|
||||
const previous = beforeSchemas["workspace.create.before"].parse(input);
|
||||
@@ -305,6 +383,13 @@ export async function validateBeforeResult<Name extends keyof PluginWireBeforeRe
|
||||
// Omitted means unchanged; an explicit {} still replaces.
|
||||
return { ...result, metadata: next.metadata ?? previous.metadata };
|
||||
}
|
||||
if (name === "terminal.create.before" || name === "command.run.before") {
|
||||
assertReadOnlyFields(name, input, result);
|
||||
const schema = beforeSchemas[name as "terminal.create.before" | "command.run.before"];
|
||||
const previous = schema.parse(input);
|
||||
const next = schema.parse(result);
|
||||
return withWrap(result, keepSelectedWrap(name, previous.wrap, next.wrap));
|
||||
}
|
||||
if (name === "worktree.create.before") {
|
||||
const previous = beforeSchemas["worktree.create.before"].parse(input);
|
||||
const next = beforeSchemas["worktree.create.before"].parse(result);
|
||||
|
||||
@@ -24,6 +24,7 @@ export interface PluginProviderMetadata {
|
||||
hasStatus?: boolean;
|
||||
installation?: PluginProviderInstallationMetadata;
|
||||
command?: readonly [string, ...string[]];
|
||||
launchWrap?: boolean;
|
||||
id: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
@@ -193,6 +194,7 @@ const providerMetadataSchema = z
|
||||
.strict()
|
||||
.optional(),
|
||||
command: z.tuple([z.string().min(1)], z.string()).optional(),
|
||||
launchWrap: z.boolean().optional(),
|
||||
})
|
||||
.strict();
|
||||
const usageSourceMetadataSchema = z
|
||||
|
||||
@@ -292,6 +292,7 @@ export function createPluginWorker(options: {
|
||||
}
|
||||
: undefined,
|
||||
command: provider.command,
|
||||
launchWrap: provider.launchWrap,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -2269,3 +2269,97 @@ export default function contribute() {
|
||||
await runtime.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
describe("open-hook launch wrap across plugins", () => {
|
||||
type OpenInput = Record<string, unknown> & { wrap?: string[] };
|
||||
|
||||
function createHookChild(name: string, hooks: string[], onHook: (input: OpenInput) => unknown) {
|
||||
const child = createReloadChild(name, []);
|
||||
const send = child.send.bind(child);
|
||||
child.send = (message, callback) => {
|
||||
if (message.type === "initialize") {
|
||||
callback?.(null);
|
||||
queueMicrotask(() =>
|
||||
child.emitMessage({ type: "ready", methods: [], providers: [], hooks }),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
if (message.type === "hook") {
|
||||
callback?.(null);
|
||||
const { requestId, input } = message as unknown as { requestId: string; input: OpenInput };
|
||||
queueMicrotask(() =>
|
||||
child.emitMessage({ type: "result", requestId, output: onHook(input) }),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
return send(message, callback);
|
||||
};
|
||||
return child;
|
||||
}
|
||||
|
||||
const request = {
|
||||
agentId: "agent",
|
||||
workspaceId: null,
|
||||
provider: "codex",
|
||||
cwd: "/project",
|
||||
reason: "resume" as const,
|
||||
purpose: "interactive" as const,
|
||||
env: {},
|
||||
title: null,
|
||||
background: false,
|
||||
labels: {},
|
||||
metadata: {},
|
||||
tools: [],
|
||||
mcpServers: {},
|
||||
};
|
||||
|
||||
// Ids sort like paseo-safehouse before zerosub, so the sandbox plugin runs first.
|
||||
async function openWith(later: (input: OpenInput) => unknown) {
|
||||
const calls: string[] = [];
|
||||
// Started in the opposite order to their ids: the runtime orders hooks by id, not start order.
|
||||
const children = [
|
||||
createHookChild("zerosub", ["agent.open.before"], (input) => {
|
||||
calls.push("zerosub");
|
||||
return later(input);
|
||||
}),
|
||||
createHookChild("paseo-safehouse", ["agent.open.before"], (input) => {
|
||||
calls.push("paseo-safehouse");
|
||||
return { ...input, wrap: ["/opt/safehouse/bin/safehouse", "--profile", "a b"] };
|
||||
}),
|
||||
];
|
||||
const runtime = createTestRuntime({ spawnChild: () => children.shift()! as never });
|
||||
await runtime.startPlugin("zerosub", await createPlugin("zerosub", "export default {}"));
|
||||
await runtime.startPlugin(
|
||||
"paseo-safehouse",
|
||||
await createPlugin("paseo-safehouse", "export default {}"),
|
||||
);
|
||||
try {
|
||||
return await runtime.before("agent.open.before", request);
|
||||
} finally {
|
||||
expect(calls).toEqual(["paseo-safehouse", "zerosub"]);
|
||||
await runtime.stopAll();
|
||||
}
|
||||
}
|
||||
|
||||
it("keeps the first plugin's wrap when a later plugin omits it", async () => {
|
||||
const result = await openWith(({ wrap: _wrap, ...input }) => ({
|
||||
...input,
|
||||
env: { LATER: "1" },
|
||||
}));
|
||||
expect(result).toMatchObject({
|
||||
wrap: ["/opt/safehouse/bin/safehouse", "--profile", "a b"],
|
||||
env: { LATER: "1" },
|
||||
});
|
||||
});
|
||||
|
||||
it("passes when a later plugin returns the same wrap", async () => {
|
||||
const result = await openWith((input) => input);
|
||||
expect(result.wrap).toEqual(["/opt/safehouse/bin/safehouse", "--profile", "a b"]);
|
||||
});
|
||||
|
||||
it("fails the open when a later plugin returns a different wrap", async () => {
|
||||
await expect(
|
||||
openWith((input) => ({ ...input, wrap: ["/usr/bin/other-sandbox"] })),
|
||||
).rejects.toThrow(/Plugin zerosub agent.open.before failed: .*cannot change a wrap/u);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -358,9 +358,16 @@ function isReusable(
|
||||
);
|
||||
}
|
||||
|
||||
/** The fields one plugin's callback passes on to the next. Tools and MCP servers are collected per plugin instead. */
|
||||
/**
|
||||
* The fields one plugin's callback passes on to the next, including the launch wrap an earlier plugin selected. Tools
|
||||
* and MCP servers are collected per plugin instead.
|
||||
*/
|
||||
function chainedFields(request: SessionOpenWireRequest) {
|
||||
return { env: request.env, appendSystemPrompt: request.appendSystemPrompt ?? [] };
|
||||
return {
|
||||
env: request.env,
|
||||
appendSystemPrompt: request.appendSystemPrompt ?? [],
|
||||
wrap: request.wrap ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -837,6 +837,10 @@ export class Session {
|
||||
private readonly daemonConfigStore: DaemonConfigStore;
|
||||
private readonly pushNotifications: PushNotifications;
|
||||
private readonly pluginRuntime: SessionOptions["pluginRuntime"];
|
||||
// What worktree setup and teardown commands run through: the plugins' hooks, or none.
|
||||
private get commandLifecycle(): NonNullable<SessionOptions["pluginRuntime"]> | null {
|
||||
return this.pluginRuntime ?? null;
|
||||
}
|
||||
private readonly orchestrationSkills: SessionOptions["orchestrationSkills"];
|
||||
private unsubscribeAgentEvents: (() => void) | null = null;
|
||||
private unsubscribeProjectMutations: (() => void) | null = null;
|
||||
@@ -1296,6 +1300,7 @@ export class Session {
|
||||
});
|
||||
this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations);
|
||||
this.createAgentLifecycleDispatch = new CreateAgentLifecycleDispatch({
|
||||
lifecycle: this.commandLifecycle,
|
||||
paseoHome: this.paseoHome,
|
||||
worktreesRoot: this.worktreesRoot,
|
||||
worktreeManagers: this.pluginRuntime,
|
||||
@@ -5832,6 +5837,7 @@ export class Session {
|
||||
): Promise<void> {
|
||||
return handleWorktreeArchiveRequest(
|
||||
{
|
||||
lifecycle: this.commandLifecycle,
|
||||
paseoHome: this.paseoHome,
|
||||
paseoWorktreesBaseRoot: this.worktreesRoot,
|
||||
worktreeManagers: this.pluginRuntime,
|
||||
@@ -8161,6 +8167,7 @@ export class Session {
|
||||
): Promise<CreatePaseoWorktreeWorkflowResult> {
|
||||
return createWorktreeWorkflow(
|
||||
{
|
||||
lifecycle: this.commandLifecycle,
|
||||
paseoHome: this.paseoHome,
|
||||
worktreesRoot: this.worktreesRoot,
|
||||
createPaseoWorktree: (workflowInput, serviceOptions) =>
|
||||
@@ -8214,6 +8221,7 @@ export class Session {
|
||||
): Promise<void> {
|
||||
return handleWorkspaceSetupRunRequestMessage(
|
||||
{
|
||||
lifecycle: this.commandLifecycle,
|
||||
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
|
||||
clearAutomationBlock: (workspaceId) =>
|
||||
this.withWorkspaceCheckout(workspaceId, async (checkoutPath) => {
|
||||
@@ -8263,6 +8271,7 @@ export class Session {
|
||||
}
|
||||
return archiveByScope(
|
||||
{
|
||||
lifecycle: this.commandLifecycle,
|
||||
paseoHome: this.paseoHome,
|
||||
paseoWorktreesBaseRoot: this.worktreesRoot,
|
||||
worktreeManagers: this.pluginRuntime,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { commandRunHook } from "./command-run-hook.js";
|
||||
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import type { Logger } from "pino";
|
||||
@@ -69,6 +71,8 @@ export interface ArchiveDependencies {
|
||||
assertWorkspaceAutomationAllowed: (workspaceId: string) => Promise<void>;
|
||||
isCheckoutUntrusted: (checkoutPath: string) => Promise<boolean>;
|
||||
sessionLogger?: Logger;
|
||||
/** Plugins' lifecycle, for `command.run.before` on teardown commands. */
|
||||
lifecycle: Pick<PluginLifecycle, "before"> | null;
|
||||
}
|
||||
|
||||
export interface KillTerminalsForWorkspaceDependencies {
|
||||
@@ -593,6 +597,11 @@ async function maybeRemoveDirectory(
|
||||
worktreePath: backing.path,
|
||||
teardownCwd: teardownTarget.cwd,
|
||||
repoRootPath: backing.mainRepoRoot ?? undefined,
|
||||
prepareCommand: commandRunHook(dependencies.lifecycle, {
|
||||
workspaceId: teardownTarget.workspaceId,
|
||||
cwd: teardownTarget.cwd,
|
||||
purpose: "teardown",
|
||||
}),
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
@@ -327,6 +327,7 @@ export async function runWorktreeAutoTerminals(options: {
|
||||
(await getWorktreeTerminalSpecs(options.workspaceCwd)).map(async (spec) => {
|
||||
try {
|
||||
const terminal = await terminalManager.createTerminal({
|
||||
origin: { source: "worktree", input: spec.command },
|
||||
cwd: options.workspaceCwd,
|
||||
name: spec.name,
|
||||
env: options.runtimeEnv,
|
||||
@@ -488,6 +489,7 @@ async function acquireWorkspaceScriptTerminal(params: {
|
||||
repoRoot: string;
|
||||
workspaceId: string;
|
||||
scriptName: string;
|
||||
command: string;
|
||||
env: Record<string, string> | undefined;
|
||||
}): Promise<{ terminal: TerminalSession; reusableTerminal: TerminalSession | null }> {
|
||||
const {
|
||||
@@ -497,6 +499,7 @@ async function acquireWorkspaceScriptTerminal(params: {
|
||||
repoRoot,
|
||||
workspaceId,
|
||||
scriptName,
|
||||
command,
|
||||
env,
|
||||
} = params;
|
||||
let reusableTerminal: TerminalSession | null = null;
|
||||
@@ -506,6 +509,7 @@ async function acquireWorkspaceScriptTerminal(params: {
|
||||
const terminal =
|
||||
reusableTerminal ??
|
||||
(await terminalManager.createTerminal({
|
||||
origin: { source: "script", input: command },
|
||||
cwd: repoRoot,
|
||||
workspaceId,
|
||||
name: scriptName,
|
||||
@@ -588,6 +592,7 @@ export async function spawnWorkspaceScript(
|
||||
repoRoot,
|
||||
workspaceId,
|
||||
scriptName,
|
||||
command: config.command,
|
||||
env,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { commandRunHook } from "./command-run-hook.js";
|
||||
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
|
||||
import type { Logger } from "pino";
|
||||
import { basename } from "node:path";
|
||||
import {
|
||||
@@ -63,6 +65,8 @@ interface CreatePaseoWorktreeInBackgroundDependencies {
|
||||
getDaemonTcpHost: (() => string | null) | null;
|
||||
serviceProxyPublicBaseUrl?: string | null;
|
||||
onScriptsChanged: ((workspaceId: string, workspaceDirectory: string) => void) | null;
|
||||
/** Plugins' lifecycle, for `command.run.before` on setup commands. */
|
||||
lifecycle: Pick<PluginLifecycle, "before"> | null;
|
||||
}
|
||||
|
||||
interface CreatePaseoWorktreeWorkflowDependencies extends CreatePaseoWorktreeInBackgroundDependencies {
|
||||
@@ -577,6 +581,11 @@ export async function runWorktreeSetupInBackground(
|
||||
applyWorktreeSetupProgressEvent(progressAccumulator, event);
|
||||
emitSetupProgress("running", null);
|
||||
},
|
||||
prepareCommand: commandRunHook(dependencies.lifecycle, {
|
||||
workspaceId,
|
||||
cwd: workspaceCwd,
|
||||
purpose: "setup",
|
||||
}),
|
||||
});
|
||||
emitSetupProgress("completed", null);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// Kept apart from terminal.ts so the daemon can resolve the shell without loading node-pty.
|
||||
export function resolveDefaultTerminalShell(
|
||||
options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {},
|
||||
): string {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
|
||||
if (platform === "win32") {
|
||||
return env.ComSpec || env.COMSPEC || "C:\\Windows\\System32\\cmd.exe";
|
||||
}
|
||||
|
||||
return env.SHELL || "/bin/sh";
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { PluginLifecycle } from "../server/plugins/lifecycle/index.js";
|
||||
import { applyLaunchWrap } from "../utils/launch-wrap.js";
|
||||
import { resolveDefaultTerminalShell } from "./default-terminal-shell.js";
|
||||
import type { DaemonTerminalManager } from "./worker-terminal-manager.js";
|
||||
|
||||
/**
|
||||
* Runs plugins' `terminal.create.before` hooks for every terminal the daemon creates, before the
|
||||
* worker starts it. A selected wrap becomes the terminal's program here, so the worker protocol
|
||||
* does not change. Terminals adopted after a daemon restart aren't created again, so the hook
|
||||
* doesn't run for them.
|
||||
*/
|
||||
export function withTerminalCreateHook(
|
||||
manager: DaemonTerminalManager,
|
||||
lifecycle: Pick<PluginLifecycle, "before">,
|
||||
): DaemonTerminalManager {
|
||||
return {
|
||||
...manager,
|
||||
async createTerminal({ origin, ...options }) {
|
||||
const args = options.args ?? [];
|
||||
const request = await lifecycle.before("terminal.create.before", {
|
||||
workspaceId: options.workspaceId,
|
||||
cwd: options.cwd,
|
||||
source: origin?.source ?? "client",
|
||||
name: options.name ?? null,
|
||||
command: options.command ?? null,
|
||||
args,
|
||||
input: origin?.input ?? null,
|
||||
env: options.env ?? {},
|
||||
});
|
||||
if (!request.wrap) return manager.createTerminal({ ...options, env: request.env });
|
||||
const command = options.command ?? resolveDefaultTerminalShell({ env: options.baseEnv });
|
||||
const launch = applyLaunchWrap({ command, args }, request.wrap);
|
||||
return manager.createTerminal({ ...options, env: request.env, ...launch });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -54,6 +54,16 @@ export type TerminalWorkspaceContributionChangedListener = (
|
||||
event: TerminalWorkspaceContributionChangedEvent,
|
||||
) => void;
|
||||
|
||||
/**
|
||||
* Who asked for a terminal: an agent's Paseo tool, a `paseo.json` script or service, or a
|
||||
* `paseo.json` worktree terminal; anything else is a client. `input` is the command Paseo types
|
||||
* into the shell once it starts.
|
||||
*/
|
||||
export interface TerminalOrigin {
|
||||
source: "client" | "agent" | "script" | "worktree";
|
||||
input?: string;
|
||||
}
|
||||
|
||||
export interface TerminalManager {
|
||||
/**
|
||||
* Set when this host's terminals cannot be served at all (a worker from a newer Paseo holds
|
||||
@@ -62,6 +72,8 @@ export interface TerminalManager {
|
||||
getUnavailableError?(): Error | null;
|
||||
getTerminals(cwd: string, options?: { workspaceId?: string }): Promise<TerminalSession[]>;
|
||||
createTerminal(options: {
|
||||
/** Where the terminal comes from, for plugins' `terminal.create.before` hooks. */
|
||||
origin?: TerminalOrigin;
|
||||
id?: string;
|
||||
cwd: string;
|
||||
workspaceId: string;
|
||||
|
||||
@@ -728,6 +728,74 @@ describe("terminal-session-controller workspace-scoped subscriptions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminal-session-controller script ownership", () => {
|
||||
test("reports a terminal as a script when its runtime registers right after the creation snapshot", async () => {
|
||||
const cwd = "/work/repo";
|
||||
const terminal = listSession({ id: "script", name: "sleeper", cwd, workspaceId: "ws-a" });
|
||||
const scriptTerminalIds = new Set<string>();
|
||||
let changedListener: ((event: TerminalsChangedEvent) => void) | null = null;
|
||||
let metadataListener: (() => void) | null = null;
|
||||
const terminalManager: TerminalManager = {
|
||||
getTerminals: vi.fn(async () => [terminal]),
|
||||
createTerminal: vi.fn(),
|
||||
registerCwdEnv: vi.fn(),
|
||||
validateTerminalActivityToken: vi.fn(() => "unknown"),
|
||||
getTerminal: vi.fn(),
|
||||
replayTerminal: async () => null,
|
||||
setTerminalTitle: vi.fn(),
|
||||
setTerminalActivity: vi.fn(),
|
||||
killTerminal: vi.fn(),
|
||||
killTerminalAndWait: vi.fn(),
|
||||
captureTerminal: vi.fn(),
|
||||
listDirectories: vi.fn(() => [cwd]),
|
||||
killAll: vi.fn(),
|
||||
subscribeTerminalsChanged: vi.fn((listener) => {
|
||||
changedListener = listener;
|
||||
return vi.fn();
|
||||
}),
|
||||
subscribeTerminalActivity: vi.fn(() => vi.fn()),
|
||||
subscribeTerminalWorkspaceContributionChanged: vi.fn(() => vi.fn()),
|
||||
};
|
||||
const reported: boolean[] = [];
|
||||
let registerAfterNextSnapshot = false;
|
||||
const controller = createController({
|
||||
terminalManager,
|
||||
emit: (message) => {
|
||||
if (message.type !== "terminals_changed") return;
|
||||
reported.push(message.payload.terminals.some((item) => item.isScript));
|
||||
if (!registerAfterNextSnapshot) return;
|
||||
registerAfterNextSnapshot = false;
|
||||
// The script service registers its runtime in a continuation that runs right after the
|
||||
// snapshot for the new terminal goes out, before that snapshot's refresh has settled.
|
||||
queueMicrotask(() => {
|
||||
scriptTerminalIds.add(terminal.id);
|
||||
metadataListener?.();
|
||||
});
|
||||
},
|
||||
emitBinary: vi.fn(),
|
||||
hasBinaryChannel: () => true,
|
||||
isPathWithinRoot: isSameOrDescendantPath,
|
||||
sessionLogger: createLogger(),
|
||||
isScriptTerminal: (item) => scriptTerminalIds.has(item.id),
|
||||
subscribeTerminalMetadata: (listener) => {
|
||||
metadataListener = listener;
|
||||
return () => {
|
||||
metadataListener = null;
|
||||
};
|
||||
},
|
||||
});
|
||||
controller.dispatch({ type: "subscribe_terminals_request", cwd, workspaceId: "ws-a" });
|
||||
await flushMicrotasks();
|
||||
reported.length = 0;
|
||||
|
||||
registerAfterNextSnapshot = true;
|
||||
changedListener?.({ cwd, terminals: [{ id: terminal.id, name: terminal.name, cwd }] });
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(reported.at(-1)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminal-session-controller backpressure snapshot fallback", () => {
|
||||
async function setup(
|
||||
getClientBufferedAmount: () => number | null,
|
||||
|
||||
@@ -390,39 +390,41 @@ export class TerminalSessionController {
|
||||
return subscription.refresh;
|
||||
}
|
||||
const refresh = (async () => {
|
||||
do {
|
||||
subscription.pending = false;
|
||||
const terminals =
|
||||
subscription.cwd === undefined
|
||||
? (await this.getAllTerminalSessions()).filter(
|
||||
(terminal) =>
|
||||
subscription.workspaceId === undefined ||
|
||||
terminal.workspaceId === subscription.workspaceId,
|
||||
)
|
||||
: await this.getTerminalsForWorkspaceRoot(subscription.cwd, subscription.workspaceId);
|
||||
if (subscription.owner.signal.aborted) return;
|
||||
subscription.owner.emit({
|
||||
type: "terminals_changed",
|
||||
payload: {
|
||||
cwd: subscription.cwd,
|
||||
workspaceId: subscription.workspaceId,
|
||||
terminals: terminals.map((terminal) =>
|
||||
Object.assign(
|
||||
this.toTerminalInfo(terminal),
|
||||
subscription.cwd === undefined ? { cwd: terminal.cwd } : {},
|
||||
try {
|
||||
do {
|
||||
subscription.pending = false;
|
||||
const terminals =
|
||||
subscription.cwd === undefined
|
||||
? (await this.getAllTerminalSessions()).filter(
|
||||
(terminal) =>
|
||||
subscription.workspaceId === undefined ||
|
||||
terminal.workspaceId === subscription.workspaceId,
|
||||
)
|
||||
: await this.getTerminalsForWorkspaceRoot(subscription.cwd, subscription.workspaceId);
|
||||
if (subscription.owner.signal.aborted) return;
|
||||
subscription.owner.emit({
|
||||
type: "terminals_changed",
|
||||
payload: {
|
||||
cwd: subscription.cwd,
|
||||
workspaceId: subscription.workspaceId,
|
||||
terminals: terminals.map((terminal) =>
|
||||
Object.assign(
|
||||
this.toTerminalInfo(terminal),
|
||||
subscription.cwd === undefined ? { cwd: terminal.cwd } : {},
|
||||
),
|
||||
),
|
||||
),
|
||||
...(requestId ? { requestId } : {}),
|
||||
},
|
||||
});
|
||||
requestId = undefined;
|
||||
} while (subscription.pending);
|
||||
...(requestId ? { requestId } : {}),
|
||||
},
|
||||
});
|
||||
requestId = undefined;
|
||||
} while (subscription.pending);
|
||||
} finally {
|
||||
// Clear in the same step as the last pending check. A change that lands after it then
|
||||
// starts a new refresh instead of setting a pending flag that nothing reads again.
|
||||
subscription.refresh = null;
|
||||
}
|
||||
})();
|
||||
subscription.refresh = refresh;
|
||||
const settled = () => {
|
||||
subscription.refresh = null;
|
||||
};
|
||||
void refresh.then(settled, settled);
|
||||
return refresh;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { resolveDefaultTerminalShell } from "./default-terminal-shell.js";
|
||||
import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode";
|
||||
import { createTerminalSerializer } from "./terminal-serializer.js";
|
||||
import { readTerminalState } from "./test-utils/terminal-state.js";
|
||||
@@ -9,7 +10,6 @@ import {
|
||||
assertTerminalCommandCanStart,
|
||||
createTerminal,
|
||||
ensureNodePtySpawnHelperExecutableForCurrentPlatform,
|
||||
resolveDefaultTerminalShell,
|
||||
resolveTerminalSpawnCommand,
|
||||
humanizeProcessTitle,
|
||||
normalizeProcessTitle,
|
||||
@@ -308,16 +308,18 @@ describe("createTerminal", () => {
|
||||
resolveExecutable: async () => "C:\\npm\\claude.cmd",
|
||||
});
|
||||
|
||||
// The `.cmd` branch now hands node-pty a single pre-escaped command line
|
||||
// (string) instead of an argv array, so that node-pty's own
|
||||
// MSVCRT-style array quoting never runs a second time over an already
|
||||
// cmd.exe-escaped argument. See escapeCmdExeArgument in terminal.ts.
|
||||
// The `.cmd` branch hands node-pty one cmd.exe command line (a string) instead of an argv
|
||||
// array, so node-pty's own array quoting never runs over it. An argument without a cmd.exe
|
||||
// metacharacter stays as given.
|
||||
expect(resolved).toEqual({
|
||||
command: "C:\\Windows\\System32\\cmd.exe",
|
||||
args: '/d /s /c "C:\\npm\\claude.cmd ^^^"--foo^^^""',
|
||||
args: '/d /s /c "C:\\npm\\claude.cmd --foo"',
|
||||
});
|
||||
});
|
||||
|
||||
// The escaping itself is the SDK's shared cmd.exe dialect, tested in
|
||||
// packages/plugin/src/server/process-internal/windows-command.test.ts. These cases pin what a
|
||||
// terminal adds: a prompt line break becomes a space, and a `.cmd` shim counts as a batch script.
|
||||
describe(".cmd shim argument escaping on Windows", () => {
|
||||
async function resolveCmdShimArgs(promptArg: string): Promise<string> {
|
||||
const resolved = await resolveTerminalSpawnCommand("claude", [promptArg], {
|
||||
@@ -325,10 +327,6 @@ describe("createTerminal", () => {
|
||||
env: { ComSpec: "C:\\Windows\\System32\\cmd.exe" },
|
||||
resolveExecutable: async () => "C:\\npm\\claude.cmd",
|
||||
});
|
||||
// A real narrow rather than a cast: the `.cmd` branch is the one case
|
||||
// that returns a pre-escaped command line instead of argv, so if that
|
||||
// contract ever changes these tests should fail loudly here rather than
|
||||
// assert against a stringified array.
|
||||
const { args } = resolved;
|
||||
if (typeof args !== "string") {
|
||||
throw new Error(`expected a cmd.exe command line, got ${JSON.stringify(args)}`);
|
||||
@@ -336,21 +334,20 @@ describe("createTerminal", () => {
|
||||
return args;
|
||||
}
|
||||
|
||||
// Each expected string is the exact cmd.exe command line the escaping
|
||||
// must produce so a real `cmd.exe /c` invocation reconstructs the
|
||||
// original prompt as a single argv element for the target process
|
||||
// (modulo the documented newline-to-space normalization below).
|
||||
it("neutralizes cmd.exe's own metacharacters instead of letting them execute", async () => {
|
||||
it("escapes cmd.exe metacharacters so they reach the shim as text", async () => {
|
||||
expect(await resolveCmdShimArgs("a & b | c")).toBe(
|
||||
'/d /s /c "C:\\npm\\claude.cmd ^^^"a^^^ ^^^&^^^ b^^^ ^^^|^^^ c^^^""',
|
||||
'/d /s /c "C:\\npm\\claude.cmd ^"a^ ^&^ b^ ^|^ c^""',
|
||||
);
|
||||
// A caret before each `%` keeps cmd.exe from expanding %PATH%.
|
||||
expect(await resolveCmdShimArgs("100% done %PATH%")).toBe(
|
||||
'/d /s /c "C:\\npm\\claude.cmd ^^^"100^^^%^^^ done^^^ ^^^%PATH^^^%^^^""',
|
||||
'/d /s /c "C:\\npm\\claude.cmd ^"100^%^ done^ ^%PATH^%^""',
|
||||
);
|
||||
expect(await resolveCmdShimArgs("a^b")).toBe('/d /s /c "C:\\npm\\claude.cmd ^^^"a^^^^b^^^""');
|
||||
expect(await resolveCmdShimArgs("a^b")).toBe('/d /s /c "C:\\npm\\claude.cmd ^"a^^b^""');
|
||||
});
|
||||
|
||||
it("escapes embedded double quotes and backslash runs preceding them", async () => {
|
||||
// The shim reads its arguments again when it forwards `%*`, so an argument with a quote is
|
||||
// escaped twice; its quotes would otherwise leave the rest of the line outside a quoted region.
|
||||
it("escapes an argument with a double quote twice for the shim", async () => {
|
||||
expect(await resolveCmdShimArgs('say "hello" now')).toBe(
|
||||
'/d /s /c "C:\\npm\\claude.cmd ^^^"say^^^ \\^^^"hello\\^^^"^^^ now^^^""',
|
||||
);
|
||||
@@ -359,18 +356,14 @@ describe("createTerminal", () => {
|
||||
);
|
||||
});
|
||||
|
||||
// cmd.exe has no way to escape a literal CR/LF inside one command line
|
||||
// -- its parser treats newlines as command separators regardless of
|
||||
// quoting -- so a raw newline is normalized to a space before escaping.
|
||||
// This is a deliberate choice, not an oversight: it avoids the prompt
|
||||
// ever splitting into a second, attacker-controlled cmd.exe command, at
|
||||
// the cost of losing the original line breaks.
|
||||
it("normalizes embedded newlines to spaces instead of letting them split the command", async () => {
|
||||
// cmd.exe ends a command at a line break whatever the quoting. A terminal prompt often has
|
||||
// several lines, so the terminal starts with each line break as a space instead of refusing.
|
||||
it("joins the lines of a prompt with spaces", async () => {
|
||||
expect(await resolveCmdShimArgs("line one\nline two")).toBe(
|
||||
'/d /s /c "C:\\npm\\claude.cmd ^^^"line^^^ one^^^ line^^^ two^^^""',
|
||||
'/d /s /c "C:\\npm\\claude.cmd ^"line^ one^ line^ two^""',
|
||||
);
|
||||
expect(await resolveCmdShimArgs("line one\r\nline two")).toBe(
|
||||
'/d /s /c "C:\\npm\\claude.cmd ^^^"line^^^ one^^^ line^^^ two^^^""',
|
||||
'/d /s /c "C:\\npm\\claude.cmd ^"line^ one^ line^ two^""',
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -11,9 +11,14 @@ import {
|
||||
statSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir, userInfo } from "node:os";
|
||||
import { basename, delimiter, dirname, extname, join, resolve as resolvePath } from "node:path";
|
||||
import { basename, delimiter, dirname, join, resolve as resolvePath } from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
isWindowsCommandScript,
|
||||
windowsCommandLine,
|
||||
windowsCommandShell,
|
||||
} from "@getpaseo/plugin/internal/windows-command";
|
||||
import { createExternalProcessEnv } from "../server/paseo-env.js";
|
||||
import {
|
||||
resolveExternalProcessPath,
|
||||
@@ -35,6 +40,7 @@ import {
|
||||
import type { TerminalReplayOptions, TerminalReplayMetadata } from "./terminal-replay.js";
|
||||
import { TerminalInputModeTracker } from "@getpaseo/protocol/terminal-input-mode";
|
||||
import { TerminalActivityTracker } from "./activity/terminal-activity-tracker.js";
|
||||
import { resolveDefaultTerminalShell } from "./default-terminal-shell.js";
|
||||
import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
@@ -263,19 +269,6 @@ export function ensureNodePtySpawnHelperExecutableForCurrentPlatform(
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveDefaultTerminalShell(
|
||||
options: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv } = {},
|
||||
): string {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
|
||||
if (platform === "win32") {
|
||||
return env.ComSpec || env.COMSPEC || "C:\\Windows\\System32\\cmd.exe";
|
||||
}
|
||||
|
||||
return env.SHELL || "/bin/sh";
|
||||
}
|
||||
|
||||
export interface ResolvedTerminalCommand {
|
||||
command: string;
|
||||
// `.cmd`/`.bat` targets resolve to a single pre-escaped `cmd.exe` command
|
||||
@@ -295,64 +288,11 @@ export interface ResolveTerminalSpawnCommandOptions {
|
||||
resolveExecutable?: (name: string) => Promise<string | null>;
|
||||
}
|
||||
|
||||
// cmd.exe treats these characters specially even inside a double-quoted
|
||||
// argument, unlike a POSIX shell — quoting alone does not neutralize them.
|
||||
// Prefixing each with `^`, cmd.exe's own escape character, does. Mirrors the
|
||||
// `escape.command` metachar list in the `cross-spawn` npm package (already a
|
||||
// dependency of this repo), which solves this exact `.cmd`/`.bat` spawning
|
||||
// problem — see http://www.robvanderwoude.com/escapechars.php.
|
||||
const CMD_EXE_METACHAR_PATTERN = /([()%!^"`<>&|;, *?])/g;
|
||||
|
||||
function escapeCmdExeMetaChars(text: string): string {
|
||||
return text.replace(CMD_EXE_METACHAR_PATTERN, "^$1");
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape one argument for safe inclusion in a `cmd.exe /c "..."` command
|
||||
* line that is about to invoke a `.cmd`/`.bat` shim.
|
||||
*
|
||||
* node-pty builds an MSVCRT/`CommandLineToArgvW`-style quoted command line
|
||||
* for whatever `command` it is given (double-quote wrap on whitespace,
|
||||
* backslash-escape only backslash runs immediately before a quote). That
|
||||
* quoting is correct for a normal executable, which parses its own argv via
|
||||
* that same convention. It is not correct here: the `command` node-pty
|
||||
* launches for a `.cmd`/`.bat` target is `cmd.exe` itself, and cmd.exe
|
||||
* re-parses the whole line with its *own* tokenizer before ever handing
|
||||
* arguments to the batch script — a tokenizer that treats `&`, `|`, `^`,
|
||||
* `%` (environment-variable expansion), `<`, `>` etc. as live syntax even
|
||||
* inside double quotes. A prompt containing any of those characters would
|
||||
* therefore be interpreted by cmd.exe, not passed through as text — the
|
||||
* same class of hazard tracked upstream as Node's CVE-2024-27980
|
||||
* ("batBadBadging").
|
||||
*
|
||||
* The escaping below is the "qntm" algorithm (https://qntm.org/cmd): double
|
||||
* every backslash run that immediately precedes a quote (or the end of the
|
||||
* argument, since a closing quote is appended next) and escape that quote,
|
||||
* wrap the whole argument in quotes, then caret-escape cmd.exe's
|
||||
* metacharacters — including the quotes just added, because cmd.exe's own
|
||||
* tokenizer runs first and would otherwise treat them as toggling a quoted
|
||||
* region. It is the same algorithm `cross-spawn` uses for its `.cmd`/`.bat`
|
||||
* auto-shell path (`lib/util/escape.js`). Command shims forward `%*`, which
|
||||
* adds a second cmd.exe parse, so metacharacters need a second escape pass to
|
||||
* survive as literal argv in the Node process behind an npm-generated shim.
|
||||
*
|
||||
* cmd.exe has no escape for a literal CR or LF inside a single command
|
||||
* line — its parser treats them as command separators regardless of
|
||||
* quoting, so passing one through verbatim would let a crafted prompt
|
||||
* inject a second, attacker-chosen command after the newline. There is no
|
||||
* fidelity-preserving option for that case, so newlines are normalized to
|
||||
* spaces before quoting: the target process still receives the full text,
|
||||
* just without the original line breaks, instead of cmd.exe splitting the
|
||||
* prompt into multiple commands.
|
||||
*/
|
||||
function escapeCmdExeArgument(rawArg: string): string {
|
||||
const arg = rawArg.replace(/\r\n|\r|\n/g, " ");
|
||||
|
||||
let escaped = arg.replace(/(\\*)"/g, '$1$1\\"');
|
||||
escaped = escaped.replace(/(\\*)$/, "$1$1");
|
||||
escaped = `"${escaped}"`;
|
||||
|
||||
return escapeCmdExeMetaChars(escapeCmdExeMetaChars(escaped));
|
||||
// cmd.exe ends a command at a line break whatever the quoting, so the shared line builder refuses
|
||||
// one. A terminal agent's initial prompt arrives as an argument and often spans lines; it still
|
||||
// starts, with each line break as a space.
|
||||
function joinPromptLines(argument: string): string {
|
||||
return argument.replace(/\r\n|\r|\n/g, " ");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -389,28 +329,15 @@ export async function resolveTerminalSpawnCommand(
|
||||
|
||||
// `.cmd`/`.bat` shims are batch scripts that conpty's CreateProcess cannot
|
||||
// launch directly; they must run through cmd.exe (node-pty has no `shell`
|
||||
// option, so build the `cmd /c` invocation ourselves). Checked by extension
|
||||
// rather than isWindowsCommandScript() because that helper gates on the live
|
||||
// process.platform, which is wrong once we're already on the win32 branch.
|
||||
const extension = extname(resolved).toLowerCase();
|
||||
if (extension === ".cmd" || extension === ".bat") {
|
||||
const env = options.env ?? process.env;
|
||||
const comSpec = env.ComSpec || env.COMSPEC || "C:\\Windows\\System32\\cmd.exe";
|
||||
// Build the `/c` command line ourselves — as a single pre-escaped
|
||||
// string, not an argv array — so node-pty's own array quoting never
|
||||
// runs over these values; see escapeCmdExeArgument for why that
|
||||
// quoting alone is not safe once cmd.exe re-parses the line. `resolved`
|
||||
// gets the same metachar (not quote-wrap) treatment as the args: it
|
||||
// isn't attacker-controlled, but it now sits inside the same joined
|
||||
// command line and needs to survive cmd.exe's tokenizer too (e.g. a
|
||||
// space in the install path).
|
||||
const commandLine = [
|
||||
"/d",
|
||||
"/s",
|
||||
"/c",
|
||||
`"${[escapeCmdExeMetaChars(resolved), ...args.map(escapeCmdExeArgument)].join(" ")}"`,
|
||||
].join(" ");
|
||||
return { command: comSpec, args: commandLine };
|
||||
// option, so build the `cmd /c` invocation ourselves).
|
||||
if (isWindowsCommandScript(resolved, platform)) {
|
||||
// node-pty quotes an argv array for a program's own parser, which cmd.exe does not use, so the
|
||||
// `/c` line goes to it as one string that the shared cmd.exe dialect has already quoted.
|
||||
const line = windowsCommandLine(resolved, args.map(joinPromptLines), { commandScript: true });
|
||||
return {
|
||||
command: windowsCommandShell(options.env ?? process.env),
|
||||
args: `/d /s /c ${line}`,
|
||||
};
|
||||
}
|
||||
|
||||
return { command: resolved, args };
|
||||
|
||||
@@ -113,7 +113,8 @@ let safeBareRepositorySupport: Promise<boolean> | null = null;
|
||||
|
||||
/** Reads `git --version` once per process. */
|
||||
export function readSafeBareRepositorySupport(): Promise<boolean> {
|
||||
safeBareRepositorySupport ??= execCommand("git", ["--version"]).then(
|
||||
// Started like every daemon git command, directly and without a PATH lookup in Node.
|
||||
safeBareRepositorySupport ??= execCommand("git", ["--version"], { shell: false }).then(
|
||||
({ stdout }) => parseSafeBareRepositorySupport(stdout),
|
||||
() => false,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/** A plugin's launch wrap: an absolute executable and its arguments. */
|
||||
export type LaunchWrap = readonly [string, ...string[]];
|
||||
|
||||
export interface CommandLaunch {
|
||||
command: string;
|
||||
args: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The launch that starts `launch` behind `wrap`: `[...wrap, command, ...args]`. Use it where the
|
||||
* process is not started by `spawnProcess`, which takes the wrap as an option.
|
||||
*/
|
||||
export function applyLaunchWrap(
|
||||
launch: CommandLaunch,
|
||||
wrap: LaunchWrap | undefined,
|
||||
): CommandLaunch {
|
||||
if (!wrap) return launch;
|
||||
const [executable, ...wrapArgs] = wrap;
|
||||
return { command: executable, args: [...wrapArgs, launch.command, ...launch.args] };
|
||||
}
|
||||
@@ -127,6 +127,7 @@ async function runFixture(params: {
|
||||
args: string[];
|
||||
shell?: boolean;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
expectedArgs?: string[];
|
||||
}): Promise<SpawnResult> {
|
||||
const child = spawnProcess(params.command, params.args, {
|
||||
env: {
|
||||
@@ -135,7 +136,7 @@ async function runFixture(params: {
|
||||
// Terminal color settings must not add Node warnings to the argv fixture's stderr.
|
||||
NO_COLOR: undefined,
|
||||
FORCE_COLOR: undefined,
|
||||
PASEO_EXPECTED_ARGV_JSON: JSON.stringify(["--config", JSON_ARG]),
|
||||
PASEO_EXPECTED_ARGV_JSON: JSON.stringify(params.expectedArgs ?? ["--config", JSON_ARG]),
|
||||
},
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
...(params.shell === undefined ? {} : { shell: params.shell }),
|
||||
@@ -278,6 +279,18 @@ describe.runIf(isPlatform("win32"))("Windows spawn launch regression", () => {
|
||||
expect(result.stdout.trim()).toBe("ARGV_OK");
|
||||
});
|
||||
|
||||
// A plugin launch wrap can pass an empty argument to a .cmd launcher; cmd.exe must keep its slot.
|
||||
test("launches a cmd shim with an empty argument in its position", async () => {
|
||||
const fixture = makeFixture();
|
||||
const args = ["--profile", "", "--config", JSON_ARG];
|
||||
|
||||
const result = await runFixture({ command: fixture.shim, args, expectedArgs: args });
|
||||
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.stdout.trim()).toBe("ARGV_OK");
|
||||
expect(result.code).toBe(0);
|
||||
});
|
||||
|
||||
test("direct launch with a space-containing executable preserves JSON args", async () => {
|
||||
const fixture = makeFixture();
|
||||
|
||||
|
||||
@@ -21,11 +21,8 @@ function writeEchoArgScript(): string {
|
||||
return scriptPath;
|
||||
}
|
||||
|
||||
// Use the bare command name "node" (no extension, no path separator) so
|
||||
// `shouldUseWindowsShell` resolves to true on Windows. That routes the spawn
|
||||
// through cmd.exe and exercises `quoteWindowsArgument`, which is where the
|
||||
// %-doubling bug lives. Using `process.execPath` here would skip the shell
|
||||
// path entirely and silently pass the test.
|
||||
// Use the bare command name "node" (no extension, no path separator), the way callers name
|
||||
// tools, so the launch goes through the Windows PATH lookup before it starts.
|
||||
const COMMAND = "node";
|
||||
|
||||
describe("spawn argument escaping for % characters", () => {
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import type { ChildProcess, SpawnOptions } from "node:child_process";
|
||||
import { spawnProcess as spawnCli, execCommand as execCli } from "@getpaseo/plugin/server";
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import {
|
||||
spawnProcess as spawnCli,
|
||||
execCommand as execCli,
|
||||
type SpawnProcessOptions as CliSpawnOptions,
|
||||
} from "@getpaseo/plugin/server";
|
||||
import { createExternalCommandProcessEnv, type ProcessEnvRecord } from "../server/paseo-env.js";
|
||||
|
||||
interface ExternalEnvOptions {
|
||||
@@ -9,7 +13,7 @@ interface ExternalEnvOptions {
|
||||
envOverlay?: ProcessEnvRecord;
|
||||
}
|
||||
|
||||
export type SpawnProcessOptions = Omit<SpawnOptions, "env"> & ExternalEnvOptions;
|
||||
export type SpawnProcessOptions = Omit<CliSpawnOptions, "env"> & ExternalEnvOptions;
|
||||
|
||||
interface ExecCommandOptions extends ExternalEnvOptions {
|
||||
cwd?: string;
|
||||
|
||||
@@ -882,6 +882,100 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
|
||||
expect(portValue).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("runs each setup command behind a plugin's wrap and stops at a refused one", async () => {
|
||||
// The launcher records the argv it was given, marks the environment, then runs the rest.
|
||||
const launcher = join(repoDir, "launcher.sh");
|
||||
writeFileSync(
|
||||
launcher,
|
||||
'#!/bin/sh\nprintf "%s\\n" "$@" > "$(dirname "$0")/launch-argv.log"\nshift 2\nexport INSIDE=wrapped\nexec "$@"\n',
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
writeFileSync(
|
||||
join(repoDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: {
|
||||
setup: [
|
||||
'echo "$HOOK_MARK" > first.log && echo "$INSIDE" > second-part.log',
|
||||
"echo refused > refused.log",
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
const seen: string[] = [];
|
||||
const setup = runWorktreeSetupCommands({
|
||||
worktreePath: repoDir,
|
||||
branchName: "main",
|
||||
runtimeEnv: {
|
||||
PASEO_SOURCE_CHECKOUT_PATH: repoDir,
|
||||
PASEO_ROOT_PATH: repoDir,
|
||||
PASEO_WORKTREE_PATH: repoDir,
|
||||
PASEO_BRANCH_NAME: "main",
|
||||
PASEO_WORKTREE_PORT: "12345",
|
||||
},
|
||||
prepareCommand: async ({ command, env }) => {
|
||||
seen.push(`${command} ${env.PASEO_BRANCH_NAME}`);
|
||||
if (command.startsWith("echo refused")) throw new Error("not in this workspace");
|
||||
return { env: { ...env, HOOK_MARK: "prepared" }, wrap: [launcher, "--profile", "a b"] };
|
||||
},
|
||||
});
|
||||
|
||||
await expect(setup).rejects.toMatchObject({
|
||||
name: "WorktreeSetupError",
|
||||
message:
|
||||
"Worktree setup command refused: echo refused > refused.log\nnot in this workspace",
|
||||
results: [expect.objectContaining({ exitCode: 0 })],
|
||||
});
|
||||
expect(seen).toEqual([
|
||||
'echo "$HOOK_MARK" > first.log && echo "$INSIDE" > second-part.log main',
|
||||
"echo refused > refused.log main",
|
||||
]);
|
||||
expect(readFileSync(join(repoDir, "launch-argv.log"), "utf8").trim().split("\n")).toEqual([
|
||||
"--profile",
|
||||
"a b",
|
||||
"bash",
|
||||
"-c",
|
||||
'echo "$HOOK_MARK" > first.log && echo "$INSIDE" > second-part.log',
|
||||
]);
|
||||
expect(readFileSync(join(repoDir, "first.log"), "utf8").trim()).toBe("prepared");
|
||||
// The part after `&&` ran inside the launcher too.
|
||||
expect(readFileSync(join(repoDir, "second-part.log"), "utf8").trim()).toBe("wrapped");
|
||||
expect(existsSync(join(repoDir, "refused.log"))).toBe(false);
|
||||
});
|
||||
|
||||
it("reports a streamed setup command that cannot start as a failed command", async () => {
|
||||
// Node refuses a null byte in an argument before it starts the process, as the SDK refuses a
|
||||
// line break for a Windows cmd.exe launch.
|
||||
writeFileSync(
|
||||
join(repoDir, "paseo.json"),
|
||||
JSON.stringify({ worktree: { setup: "echo a\0b" } }),
|
||||
);
|
||||
const events: string[] = [];
|
||||
const setup = runWorktreeSetupCommands({
|
||||
worktreePath: repoDir,
|
||||
branchName: "main",
|
||||
runtimeEnv: {
|
||||
PASEO_SOURCE_CHECKOUT_PATH: repoDir,
|
||||
PASEO_ROOT_PATH: repoDir,
|
||||
PASEO_WORKTREE_PATH: repoDir,
|
||||
PASEO_BRANCH_NAME: "main",
|
||||
PASEO_WORKTREE_PORT: "12345",
|
||||
},
|
||||
signal: new AbortController().signal,
|
||||
onEvent: (event) => events.push(event.type),
|
||||
});
|
||||
|
||||
await expect(setup).rejects.toMatchObject({
|
||||
name: "WorktreeSetupError",
|
||||
results: [
|
||||
expect.objectContaining({
|
||||
exitCode: null,
|
||||
stderr: expect.stringContaining("null bytes"),
|
||||
}),
|
||||
],
|
||||
});
|
||||
expect(events).toEqual(["command_started", "output", "command_completed"]);
|
||||
});
|
||||
|
||||
it("runs string setup scripts from paseo.json as a single shell command", async () => {
|
||||
const paseoConfig = {
|
||||
worktree: {
|
||||
|
||||
@@ -223,6 +223,45 @@ describe("paseo worktree manager", () => {
|
||||
}).toEqual({ exitCode: 0, stdoutLength: limit, stderrLength: limit });
|
||||
});
|
||||
|
||||
it("stops teardown at its deadline while a plugin hook is pending, without starting the command", async () => {
|
||||
writeFileSync(
|
||||
join(repoDir, "paseo.json"),
|
||||
JSON.stringify({
|
||||
worktree: {
|
||||
teardown: `node -e "require('fs').writeFileSync('ran.txt', 'ran')"`,
|
||||
teardownTimeoutMs: 100,
|
||||
},
|
||||
}),
|
||||
);
|
||||
let hookDone!: () => void;
|
||||
const hookSettled = new Promise<void>((resolve) => {
|
||||
hookDone = resolve;
|
||||
});
|
||||
|
||||
const startedAt = Date.now();
|
||||
await expect(
|
||||
runWorktreeTeardownCommands({
|
||||
worktreePath: repoDir,
|
||||
repoRootPath: repoDir,
|
||||
branchName: "main",
|
||||
prepareCommand: async ({ env }) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
hookDone();
|
||||
return { env };
|
||||
},
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
name: "WorktreeTeardownError",
|
||||
message: `Worktree teardown command failed: node -e "require('fs').writeFileSync('ran.txt', 'ran')"\nTimed out after 0.1s`,
|
||||
results: [],
|
||||
});
|
||||
expect(Date.now() - startedAt).toBeLessThan(900);
|
||||
// The hook answering after the deadline does not start the command.
|
||||
await hookSettled;
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
expect(existsSync(join(repoDir, "ran.txt"))).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects paths that are not under the paseo worktrees root", async () => {
|
||||
const outsidePath = join(tempDir, "outside-paseo-home");
|
||||
mkdirSync(outsidePath, { recursive: true });
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { execFile } from "child_process";
|
||||
import { promisify } from "util";
|
||||
import { constants as fsConstants, type Dirent, realpath } from "fs";
|
||||
import { copyFile, mkdir, readdir, rm, stat } from "fs/promises";
|
||||
@@ -7,9 +6,11 @@ import net from "node:net";
|
||||
import { createHash } from "node:crypto";
|
||||
import stripAnsi from "strip-ansi";
|
||||
import pLimit from "p-limit";
|
||||
import { execCommand } from "@getpaseo/plugin/server";
|
||||
import {
|
||||
buildStringCommandShellInvocation,
|
||||
createStringCommandShellEnv,
|
||||
type StringCommandShellInvocation,
|
||||
} from "./string-command-shell.js";
|
||||
import { readPaseoConfig } from "./paseo-config-file.js";
|
||||
export {
|
||||
@@ -38,6 +39,7 @@ import { runWithRepositoryRoot } from "./git-repository-discovery.js";
|
||||
import { runGitCommand } from "./run-git-command.js";
|
||||
import { getCurrentBranch, resolveRepositoryDefaultBranch } from "./checkout-git.js";
|
||||
import { spawnProcess } from "./spawn.js";
|
||||
import { applyLaunchWrap } from "./launch-wrap.js";
|
||||
import { resolvePaseoHome } from "../server/paseo-home.js";
|
||||
import { createExternalProcessEnv } from "../server/paseo-env.js";
|
||||
import { parseGitRevParsePath, resolveGitRevParsePath } from "./git-rev-parse-path.js";
|
||||
@@ -55,7 +57,6 @@ import type { PluginWorktreeManagerRuntime } from "../server/plugins/runtime.js"
|
||||
|
||||
export { slugify, validateBranchSlug } from "@getpaseo/protocol/branch-slug";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const READ_ONLY_GIT_ENV = {
|
||||
GIT_OPTIONAL_LOCKS: "0",
|
||||
} as const;
|
||||
@@ -140,6 +141,64 @@ export function isServiceScript(config: ScriptConfig): config is ServiceScriptCo
|
||||
return "type" in config && config.type === "service";
|
||||
}
|
||||
|
||||
/** A lifecycle command, and the environment Paseo adds to the daemon's for it. */
|
||||
export interface WorktreeLifecycleCommand {
|
||||
command: string;
|
||||
env: Record<string, string>;
|
||||
}
|
||||
|
||||
/** How a lifecycle command runs after plugins saw it: its environment and an optional wrap. */
|
||||
export interface PreparedWorktreeLifecycleCommand {
|
||||
env: Record<string, string>;
|
||||
wrap?: readonly [string, ...string[]];
|
||||
}
|
||||
|
||||
/** Lets plugins wrap or refuse a lifecycle command before it runs; see `command.run.before`. */
|
||||
export type PrepareWorktreeLifecycleCommand = (
|
||||
command: WorktreeLifecycleCommand,
|
||||
) => Promise<PreparedWorktreeLifecycleCommand>;
|
||||
|
||||
/**
|
||||
* Asks the hooks how to run `command`. Resolves to `null` when `signal` aborts first, such as at the
|
||||
* teardown deadline or when archive cancels setup; the command must then not start.
|
||||
*/
|
||||
async function prepareLifecycleCommand(options: {
|
||||
prepare: PrepareWorktreeLifecycleCommand | undefined;
|
||||
command: WorktreeLifecycleCommand;
|
||||
signal: AbortSignal | undefined;
|
||||
fail: (message: string) => Error;
|
||||
}): Promise<PreparedWorktreeLifecycleCommand | null> {
|
||||
const { prepare, command, signal } = options;
|
||||
if (signal?.aborted) return null;
|
||||
if (!prepare) return { env: command.env };
|
||||
let stopWaiting = () => {};
|
||||
const aborted = new Promise<null>((settle) => {
|
||||
const onAbort = () => settle(null);
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
stopWaiting = () => signal?.removeEventListener("abort", onAbort);
|
||||
});
|
||||
const prepared = prepare(command).catch((error: unknown) => {
|
||||
throw options.fail(error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
// A hook that settles after the abort no longer matters; keep its rejection handled.
|
||||
prepared.catch(() => {});
|
||||
try {
|
||||
return await Promise.race([prepared, aborted]);
|
||||
} finally {
|
||||
stopWaiting();
|
||||
}
|
||||
}
|
||||
|
||||
/** The shell invocation for a `paseo.json` command, started behind a plugin's wrap when set. */
|
||||
function lifecycleCommandInvocation(
|
||||
command: string,
|
||||
wrap: PreparedWorktreeLifecycleCommand["wrap"],
|
||||
): StringCommandShellInvocation {
|
||||
const invocation = buildStringCommandShellInvocation({ command });
|
||||
const launch = applyLaunchWrap({ command: invocation.shell, args: invocation.args }, wrap);
|
||||
return { shell: launch.command, args: launch.args };
|
||||
}
|
||||
|
||||
export class WorktreeSetupError extends Error {
|
||||
readonly results: WorktreeSetupCommandResult[];
|
||||
|
||||
@@ -445,14 +504,16 @@ export function processCarriageReturns(text: string): string {
|
||||
|
||||
async function execSetupCommand(
|
||||
command: string,
|
||||
options: { cwd: string; env: NodeJS.ProcessEnv },
|
||||
options: { cwd: string; env: NodeJS.ProcessEnv; wrap: PreparedWorktreeLifecycleCommand["wrap"] },
|
||||
): Promise<WorktreeSetupCommandResult> {
|
||||
const startedAt = Date.now();
|
||||
const shellInvocation = buildStringCommandShellInvocation({ command });
|
||||
const shellInvocation = lifecycleCommandInvocation(command, options.wrap);
|
||||
try {
|
||||
const { stdout, stderr } = await execFileAsync(shellInvocation.shell, shellInvocation.args, {
|
||||
// execCommand starts a Windows `.cmd` or `.bat` wrap through cmd.exe; anything else has no shell.
|
||||
const { stdout, stderr } = await execCommand(shellInvocation.shell, shellInvocation.args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
shell: false,
|
||||
});
|
||||
return {
|
||||
command,
|
||||
@@ -477,6 +538,7 @@ async function execSetupCommand(
|
||||
|
||||
async function execSetupCommandStreamed(options: {
|
||||
command: string;
|
||||
wrap: PreparedWorktreeLifecycleCommand["wrap"];
|
||||
cwd: string;
|
||||
env: NodeJS.ProcessEnv;
|
||||
index: number;
|
||||
@@ -556,21 +618,29 @@ async function execSetupCommandStreamed(options: {
|
||||
cwd: options.cwd,
|
||||
});
|
||||
|
||||
const shellInvocation = buildStringCommandShellInvocation({ command: options.command });
|
||||
const child = spawnProcess(shellInvocation.shell, shellInvocation.args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
shell: false,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const shellInvocation = lifecycleCommandInvocation(options.command, options.wrap);
|
||||
let child: ReturnType<typeof spawnProcess>;
|
||||
try {
|
||||
child = spawnProcess(shellInvocation.shell, shellInvocation.args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
shell: false,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
} catch (error) {
|
||||
// A command that cannot start fails like one whose process reports a spawn error.
|
||||
emitOutput("stderr", error instanceof Error ? error.message : String(error));
|
||||
void finish(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const abort = () => {
|
||||
function abort(): void {
|
||||
termination ??= terminateWithTreeKill(child, {
|
||||
gracefulTimeoutMs: 1000,
|
||||
forceTimeoutMs: 1000,
|
||||
});
|
||||
void finish(null);
|
||||
};
|
||||
}
|
||||
if (options.signal?.aborted) {
|
||||
abort();
|
||||
} else {
|
||||
@@ -678,6 +748,7 @@ export async function runWorktreeSetupCommands(options: {
|
||||
runtimeEnv?: WorktreeRuntimeEnv;
|
||||
signal?: AbortSignal;
|
||||
onEvent?: (event: WorktreeSetupCommandProgressEvent) => void;
|
||||
prepareCommand?: PrepareWorktreeLifecycleCommand;
|
||||
}): Promise<WorktreeSetupCommandResult[]> {
|
||||
// Read paseo.json from the worktree (it will have the same content as the source repo)
|
||||
const setupCommands = await getWorktreeSetupCommands(options.worktreePath);
|
||||
@@ -692,13 +763,26 @@ export async function runWorktreeSetupCommands(options: {
|
||||
branchName: options.branchName,
|
||||
...(options.repoRootPath ? { repoRootPath: options.repoRootPath } : {}),
|
||||
}));
|
||||
const setupEnv = createStringCommandShellEnv(createExternalProcessEnv(process.env, runtimeEnv));
|
||||
|
||||
const results: WorktreeSetupCommandResult[] = [];
|
||||
for (const [index, cmd] of setupCommands.entries()) {
|
||||
const prepared = await prepareLifecycleCommand({
|
||||
prepare: options.prepareCommand,
|
||||
command: { command: cmd, env: { ...runtimeEnv } },
|
||||
signal: options.signal,
|
||||
fail: (message) =>
|
||||
new WorktreeSetupError(`Worktree setup command refused: ${cmd}\n${message}`, results),
|
||||
});
|
||||
if (!prepared) {
|
||||
throw new WorktreeSetupError(`Worktree setup canceled before: ${cmd}`, results);
|
||||
}
|
||||
const setupEnv = createStringCommandShellEnv(
|
||||
createExternalProcessEnv(process.env, prepared.env),
|
||||
);
|
||||
const result = options.onEvent
|
||||
? await execSetupCommandStreamed({
|
||||
command: cmd,
|
||||
wrap: prepared.wrap,
|
||||
cwd: options.worktreePath,
|
||||
env: setupEnv,
|
||||
index: index + 1,
|
||||
@@ -709,6 +793,7 @@ export async function runWorktreeSetupCommands(options: {
|
||||
: await execSetupCommand(cmd, {
|
||||
cwd: options.worktreePath,
|
||||
env: setupEnv,
|
||||
wrap: prepared.wrap,
|
||||
});
|
||||
results.push(result);
|
||||
|
||||
@@ -779,6 +864,7 @@ export async function runWorktreeTeardownCommands(options: {
|
||||
teardownCwd?: string;
|
||||
branchName?: string;
|
||||
repoRootPath?: string;
|
||||
prepareCommand?: PrepareWorktreeLifecycleCommand;
|
||||
}): Promise<WorktreeTeardownCommandResult[]> {
|
||||
const teardownCwd = options.teardownCwd ?? options.worktreePath;
|
||||
if ((await getOwnershipRelativePath(options.worktreePath, teardownCwd)) === null) {
|
||||
@@ -795,29 +881,41 @@ export async function runWorktreeTeardownCommands(options: {
|
||||
options.branchName ?? (await resolveBranchNameForWorktreePath(options.worktreePath));
|
||||
const worktreePort = await readPaseoWorktreeRuntimePort(options.worktreePath);
|
||||
|
||||
const teardownEnv: NodeJS.ProcessEnv = createStringCommandShellEnv(
|
||||
createExternalProcessEnv(process.env, {
|
||||
// Source checkout path is the original git repo root (shared across worktrees), not the
|
||||
// worktree itself. This allows lifecycle scripts to copy or clean resources using paths
|
||||
// from the source checkout.
|
||||
PASEO_SOURCE_CHECKOUT_PATH: repoRootPath,
|
||||
// Backward-compatible alias.
|
||||
PASEO_ROOT_PATH: repoRootPath,
|
||||
PASEO_WORKTREE_PATH: options.worktreePath,
|
||||
PASEO_BRANCH_NAME: branchName,
|
||||
...(worktreePort !== null ? { PASEO_WORKTREE_PORT: String(worktreePort) } : {}),
|
||||
}),
|
||||
);
|
||||
const runtimeEnv: Record<string, string> = {
|
||||
// Source checkout path is the original git repo root (shared across worktrees), not the
|
||||
// worktree itself. This allows lifecycle scripts to copy or clean resources using paths
|
||||
// from the source checkout.
|
||||
PASEO_SOURCE_CHECKOUT_PATH: repoRootPath,
|
||||
// Backward-compatible alias.
|
||||
PASEO_ROOT_PATH: repoRootPath,
|
||||
PASEO_WORKTREE_PATH: options.worktreePath,
|
||||
PASEO_BRANCH_NAME: branchName,
|
||||
...(worktreePort !== null ? { PASEO_WORKTREE_PORT: String(worktreePort) } : {}),
|
||||
};
|
||||
|
||||
// One deadline covers every command. Reaching it counts as failure and keeps the worktree.
|
||||
const timeoutMs = await getWorktreeTeardownTimeoutMs(teardownCwd);
|
||||
const deadline = AbortSignal.timeout(timeoutMs);
|
||||
const results: WorktreeTeardownCommandResult[] = [];
|
||||
for (const [index, cmd] of teardownCommands.entries()) {
|
||||
const prepared = await prepareLifecycleCommand({
|
||||
prepare: options.prepareCommand,
|
||||
command: { command: cmd, env: { ...runtimeEnv } },
|
||||
signal: deadline,
|
||||
fail: (message) =>
|
||||
new WorktreeTeardownError(`Worktree teardown command refused: ${cmd}\n${message}`, results),
|
||||
});
|
||||
if (!prepared) {
|
||||
throw new WorktreeTeardownError(
|
||||
`Worktree teardown command failed: ${cmd}\nTimed out after ${timeoutMs / 1000}s`,
|
||||
results,
|
||||
);
|
||||
}
|
||||
const result = await execSetupCommandStreamed({
|
||||
command: cmd,
|
||||
wrap: prepared.wrap,
|
||||
cwd: teardownCwd,
|
||||
env: teardownEnv,
|
||||
env: createStringCommandShellEnv(createExternalProcessEnv(process.env, prepared.env)),
|
||||
index: index + 1,
|
||||
total: teardownCommands.length,
|
||||
signal: deadline,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
# Lifecycle logger
|
||||
|
||||
Registers agent, workspace, and worktree hooks and logs their data as JSON. It observes agent creation,
|
||||
session opening, turns, permissions, archive, and workspace creation/archive. Before hooks return
|
||||
Registers agent, workspace, worktree, terminal, and command hooks and logs their data as JSON. It
|
||||
observes agent creation, session opening, turns, permissions, archive, workspace creation/archive,
|
||||
terminal creation, and worktree setup and teardown commands. Before hooks return
|
||||
the request unchanged. Environment values are redacted; prompts and timeline content are logged.
|
||||
|
||||
Install it on a daemon where plugins are enabled:
|
||||
|
||||
@@ -57,5 +57,15 @@ export default function contribute(server: PluginServerContext) {
|
||||
logHook("agent.archive.after", event);
|
||||
});
|
||||
|
||||
server.addHook("terminal.create.before", async ({ request }) => {
|
||||
logHook("terminal.create.before", { request });
|
||||
return request;
|
||||
});
|
||||
|
||||
server.addHook("command.run.before", async ({ request }) => {
|
||||
logHook("command.run.before", { request });
|
||||
return request;
|
||||
});
|
||||
|
||||
return () => {};
|
||||
}
|
||||
|
||||
@@ -886,3 +886,75 @@ it("keeps a turn open for backgrounded run_command calls but not IsDaemon comman
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("runs a wrapped session as [...wrap, agy, acp, --disable-telemetry] with the session env", async () => {
|
||||
const { directory, launch: fixture } = await launchAgent(`
|
||||
const { createInterface } = require("node:readline");
|
||||
const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
|
||||
createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const { id, method } = JSON.parse(line);
|
||||
if (method === "initialize") send({ id, result: { protocolVersion: 1 } });
|
||||
if (method === "session/new") {
|
||||
send({ id, result: { sessionId: "native", configOptions: [{ id: "mode", name: "Mode", category: "mode", type: "select", currentValue: "default", options: [{ value: "default", name: "Default" }] }] } });
|
||||
send({ method: "session/update", params: { sessionId: "native", update: { sessionUpdate: "available_commands_update", availableCommands: [] } } });
|
||||
}
|
||||
});
|
||||
`);
|
||||
// Records what it was started with, then runs the rest: the provider's own launch.
|
||||
const launcher = path.join(directory, "launcher.cjs");
|
||||
const record = path.join(directory, "launch.json");
|
||||
await writeFile(
|
||||
launcher,
|
||||
`const { writeFileSync } = require("node:fs");
|
||||
const { spawn } = require("node:child_process");
|
||||
const [log, command, ...args] = process.argv.slice(2);
|
||||
writeFileSync(log, JSON.stringify({ argv: process.argv.slice(2), hook: process.env.HOOK_ENV ?? null }));
|
||||
const child = spawn(command, args, { stdio: "inherit" });
|
||||
process.on("SIGTERM", () => child.kill("SIGTERM"));
|
||||
child.on("exit", (code) => process.exit(code ?? 1));
|
||||
`,
|
||||
);
|
||||
const provider = createAntigravityProvider();
|
||||
expect(provider.launchWrap).toBe(true);
|
||||
// The daemon resolves the registration's executable and passes its arguments as declared;
|
||||
// Node running the fake agent stands in for the resolved `agy`.
|
||||
const [executable, ...declaredArgs] = provider.command!;
|
||||
expect(executable).toBe("agy");
|
||||
const agentScript = fixture.args[0]!;
|
||||
const launch = { ...fixture, args: [agentScript, ...declaredArgs] };
|
||||
const connection = await provider.connect({
|
||||
launch,
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message", "session.launch_wrap"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send({
|
||||
type: "session.open",
|
||||
requestId: "new",
|
||||
sessionId: "test",
|
||||
history: "skip",
|
||||
config: {
|
||||
cwd: directory,
|
||||
env: { HOOK_ENV: "final" },
|
||||
mcpServers: {},
|
||||
settings: {},
|
||||
persist: false,
|
||||
wrap: [process.execPath, launcher, record],
|
||||
},
|
||||
});
|
||||
await expect
|
||||
.poll(() =>
|
||||
events.find((event) => event.type === "session.ready" || event.type === "request.failed"),
|
||||
)
|
||||
.toMatchObject({ type: "session.ready" });
|
||||
const launched = JSON.parse(await readFile(record, "utf8"));
|
||||
expect(launched).toEqual({
|
||||
argv: [record, process.execPath, agentScript, "acp", "--disable-telemetry"],
|
||||
hook: "final",
|
||||
});
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user