Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,12 @@ for intentional non-interactive execution, `--json` for structured output and
`--scope user|workspace` to choose installation scope. Marketplace Git access
behind a proxy uses `ZCODE_HTTP_PROXY`.

Each launcher plugin request has a 60-second timeout. For slow marketplace or
plugin downloads, set `ZCODE_PLUGIN_REQUEST_TIMEOUT_MS` to a larger duration in
milliseconds. For marketplace addition/update and plugin installation,
cancellation asks the runtime to stop the operation and release its storage lock
before the launcher terminates an unresponsive app-server.

Plugins with configuration can load options from a JSON file without exposing
values in the process argument list:

Expand Down
8 changes: 8 additions & 0 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,14 @@ export ZCODE_TUI_NOTIFICATION_CONDITION=always # unfocused|always
zcode
```

## Plugin request timeout

Launcher plugin requests time out after 60 seconds. Set
`ZCODE_PLUGIN_REQUEST_TIMEOUT_MS` to a positive integer in milliseconds (up to
2147483647) to allow longer downloads. Marketplace addition/update and plugin
installation request runtime cleanup on timeout or cancellation before terminating
an unresponsive app-server.

## Official MCP Availability

When the bundled runtime has no official MCP trusted-origin registry, official
Expand Down
6 changes: 6 additions & 0 deletions docs/CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,12 @@ export ZCODE_TUI_NOTIFICATION_CONDITION=always # unfocused|always
zcode
```

## 插件请求超时

启动器的插件请求默认在 60 秒后超时。下载较慢时,可将
`ZCODE_PLUGIN_REQUEST_TIMEOUT_MS` 设置为更大的正整数毫秒值(最大 2147483647)。
添加或更新市场、安装插件时,超时或取消会先请求 runtime 清理操作,再终止无响应的 app-server。

## 官方 MCP 可用性

如果捆绑 runtime 没有官方 MCP 的可信来源 registry,官方 HTTP MCP 服务会显示为禁用,
Expand Down
42 changes: 39 additions & 3 deletions src/app-server-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { StringDecoder } from "node:string_decoder";

const maximumOutputBytes = 16 * 1024 * 1024;
const forceTerminationDelayMilliseconds = 500;
const cooperativeCancellationDelayMilliseconds = 3_000;

export interface AppServerTransport {
args: string[];
Expand All @@ -14,10 +15,12 @@ export interface AppServerTransport {
}

export interface AppServerRequest {
cancellation?: { method: string; params: Record<string, unknown> };
method: string;
onStderr?: (stderr: string) => void;
params: Record<string, unknown>;
signal?: AbortSignal;
timeoutMs?: number;
transport: AppServerTransport;
}

Expand Down Expand Up @@ -56,6 +59,13 @@ export class AppServerCancellationError extends Error {
}
}

export class AppServerTimeoutError extends Error {
constructor(public readonly timeoutMs: number) {
super(`App-server request timed out after ${timeoutMs}ms.`);
this.name = "TimeoutError";
}
}

