Skip to content

Commit c215eaa

Browse files
suharvestclaude
andcommitted
feat(server): classify errors + auto-repair opencode.json on ensureServer
Two server-side robustness features so newcomers hit fewer cryptic failures: 1. errors.mjs — classifyError() annotates fetch/abort/connection errors with actionable fix hints. Wired into request() and sendPrompt() in opencode-server.mjs so "fetch failed" becomes e.g. "Aborted after Ns (OPENCODE_PROMPT_TIMEOUT_MS=...). For longer tasks set ... to a higher value." ECONNREFUSED gets the start-server hint, 401/403 points at OPENCODE_SERVER_PASSWORD, 5xx points at docker logs. 2. opencode-config.mjs — ensureOpencodeConfig() writes the headless-safe permission set (bash/edit/webfetch/external_directory all "allow") to ~/.config/opencode/opencode.json before ensureServer spawns opencode. Idempotent, atomic temp+rename, respects XDG_CONFIG_HOME. Fixes anomalyco/opencode#14473 hang that cost 48 min in one session to diagnose. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 4fb3c30 commit c215eaa

3 files changed

Lines changed: 210 additions & 8 deletions

File tree

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// Error classification helpers — turn raw fetch/abort/HTTP errors into
2+
// actionable messages that point newcomers at the right knob to turn.
3+
//
4+
// Usage:
5+
// try { ... }
6+
// catch (err) { throw classifyError(err, { baseUrl, startedAt, timeoutMs }); }
7+
//
8+
// classifyError always returns an Error (never swallows). When the input
9+
// matches one of the known patterns, the returned Error's message is prefixed
10+
// with a one-line hint; otherwise the original error is returned unchanged.
11+
12+
/**
13+
* Classify an error and return an annotated Error instance.
14+
* @param {any} err
15+
* @param {object} [ctx]
16+
* @param {string} [ctx.baseUrl]
17+
* @param {number} [ctx.startedAt] - epoch ms when the request started
18+
* @param {number} [ctx.timeoutMs] - caller-side abort timeout
19+
* @param {string} [ctx.op] - operation name (e.g. "sendPrompt", "request GET /session")
20+
* @returns {Error}
21+
*/
22+
export function classifyError(err, ctx = {}) {
23+
if (!err) return new Error("unknown error");
24+
const original = err instanceof Error ? err : new Error(String(err));
25+
const msg = original.message || "";
26+
const code = original.code || original.cause?.code || "";
27+
const elapsedSec = ctx.startedAt ? Math.round((Date.now() - ctx.startedAt) / 1000) : null;
28+
29+
// AbortSignal fired from our side (caller-imposed timeout).
30+
if (original.name === "AbortError" || /abort/i.test(msg)) {
31+
if (ctx.timeoutMs && elapsedSec != null && elapsedSec * 1000 >= ctx.timeoutMs * 0.9) {
32+
const envVar = ctx.op === "sendPrompt" ? "OPENCODE_PROMPT_TIMEOUT_MS" : "OPENCODE_REQUEST_TIMEOUT_MS";
33+
return annotate(original,
34+
`Aborted after ${elapsedSec}s (${envVar}=${ctx.timeoutMs}). For longer tasks set ${envVar}=3600000 or higher.`);
35+
}
36+
// ~5min watershed — opencode server closes POST body at that boundary.
37+
if (elapsedSec != null && elapsedSec >= 290 && elapsedSec <= 320) {
38+
return annotate(original,
39+
`OpenCode server closed POST body at ~5min (watcher took over if task still running).`);
40+
}
41+
}
42+
43+
// Connection refused — server not listening.
44+
if (code === "ECONNREFUSED" || /ECONNREFUSED/.test(msg)) {
45+
const url = ctx.baseUrl || "http://127.0.0.1:4096";
46+
return annotate(original,
47+
`OpenCode server at ${url} unreachable. Start it with 'opencode serve --port 4096' or run 'companion doctor'.`);
48+
}
49+
50+
// HTTP status-coded errors (shape: "OpenCode API GET /foo returned 401: ...")
51+
const m = msg.match(/returned (\d{3})\b/);
52+
if (m) {
53+
const status = Number(m[1]);
54+
if (status === 401 || status === 403) {
55+
return annotate(original,
56+
`Auth failed (${status}). Check OPENCODE_SERVER_PASSWORD / OPENCODE_SERVER_USERNAME env.`);
57+
}
58+
if (status >= 500 && status < 600) {
59+
return annotate(original,
60+
`OpenCode server error ${status} (check 'docker logs' or opencode logs):`);
61+
}
62+
}
63+
64+
// fetch failed at exactly ~5min — server-side body close.
65+
if (/fetch failed/i.test(msg) && elapsedSec != null && elapsedSec >= 290 && elapsedSec <= 320) {
66+
return annotate(original,
67+
`OpenCode server closed POST body at ~5min (watcher took over if task still running).`);
68+
}
69+
70+
return original;
71+
}
72+
73+
function annotate(err, hint) {
74+
const wrapped = new Error(`${hint} [${err.message}]`);
75+
wrapped.cause = err;
76+
wrapped.code = err.code;
77+
return wrapped;
78+
}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
// Self-heal for ~/.config/opencode/opencode.json permissions.
2+
//
3+
// Background: opencode's bash tool hangs forever in headless mode when
4+
// permission.external_directory == "ask" (sst/opencode#14473).
5+
// Our companion runs opencode serve in headless mode, so we MUST have:
6+
// permission.bash = "allow"
7+
// permission.edit = "allow"
8+
// permission.webfetch = "allow"
9+
// permission.external_directory = "allow"
10+
//
11+
// ensureOpencodeConfig() merges these in idempotently, preserving any other
12+
// user keys. Called from ensureServer() before spawning opencode serve, and
13+
// from the `doctor` subcommand.
14+
15+
import fs from "node:fs";
16+
import os from "node:os";
17+
import path from "node:path";
18+
19+
import { ensureDir, readJson } from "./fs.mjs";
20+
21+
export const REQUIRED_PERMISSIONS = {
22+
bash: "allow",
23+
edit: "allow",
24+
webfetch: "allow",
25+
external_directory: "allow",
26+
};
27+
28+
/**
29+
* Resolve the opencode config file path, respecting $XDG_CONFIG_HOME.
30+
* @returns {string}
31+
*/
32+
export function resolveConfigPath() {
33+
const xdg = process.env.XDG_CONFIG_HOME;
34+
const base = xdg && xdg.length > 0 ? xdg : path.join(os.homedir(), ".config");
35+
return path.join(base, "opencode", "opencode.json");
36+
}
37+
38+
/**
39+
* Read the opencode config, returning the parsed object or a fresh scaffold.
40+
* @returns {{ path: string, exists: boolean, data: object }}
41+
*/
42+
export function readOpencodeConfig() {
43+
const p = resolveConfigPath();
44+
const exists = fs.existsSync(p);
45+
const data = exists ? (readJson(p) ?? {}) : { $schema: "https://opencode.ai/config.json" };
46+
return { path: p, exists, data };
47+
}
48+
49+
/**
50+
* Returns the set of permission keys that are NOT already "allow".
51+
* @param {object} data
52+
* @returns {string[]}
53+
*/
54+
export function missingPermissions(data) {
55+
const perm = (data && data.permission) || {};
56+
const missing = [];
57+
for (const [k, v] of Object.entries(REQUIRED_PERMISSIONS)) {
58+
if (perm[k] !== v) missing.push(k);
59+
}
60+
return missing;
61+
}
62+
63+
/**
64+
* Ensure opencode.json has all required permissions set to "allow".
65+
* Idempotent: if everything is already correct, does not touch the file.
66+
*
67+
* @param {object} [opts]
68+
* @param {boolean} [opts.dryRun] - if true, do not write; just report what would change
69+
* @param {boolean} [opts.silent] - if true, suppress stderr notice on change
70+
* @returns {{ path: string, changed: boolean, missing: string[], dryRun: boolean }}
71+
*/
72+
export function ensureOpencodeConfig(opts = {}) {
73+
const dryRun = !!opts.dryRun;
74+
const { path: p, exists, data } = readOpencodeConfig();
75+
const missing = missingPermissions(data);
76+
77+
if (missing.length === 0 && exists) {
78+
return { path: p, changed: false, missing: [], dryRun };
79+
}
80+
81+
if (dryRun) {
82+
return { path: p, changed: false, missing, dryRun };
83+
}
84+
85+
// Merge permissions, preserving other keys.
86+
const merged = { ...data };
87+
if (!merged.$schema) merged.$schema = "https://opencode.ai/config.json";
88+
merged.permission = { ...(merged.permission || {}), ...REQUIRED_PERMISSIONS };
89+
90+
ensureDir(path.dirname(p));
91+
const tmp = `${p}.tmp.${process.pid}`;
92+
fs.writeFileSync(tmp, JSON.stringify(merged, null, 2) + "\n", "utf8");
93+
fs.renameSync(tmp, p);
94+
95+
if (!opts.silent) {
96+
process.stderr.write(`[opencode-companion] Ensured opencode.json permissions (headless-safe)\n`);
97+
}
98+
return { path: p, changed: true, missing, dryRun };
99+
}

