Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(channel): round and clamp timeout_seconds to 1-3600 in createSession
Jack Rudenko9d511f4c9bed
diff --git a/docs/usage/mcp-server.md b/docs/usage/mcp-server.mdindex 9b6464a1..a1099921 100644--- a/docs/usage/mcp-server.md+++ b/docs/usage/mcp-server.md@@ -248,7 +248,7 @@ Spawn an async external model session.**Parameters:**- `model` (required) - Model identifier (e.g., `[email protected]`, `x-ai/grok-code-fast-1`)- `prompt` (optional) - Initial prompt. If omitted, send later via `send_input`.-- `timeout_seconds` (optional) - Session timeout (default: 600, max: 3600)+- `timeout_seconds` (optional) - Session timeout in whole seconds, 1-3600 (default: 600). A fractional value is rounded and an out-of-range one clamped, so `spawn.json` always carries an integer in that range- `claude_flags` (optional) - Extra flags to pass to claudish (space-separated)- `work_dir` (optional) - Working directory for the session (default: current directory)diff --git a/packages/cli/src/channel/session-manager.ts b/packages/cli/src/channel/session-manager.tsindex f7582600..4451e07a 100644--- a/packages/cli/src/channel/session-manager.ts+++ b/packages/cli/src/channel/session-manager.ts@@ -244,6 +244,23 @@ const DRAIN_TIMEOUT_MS = 10_000;const DEFAULT_SCROLLBACK = 2000;const DEFAULT_TIMEOUT = 600;const MAX_TIMEOUT = 3600;++/**+ * The caller's `timeout_seconds` as a whole number of seconds in+ * 1..MAX_TIMEOUT: rounded, then clamped. Anything that is not a finite number+ * (absent, null, NaN, Infinity, garbage from a client that ignored the schema)+ * is DEFAULT_TIMEOUT; a numeric string is read as its number.+ *+ * `spawn.json` is a contract with the magus plugin monitor, which drops any+ * record whose `timeoutSeconds` is not an integer in 1..3600 — so a raw 90.5,+ * 0 or -5 made the whole run invisible, and 0 or less also timed the session+ * out at once.+ */+export function normaliseTimeoutSeconds(raw: unknown): number {+ const n = typeof raw === "string" && raw.trim() !== "" ? Number(raw) : raw;+ if (typeof n !== "number" || !Number.isFinite(n)) return DEFAULT_TIMEOUT;+ return Math.min(MAX_TIMEOUT, Math.max(1, Math.round(n)));+}const KILL_GRACE_MS = 5000;/**@@ -957,7 +974,9 @@ export class SessionManager {// filename under ~/.claude/projects/<slug>/, so knowing it BEFORE spawn// removes the cwd+mtime guessing a post-hoc search would need.const claudeSessionId = randomUUID();- const timeout = Math.min(opts.timeoutSeconds ?? DEFAULT_TIMEOUT, MAX_TIMEOUT);+ // Normalised once, here, so `spawn.json` and the timer agree on one value+ // the plugin monitor accepts (an integer in 1..MAX_TIMEOUT).+ const timeout = normaliseTimeoutSeconds(opts.timeoutSeconds);const startedAt = new Date().toISOString();const sessionDir = opts.sessionDir ?? join(this.sessionsDir, sessionId);diff --git a/packages/cli/src/channel/session-timeout.test.ts b/packages/cli/src/channel/session-timeout.test.tsnew file mode 100644index 00000000..f39bbe8a--- /dev/null+++ b/packages/cli/src/channel/session-timeout.test.ts@@ -0,0 +1,80 @@+/**+ * `timeout_seconds` is normalised ONCE, in `createSession`, before it reaches+ * `spawn.json` or the timer.+ *+ * The tool schema accepted any number, and the writer persisted+ * `Math.min(value, 3600)` unvalidated: 90.5, 0 and -5 went to disk as-is, and a+ * non-numeric value became NaN, which `JSON.stringify` writes as null. The+ * magus plugin monitor requires an integer in 1..3600 and drops any other+ * record, so the whole run went unreported — and 0 or a negative value also+ * timed the session out at once.+ */++import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++import { SessionManager } from "./session-manager.js";++const FAKE_CLAUDISH_TS = join(+ dirname(fileURLToPath(import.meta.url)),+ "test-helpers",+ "fake-channel-stream-json.ts"+);++const originalClaudishBin = process.env.CLAUDISH_BIN;+let sessionsDir: string;+let manager: SessionManager;++beforeAll(() => {+ process.env.CLAUDISH_BIN = FAKE_CLAUDISH_TS;+});++afterAll(() => {+ if (originalClaudishBin === undefined) delete process.env.CLAUDISH_BIN;+ else process.env.CLAUDISH_BIN = originalClaudishBin;+});++beforeEach(() => {+ sessionsDir = mkdtempSync(join(tmpdir(), "claudish-session-timeout-"));+ manager = new SessionManager({ hostPid: 1, sessionsDir, stallSeconds: 0 });+});++afterEach(async () => {+ await manager.shutdownAll();+ rmSync(sessionsDir, { recursive: true, force: true });+});++function spawnRecordTimeout(raw: unknown): unknown {+ const sessionId = manager.createSession({+ model: "fake-model",+ // A promptless session waits for input, so nothing ends it during the test.+ timeoutSeconds: raw as number | undefined,+ });+ const spawn = JSON.parse(readFileSync(join(sessionsDir, sessionId, "spawn.json"), "utf-8"));+ return spawn.timeoutSeconds;+}++describe("createSession timeout normalisation", () => {+ const cases: [unknown, number][] = [+ [90.5, 91],+ [90.4, 90],+ [0, 1],+ [-5, 1],+ [0.2, 1],+ [7200, 3600],+ [Number.NaN, 600],+ [Number.POSITIVE_INFINITY, 600],+ ["600", 600],+ [null, 600],+ [undefined, 600],+ ];++ for (const [raw, expected] of cases) {+ test(`${String(raw)} → ${expected}`, () => {+ expect(spawnRecordTimeout(raw)).toBe(expected);+ });+ }+});diff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.tsindex b09f998c..7cd197f6 100644--- a/packages/cli/src/mcp-server.ts+++ b/packages/cli/src/mcp-server.ts@@ -1743,8 +1743,11 @@ function defineTools(description: "Initial prompt to send. If omitted, send later via send_input.",},timeout_seconds: {- type: "number",- description: "Session timeout in seconds (default: 600, max: 3600)",+ type: "integer",+ minimum: 1,+ maximum: 3600,+ description:+ "Session timeout in whole seconds, 1-3600 (default: 600). Out-of-range values are clamped.",},agent: {type: "string",