function signalExitCode(signal: NodeJS.Signals | null): number {
if (!signal) return 1;
const number = (osConstants.signals as Record<string, number>)[signal];
Expand Down Expand Up @@ -120,6 +130,10 @@ function responseEnvelope(stdout: string): AppServerEnvelope | undefined {

export async function requestAppServer(request: AppServerRequest): Promise<unknown> {
if (request.signal?.aborted) throw cancellationError(request.signal);
if (request.timeoutMs !== undefined && (!Number.isInteger(request.timeoutMs)
|| request.timeoutMs <= 0 || request.timeoutMs > 2_147_483_647)) {
throw new Error("App-server timeoutMs must be an integer between 1 and 2147483647.");
}

const child = spawn(request.transport.command, request.transport.args, {
cwd: request.transport.cwd,
Expand All @@ -130,6 +144,9 @@ export async function requestAppServer(request: AppServerRequest): Promise<unkno
let launchError: Error | undefined;
let overflow = false;
let forceTerminationTimer: NodeJS.Timeout | undefined;
let requestTimeoutTimer: NodeJS.Timeout | undefined;
let timedOut = false;
let cancelling = false;
const exited = new Promise<number>((resolve) => {
let settled = false;
const finish = (code: number) => {
Expand All @@ -147,16 +164,27 @@ export async function requestAppServer(request: AppServerRequest): Promise<unkno
overflow = true;
child.kill("SIGKILL");
};
const onAbort = () => {
const terminate = () => {
if (child.exitCode !== null || child.signalCode !== null) return;
child.kill(terminationSignal(request.signal));
forceTerminationTimer = setTimeout(() => {
if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
}, forceTerminationDelayMilliseconds);
forceTerminationTimer.unref();
};
request.signal?.addEventListener("abort", onAbort, { once: true });
if (request.signal?.aborted) onAbort();
const onAbort = () => {
if (cancelling || child.exitCode !== null || child.signalCode !== null) return;
cancelling = true;
if (requestTimeoutTimer) clearTimeout(requestTimeoutTimer);
if (request.cancellation && !child.stdin.writableEnded && !child.stdin.destroyed) {
// Serial app-server handlers may not read the cancellation until the original
// request finishes. EOF also triggers client-disconnect cancellation so the
// runtime can abort downloads and unwind its storage-lock finally blocks.
child.stdin.end(`${JSON.stringify({ id: 2, ...request.cancellation })}\n`);
forceTerminationTimer = setTimeout(terminate, cooperativeCancellationDelayMilliseconds);
forceTerminationTimer.unref();
} else terminate();
};

child.stdin.on("error", () => {});
// 3.14 treats stdin EOF as client disconnection and cancels outstanding work.
Expand All @@ -173,13 +201,20 @@ export async function requestAppServer(request: AppServerRequest): Promise<unkno
}
});
child.stdin.write(`${JSON.stringify({ id: 1, method: request.method, params: request.params })}\n`);
request.signal?.addEventListener("abort", onAbort, { once: true });
if (request.signal?.aborted) onAbort();
else if (request.timeoutMs !== undefined) {
requestTimeoutTimer = setTimeout(() => { timedOut = true; onAbort(); }, request.timeoutMs);
requestTimeoutTimer.unref();
}

try {
const [code, stdout, stderr] = await Promise.all([
exited,
stdoutPromise,
readBounded(child.stderr, terminateForOverflow)
]);
if (timedOut) throw new AppServerTimeoutError(request.timeoutMs!);
if (request.signal?.aborted) throw cancellationError(request.signal);
if (overflow) throw new Error(`App-server output exceeded ${maximumOutputBytes} bytes.`);
if (launchError) throw launchError;
Expand All @@ -201,6 +236,7 @@ export async function requestAppServer(request: AppServerRequest): Promise<unkno
if (stderr) request.onStderr?.(stderr);
return envelope.result;
} finally {
if (requestTimeoutTimer) clearTimeout(requestTimeoutTimer);
if (forceTerminationTimer) clearTimeout(forceTerminationTimer);
request.signal?.removeEventListener("abort", onAbort);
}
Expand Down
57 changes: 39 additions & 18 deletions src/launcher.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { spawn as spawnChild, type ChildProcess } from "node:child_process";
import { randomUUID } from "node:crypto";
import {
appendFileSync,
chmodSync,
Expand Down Expand Up @@ -30,6 +31,7 @@ import {
} from "./zai-oauth.ts";
import { requestAppServer } from "./app-server-client.ts";
import { runPluginCommand } from "./plugin-cli.ts";
import { pluginProtocolMethods } from "./plugin-protocol.ts";
import { runTuiWithHerdrStatus } from "./herdr-status.mjs";
import { missingCodingPlanKey } from "./prompt-preflight.ts";
import { extractPromptOverrides } from "./prompt-model.ts";
Expand All @@ -50,6 +52,18 @@ const defaultBrowserUseArgument = "--browser-use=headless";
const tuiRuntimeLogLimitBytes = 2 * 1024 * 1024;
const versionArguments = new Set(["version", "--version", "-v"]);
const runtimeVariadicOptions = new Set(["--disallowedTools", "--disallowed-tools"]);
const cancellablePluginMethods = new Set<string>([
pluginProtocolMethods.marketplaceAdd, pluginProtocolMethods.marketplaceUpdate, pluginProtocolMethods.install
]);

function pluginRequestTimeoutMs(): number {
const value = process.env.ZCODE_PLUGIN_REQUEST_TIMEOUT_MS?.trim();
const timeout = value ? Number(value) : 60_000;
if (!Number.isInteger(timeout) || timeout <= 0 || timeout > 2_147_483_647) {
throw new Error("ZCODE_PLUGIN_REQUEST_TIMEOUT_MS must be an integer between 1 and 2147483647.");
}
return timeout;
}


export function resolveModelRetryMaxRetries(env: NodeJS.ProcessEnv): string {
Expand Down Expand Up @@ -539,25 +553,32 @@ export async function main(args: string[]): Promise<number> {
let pluginCommand: number | undefined;
try {
pluginCommand = await runPluginCommand(args, {
request: async ({ method, params, signal, workingDirectory }) => await requestAppServer({
method,
params,
onStderr: stderr => {
for (const line of stderr.split(/\r?\n/u)) {
if (!line.startsWith("ZCode Built-in: ignoring unavailable ZCODE_BUILTIN_PROVIDER_CONFIG_FILE ")
|| builtinProviderWarnings.has(line)) continue;
builtinProviderWarnings.add(line);
process.stderr.write(`${line}\n`);
request: async ({ method, params, signal, workingDirectory }) => {
const operationId = cancellablePluginMethods.has(method) ? randomUUID() : undefined;
return await requestAppServer({
method,
params: operationId ? { ...params, operationId } : params,
...(operationId ? { cancellation: {
method: "plugins/cancelOperation", params: { operationId }
} } : {}),
timeoutMs: pluginRequestTimeoutMs(),
onStderr: stderr => {
for (const line of stderr.split(/\r?\n/u)) {
if (!line.startsWith("ZCode Built-in: ignoring unavailable ZCODE_BUILTIN_PROVIDER_CONFIG_FILE ")
|| builtinProviderWarnings.has(line)) continue;
builtinProviderWarnings.add(line);
process.stderr.write(`${line}\n`);
}
},
signal: signal ?? pluginAbortController.signal,
transport: {
args: [runtimePath, "app-server"],
command: node,
cwd: workingDirectory,
env: runtimeEnvironment()
}
},
signal: signal ?? pluginAbortController.signal,
transport: {
args: [runtimePath, "app-server"],
command: node,
cwd: workingDirectory,
env: runtimeEnvironment()
}
}),
});
},
signal: pluginAbortController.signal
});
} finally {
Expand Down
1 change: 1 addition & 0 deletions src/plugin-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,7 @@ export async function runPluginCommand(
if (!command.yes && !await confirm(`Add marketplace from ${printable(value)}?`)) {
throw new Error("Marketplace addition cancelled. Use --yes for non-interactive use.");
}
if (!command.json) stdout.write("Adding marketplace...\n");
const result = await call(pluginProtocolMethods.marketplaceAdd, { source: value });
print(result, () => renderMutation(stdout, result, {
failure: "Marketplace addition failed.",
Expand Down
1 change: 1 addition & 0 deletions test/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ Counts describe this reset, not an assertion that future suites must have a fixe
| File | Failure this must prevent |
| --- | --- |
| `launcher.test.ts` | Keyless prompts run, missing sessions leak diagnostics, repeated cancellation leaves the runtime alive, or a local plugin cannot be installed and discovered. |
| `plugin-cancellation.test.ts` | A stalled marketplace add leaves its native storage lock after cancellation or timeout, blocking the next command. |
| `app-server-auth.test.ts` | Real protocol turns use the wrong credential owner, fail to rotate keys, or fall back from missing credentials to host authentication. |
| `settings-file.test.ts` | Runtime writes and trust changes escape a host-selected settings store or change native MCP precedence. |
| `config-migration.test.ts` | Migration loses providers, overwrites conflicting/invalid configuration, or runs twice concurrently. |
Expand Down
17 changes: 15 additions & 2 deletions test/app-server-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { describe, expect, test } from "bun:test";
import {
AppServerProcessError,
AppServerRequestError,
AppServerTimeoutError,
requestAppServer
} from "../src/app-server-client.ts";

Expand Down Expand Up @@ -78,12 +79,13 @@ describe("app-server NDJSON client", () => {
})).rejects.toMatchObject({ name: "AbortError" });
});

test("finishes cancellation when the app-server ignores SIGTERM", async () => {
test.each([false, true])("finishes cancellation when the app-server ignores SIGTERM (cooperative: %s)", async cooperative => {
const controller = new AbortController();
const pending = requestAppServer({
method: "plugins/list",
params: {},
signal: controller.signal,
...(cooperative ? { cancellation: { method: "plugins/cancelOperation", params: { operationId: "fixture" } } } : {}),
transport: transport(`
process.on("SIGTERM", () => {});
process.stdin.resume();
Expand All @@ -93,6 +95,17 @@ describe("app-server NDJSON client", () => {
setTimeout(() => controller.abort(), 150);

await expect(pending).rejects.toMatchObject({ name: "AbortError" });
}, 3_000);
}, 6_000);

test.each([false, true])("times out a stalled request instead of waiting for process exit (reply: %s)", async reply => {
await expect(requestAppServer({
method: "plugins/overview", params: {}, timeoutMs: 100,
transport: transport(`
process.stdin.resume();
${reply ? 'process.stdin.once("data", () => console.log(JSON.stringify({ id: 1, result: {} })));' : ""}
setInterval(() => {}, 1000);
`)
})).rejects.toBeInstanceOf(AppServerTimeoutError);
}, 2_000);

});
58 changes: 58 additions & 0 deletions test/runtime/plugin-cancellation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { expect, test } from "bun:test";
import { mkdtemp, readdir, rm, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { runtimeTestEnv } from "../fixtures/runtime-env.ts";

const root = join(import.meta.dir, "../..");

test.skipIf(process.platform === "win32").each(["signal", "timeout"] as const)(
"a stalled marketplace add releases its native lock on %s and allows the next add", async kind => {
const home = await mkdtemp(join(tmpdir(), "zcode-plugin-cancel-"));
let started!: () => void;
const downloading = new Promise<void>(resolve => { started = resolve; });
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) {
if (new URL(request.url).pathname === "/stalled.json") {
started();
return await new Promise<Response>(() => {});
}
return Response.json({ name: "recovered-marketplace", plugins: [] });
} });
const env = { ...runtimeTestEnv(home),
http_proxy: "", https_proxy: "", HTTP_PROXY: "", HTTPS_PROXY: "", all_proxy: "", ALL_PROXY: "",
ZCODE_PLUGIN_REQUEST_TIMEOUT_MS: kind === "timeout" ? "5000" : "15000" };
const launch = (path: string) => Bun.spawn([
Bun.which("node")!, join(root, "bin/zcode.js"), "plugins", "marketplace", "add", `${server.url.origin}/${path}`, "--yes", "--json"
], { cwd: home, env, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
let child = launch("stalled.json");
const deadline = setTimeout(() => child.kill("SIGKILL"), 20_000);
const lock = join(home, ".zcode/cli/plugins/installed_plugins.json.lock");
try {
const output = Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]);
// The request starts after the runtime acquires the real mutation lock.
await Promise.race([downloading, child.exited.then(() => { throw new Error("Add exited before starting the download."); })]);
expect((await readdir(lock)).some(name => name.startsWith("owner-"))).toBe(true);
if (kind === "signal") child.kill("SIGTERM");
const code = await child.exited;
const [stdout, stderr] = await output;
expect(code, `${stdout}\n${stderr}`).toBe(kind === "signal" ? 143 : 1);
expect(stderr).toContain(kind === "signal" ? "App-server request cancelled." : "timed out after 5000ms");
await expect(stat(lock)).rejects.toMatchObject({ code: "ENOENT" });

child = launch("healthy.json");
const [nextCode, nextOut, nextErr] = await Promise.all([
child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()
]);
expect(nextCode, nextErr).toBe(0);
expect(JSON.parse(nextOut)).toMatchObject({ marketplace: { id: "recovered-marketplace" }, diagnostics: [] });
await expect(stat(lock)).rejects.toMatchObject({ code: "ENOENT" });
} finally {
clearTimeout(deadline);
if (child.exitCode === null) child.kill("SIGKILL");
await child.exited;
server.stop(true);
await rm(home, { recursive: true, force: true });
}
}, 25_000
);
Loading