‎plugins/opencode/scripts/lib/opencode-server.mjs‎

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import { spawn, spawnSync } from "node:child_process";
88
// in auto-heal.mjs because it is tightly coupled to heal-decision logic, but
99
// conceptually it is a server probe.
1010
export { probeSessionTerminal } from "./auto-heal.mjs";
11+
import { ensureOpencodeConfig } from "./opencode-config.mjs";
12+
import { classifyError } from "./errors.mjs";
1113

1214
const DEFAULT_PORT = 4096;
1315
const DEFAULT_HOST = "127.0.0.1";
@@ -114,6 +116,14 @@ export async function ensureServer(opts = {}) {
114116
return { url, alreadyRunning: true };
115117
}
116118

119+
// Self-heal permissions BEFORE spawning the server. The running daemon reads
120+
// opencode.json at startup; fixing it after the spawn would require a restart.
121+
try {
122+
ensureOpencodeConfig();
123+
} catch (err) {
124+
process.stderr.write(`[opencode-companion] ensureOpencodeConfig failed: ${err.message}\n`);
125+
}
126+
117127
// Start the server
118128
const proc = spawn("opencode", ["serve", "--port", String(port)], {
119129
stdio: ["ignore", "pipe", "pipe"],
@@ -155,15 +165,24 @@ export function createClient(baseUrl, opts = {}) {
155165
}
156166

157167
async function request(method, path, body) {
158-
const res = await fetch(`${baseUrl}${path}`, {
159-
method,
160-
headers,
161-
body: body != null ? JSON.stringify(body) : undefined,
162-
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
163-
});
168+
const startedAt = Date.now();
169+
let res;
170+
try {
171+
res = await fetch(`${baseUrl}${path}`, {
172+
method,
173+
headers,
174+
body: body != null ? JSON.stringify(body) : undefined,
175+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
176+
});
177+
} catch (err) {
178+
throw classifyError(err, { baseUrl, startedAt, timeoutMs: REQUEST_TIMEOUT_MS, op: `request ${method} ${path}` });
179+
}
164180
if (!res.ok) {
165181
const text = await res.text().catch(() => "");
166-
throw new Error(`OpenCode API ${method} ${path} returned ${res.status}: ${text}`);
182+
throw classifyError(
183+
new Error(`OpenCode API ${method} ${path} returned ${res.status}: ${text}`),
184+
{ baseUrl, startedAt, timeoutMs: REQUEST_TIMEOUT_MS, op: `request ${method} ${path}` },
185+
);
167186
}
168187
const ct = res.headers.get("content-type") ?? "";
169188
if (ct.includes("application/json")) {
@@ -394,7 +413,13 @@ export function createClient(baseUrl, opts = {}) {
394413
if (second.ok) return second.data;
395414
// Both failed — surface the more informative error. Prefer the
396415
// fetch error because it usually has the HTTP status/body.
397-
throw first.via === "fetch" ? first.err : second.err;
416+
const rawErr = first.via === "fetch" ? first.err : second.err;
417+
throw classifyError(rawErr, {
418+
baseUrl,
419+
startedAt,
420+
timeoutMs: PROMPT_TIMEOUT_MS,
421+
op: "sendPrompt",
422+
});
398423
} finally {
399424
clearTimeout(timeoutId);
400425
}

0 commit comments

Comments
 (0)