wide-cli 0.5.1611261726 → 0.6.191126
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/osv-bundle.json +1 -1
- package/data/rules.json +1 -1
- package/dist/agent/index.d.ts +25 -3
- package/dist/agent/index.d.ts.map +1 -1
- package/dist/agent/index.js +117 -18
- package/dist/agent/index.js.map +1 -1
- package/dist/completion.js +5 -5
- package/dist/completion.js.map +1 -1
- package/dist/config/index.d.ts +4 -1
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/index.js +9 -2
- package/dist/config/index.js.map +1 -1
- package/dist/fix.d.ts +25 -0
- package/dist/fix.d.ts.map +1 -0
- package/dist/fix.js +197 -0
- package/dist/fix.js.map +1 -0
- package/dist/hook.d.ts +31 -0
- package/dist/hook.d.ts.map +1 -0
- package/dist/hook.js +152 -0
- package/dist/hook.js.map +1 -0
- package/dist/index.js +168 -5
- package/dist/index.js.map +1 -1
- package/dist/providers/antigravity.d.ts +46 -0
- package/dist/providers/antigravity.d.ts.map +1 -0
- package/dist/providers/antigravity.js +496 -0
- package/dist/providers/antigravity.js.map +1 -0
- package/dist/providers/claude-code.d.ts +60 -0
- package/dist/providers/claude-code.d.ts.map +1 -0
- package/dist/providers/claude-code.js +973 -0
- package/dist/providers/claude-code.js.map +1 -0
- package/dist/providers/codex.d.ts +52 -0
- package/dist/providers/codex.d.ts.map +1 -0
- package/dist/providers/codex.js +742 -0
- package/dist/providers/codex.js.map +1 -0
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js +33 -1
- package/dist/providers/index.js.map +1 -1
- package/dist/repl/commands.d.ts.map +1 -1
- package/dist/repl/commands.js +53 -3
- package/dist/repl/commands.js.map +1 -1
- package/dist/repl/index.d.ts +3 -0
- package/dist/repl/index.d.ts.map +1 -1
- package/dist/repl/index.js +11 -6
- package/dist/repl/index.js.map +1 -1
- package/dist/repl/setup.d.ts.map +1 -1
- package/dist/repl/setup.js +16 -4
- package/dist/repl/setup.js.map +1 -1
- package/dist/security/crawler.d.ts +90 -0
- package/dist/security/crawler.d.ts.map +1 -0
- package/dist/security/crawler.js +622 -0
- package/dist/security/crawler.js.map +1 -0
- package/dist/security/fuzzer.d.ts +1 -0
- package/dist/security/fuzzer.d.ts.map +1 -1
- package/dist/security/fuzzer.js +25 -1
- package/dist/security/fuzzer.js.map +1 -1
- package/dist/security/inspect/evasion-decode.d.ts +41 -0
- package/dist/security/inspect/evasion-decode.d.ts.map +1 -0
- package/dist/security/inspect/evasion-decode.js +316 -0
- package/dist/security/inspect/evasion-decode.js.map +1 -0
- package/dist/security/inspect/http-conformance.d.ts +51 -0
- package/dist/security/inspect/http-conformance.d.ts.map +1 -0
- package/dist/security/inspect/http-conformance.js +389 -0
- package/dist/security/inspect/http-conformance.js.map +1 -0
- package/dist/security/inspect/lexical-sqli.d.ts +7 -0
- package/dist/security/inspect/lexical-sqli.d.ts.map +1 -0
- package/dist/security/inspect/lexical-sqli.js +986 -0
- package/dist/security/inspect/lexical-sqli.js.map +1 -0
- package/dist/security/inspect/lexical-xss.d.ts +10 -0
- package/dist/security/inspect/lexical-xss.d.ts.map +1 -0
- package/dist/security/inspect/lexical-xss.js +654 -0
- package/dist/security/inspect/lexical-xss.js.map +1 -0
- package/dist/security/inspect/libinjection-tables.d.ts +6 -0
- package/dist/security/inspect/libinjection-tables.d.ts.map +1 -0
- package/dist/security/inspect/libinjection-tables.js +6 -0
- package/dist/security/inspect/libinjection-tables.js.map +1 -0
- package/dist/security/inspect/safe-pattern.d.ts +62 -0
- package/dist/security/inspect/safe-pattern.d.ts.map +1 -0
- package/dist/security/inspect/safe-pattern.js +640 -0
- package/dist/security/inspect/safe-pattern.js.map +1 -0
- package/dist/security/inspect/score-policy.d.ts +82 -0
- package/dist/security/inspect/score-policy.d.ts.map +1 -0
- package/dist/security/inspect/score-policy.js +241 -0
- package/dist/security/inspect/score-policy.js.map +1 -0
- package/dist/security/inspect.d.ts +7 -0
- package/dist/security/inspect.d.ts.map +1 -0
- package/dist/security/inspect.js +7 -0
- package/dist/security/inspect.js.map +1 -0
- package/dist/security/loader.d.ts.map +1 -1
- package/dist/security/loader.js +12 -2
- package/dist/security/loader.js.map +1 -1
- package/dist/security/payloads.d.ts.map +1 -1
- package/dist/security/payloads.js +19 -0
- package/dist/security/payloads.js.map +1 -1
- package/dist/security/scanner.d.ts +2 -0
- package/dist/security/scanner.d.ts.map +1 -1
- package/dist/security/scanner.js +31 -26
- package/dist/security/scanner.js.map +1 -1
- package/dist/tools/article.d.ts +18 -0
- package/dist/tools/article.d.ts.map +1 -0
- package/dist/tools/article.js +193 -0
- package/dist/tools/article.js.map +1 -0
- package/dist/tools/browser.d.ts +8 -2
- package/dist/tools/browser.d.ts.map +1 -1
- package/dist/tools/browser.js +76 -10
- package/dist/tools/browser.js.map +1 -1
- package/dist/tools/docx.d.ts +11 -0
- package/dist/tools/docx.d.ts.map +1 -0
- package/dist/tools/docx.js +149 -0
- package/dist/tools/docx.js.map +1 -0
- package/dist/tools/fs.d.ts +2 -0
- package/dist/tools/fs.d.ts.map +1 -1
- package/dist/tools/fs.js +96 -7
- package/dist/tools/fs.js.map +1 -1
- package/dist/tools/http.d.ts.map +1 -1
- package/dist/tools/http.js +125 -48
- package/dist/tools/http.js.map +1 -1
- package/dist/tools/index.d.ts +21 -2
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +137 -14
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/resilience.d.ts +78 -0
- package/dist/tools/resilience.d.ts.map +1 -0
- package/dist/tools/resilience.js +211 -0
- package/dist/tools/resilience.js.map +1 -0
- package/dist/tools/security.d.ts +2 -0
- package/dist/tools/security.d.ts.map +1 -1
- package/dist/tools/security.js +79 -1
- package/dist/tools/security.js.map +1 -1
- package/dist/tools/types.d.ts +4 -0
- package/dist/tools/types.d.ts.map +1 -1
- package/dist/ui/banner.d.ts.map +1 -1
- package/dist/ui/banner.js +2 -2
- package/dist/ui/banner.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,973 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
import { homedir, tmpdir } from "node:os";
|
|
6
|
+
import { dirname, join, resolve } from "node:path";
|
|
7
|
+
import { configManager } from "../config/index.js";
|
|
8
|
+
import { executeTool } from "../tools/index.js";
|
|
9
|
+
export const CLI_NATIVE_OVERLAP_TOOLS = new Set([
|
|
10
|
+
"read_file",
|
|
11
|
+
"write_file",
|
|
12
|
+
"edit_file",
|
|
13
|
+
"delete_file",
|
|
14
|
+
"create_dir",
|
|
15
|
+
"list_dir",
|
|
16
|
+
"search_files",
|
|
17
|
+
"run_command",
|
|
18
|
+
]);
|
|
19
|
+
export function filterCliToolsForClaudeMcp(tools) {
|
|
20
|
+
return tools.filter((t) => !CLI_NATIVE_OVERLAP_TOOLS.has(t.name));
|
|
21
|
+
}
|
|
22
|
+
export function parseClaudeAuthJson(stdout) {
|
|
23
|
+
const trimmed = String(stdout ?? "").trim();
|
|
24
|
+
if (!trimmed)
|
|
25
|
+
return null;
|
|
26
|
+
let parsed = null;
|
|
27
|
+
try {
|
|
28
|
+
parsed = JSON.parse(trimmed);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
const start = trimmed.indexOf("{");
|
|
32
|
+
const end = trimmed.lastIndexOf("}");
|
|
33
|
+
if (start >= 0 && end > start) {
|
|
34
|
+
try {
|
|
35
|
+
parsed = JSON.parse(trimmed.slice(start, end + 1));
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
46
|
+
return null;
|
|
47
|
+
const rec = parsed;
|
|
48
|
+
const loggedIn = typeof rec.loggedIn === "boolean"
|
|
49
|
+
? rec.loggedIn
|
|
50
|
+
: typeof rec.logged_in === "boolean"
|
|
51
|
+
? rec.logged_in
|
|
52
|
+
: false;
|
|
53
|
+
return {
|
|
54
|
+
loggedIn,
|
|
55
|
+
authMethod: String(rec.authMethod ?? rec.auth_method ?? "").trim(),
|
|
56
|
+
apiProvider: String(rec.apiProvider ?? rec.api_provider ?? "").trim(),
|
|
57
|
+
email: String(rec.email ?? "").trim(),
|
|
58
|
+
subscriptionType: String(rec.subscriptionType ?? rec.subscription_type ?? "").trim(),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function sanitizedClaudeEnv() {
|
|
62
|
+
const env = { ...process.env };
|
|
63
|
+
delete env.CLAUDECODE;
|
|
64
|
+
delete env.CLAUDE_CODE_ENTRYPOINT;
|
|
65
|
+
delete env.CLAUDE_CODE_SSE_PORT;
|
|
66
|
+
return env;
|
|
67
|
+
}
|
|
68
|
+
async function whereExecutable(cmd) {
|
|
69
|
+
const tool = process.platform === "win32" ? "where.exe" : "which";
|
|
70
|
+
return await new Promise((resolvePath) => {
|
|
71
|
+
let done = false;
|
|
72
|
+
const finish = (val) => {
|
|
73
|
+
if (done)
|
|
74
|
+
return;
|
|
75
|
+
done = true;
|
|
76
|
+
resolvePath(val);
|
|
77
|
+
};
|
|
78
|
+
try {
|
|
79
|
+
const child = spawn(tool, [cmd], {
|
|
80
|
+
windowsHide: true,
|
|
81
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
82
|
+
});
|
|
83
|
+
const timer = setTimeout(() => {
|
|
84
|
+
try {
|
|
85
|
+
child.kill("SIGKILL");
|
|
86
|
+
}
|
|
87
|
+
catch { }
|
|
88
|
+
finish("");
|
|
89
|
+
}, 3000);
|
|
90
|
+
let stdout = "";
|
|
91
|
+
child.stdout.on("data", (c) => {
|
|
92
|
+
stdout += c.toString("utf8");
|
|
93
|
+
});
|
|
94
|
+
child.on("error", () => {
|
|
95
|
+
clearTimeout(timer);
|
|
96
|
+
finish("");
|
|
97
|
+
});
|
|
98
|
+
child.on("close", (code) => {
|
|
99
|
+
clearTimeout(timer);
|
|
100
|
+
if (code !== 0) {
|
|
101
|
+
finish("");
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const lines = stdout
|
|
105
|
+
.split(/\r?\n/)
|
|
106
|
+
.map((l) => l.trim())
|
|
107
|
+
.filter(Boolean);
|
|
108
|
+
if (process.platform === "win32") {
|
|
109
|
+
finish(lines.find((l) => /\.(cmd|exe)$/i.test(l)) ||
|
|
110
|
+
lines.find((l) => /\.(js|mjs|cjs)$/i.test(l)) ||
|
|
111
|
+
lines[0] ||
|
|
112
|
+
"");
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
finish(lines[0] || "");
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
finish("");
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
export async function claudeCodeBinaryPath() {
|
|
125
|
+
const override = String(process.env.WIDE_CLAUDE_PATH || "").trim();
|
|
126
|
+
if (override && existsSync(override))
|
|
127
|
+
return override;
|
|
128
|
+
const home = homedir();
|
|
129
|
+
const candidates = process.platform === "win32"
|
|
130
|
+
? [
|
|
131
|
+
process.env.APPDATA ? join(process.env.APPDATA, "npm", "claude.cmd") : "",
|
|
132
|
+
process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, "Programs", "claude", "claude.exe") : "",
|
|
133
|
+
join(home, ".claude", "local", "claude.exe"),
|
|
134
|
+
join(home, ".local", "bin", "claude.exe"),
|
|
135
|
+
]
|
|
136
|
+
: [
|
|
137
|
+
join(home, ".claude", "local", "claude"),
|
|
138
|
+
join(home, ".local", "bin", "claude"),
|
|
139
|
+
"/opt/homebrew/bin/claude",
|
|
140
|
+
"/usr/local/bin/claude",
|
|
141
|
+
"/usr/bin/claude",
|
|
142
|
+
];
|
|
143
|
+
for (const candidate of candidates) {
|
|
144
|
+
if (candidate && existsSync(candidate))
|
|
145
|
+
return candidate;
|
|
146
|
+
}
|
|
147
|
+
const found = await whereExecutable(process.platform === "win32" ? "claude.cmd" : "claude");
|
|
148
|
+
if (found && existsSync(found))
|
|
149
|
+
return found;
|
|
150
|
+
if (process.platform === "win32") {
|
|
151
|
+
const exe = await whereExecutable("claude.exe");
|
|
152
|
+
if (exe && existsSync(exe))
|
|
153
|
+
return exe;
|
|
154
|
+
}
|
|
155
|
+
return "";
|
|
156
|
+
}
|
|
157
|
+
function resolveCmdShimScript(binPath) {
|
|
158
|
+
if (process.platform !== "win32" || !/\.(cmd|bat)$/i.test(binPath))
|
|
159
|
+
return "";
|
|
160
|
+
try {
|
|
161
|
+
const content = readFileSync(binPath, "utf8");
|
|
162
|
+
const match = /"%~dp0\\([^"\r\n]+\.(?:js|mjs|cjs))"/i.exec(content);
|
|
163
|
+
if (!match)
|
|
164
|
+
return "";
|
|
165
|
+
const resolved = resolve(dirname(binPath), match[1]);
|
|
166
|
+
if (existsSync(resolved))
|
|
167
|
+
return resolved;
|
|
168
|
+
}
|
|
169
|
+
catch { }
|
|
170
|
+
return "";
|
|
171
|
+
}
|
|
172
|
+
function buildSpawnSpec(binPath, args) {
|
|
173
|
+
if (/\.(js|mjs|cjs)$/i.test(binPath)) {
|
|
174
|
+
return { command: process.execPath, args: [binPath, ...args], shell: false };
|
|
175
|
+
}
|
|
176
|
+
if (process.platform === "win32" && /\.(cmd|bat)$/i.test(binPath)) {
|
|
177
|
+
const script = resolveCmdShimScript(binPath);
|
|
178
|
+
if (script) {
|
|
179
|
+
return { command: process.execPath, args: [script, ...args], shell: false };
|
|
180
|
+
}
|
|
181
|
+
return { command: binPath, args, shell: true };
|
|
182
|
+
}
|
|
183
|
+
return { command: binPath, args, shell: false };
|
|
184
|
+
}
|
|
185
|
+
export async function checkClaudeCodeAuth(binPath) {
|
|
186
|
+
const exe = binPath || (await claudeCodeBinaryPath());
|
|
187
|
+
if (!exe)
|
|
188
|
+
return null;
|
|
189
|
+
const spec = buildSpawnSpec(exe, ["auth", "status", "--json"]);
|
|
190
|
+
return await new Promise((resolveAuth) => {
|
|
191
|
+
let settled = false;
|
|
192
|
+
let stdout = "";
|
|
193
|
+
const finish = (val) => {
|
|
194
|
+
if (settled)
|
|
195
|
+
return;
|
|
196
|
+
settled = true;
|
|
197
|
+
resolveAuth(val);
|
|
198
|
+
};
|
|
199
|
+
try {
|
|
200
|
+
const child = spawn(spec.command, spec.args, {
|
|
201
|
+
env: sanitizedClaudeEnv(),
|
|
202
|
+
windowsHide: true,
|
|
203
|
+
shell: spec.shell,
|
|
204
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
205
|
+
});
|
|
206
|
+
const timer = setTimeout(() => {
|
|
207
|
+
try {
|
|
208
|
+
child.kill("SIGKILL");
|
|
209
|
+
}
|
|
210
|
+
catch { }
|
|
211
|
+
finish(null);
|
|
212
|
+
}, 6000);
|
|
213
|
+
child.stdout.on("data", (chunk) => {
|
|
214
|
+
stdout += chunk.toString("utf8");
|
|
215
|
+
});
|
|
216
|
+
child.on("error", () => {
|
|
217
|
+
clearTimeout(timer);
|
|
218
|
+
finish(null);
|
|
219
|
+
});
|
|
220
|
+
child.on("close", () => {
|
|
221
|
+
clearTimeout(timer);
|
|
222
|
+
finish(parseClaudeAuthJson(stdout));
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
finish(null);
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
function buildStdioMcpScriptSource(port, token) {
|
|
231
|
+
return [
|
|
232
|
+
"'use strict';",
|
|
233
|
+
"const http = require('node:http');",
|
|
234
|
+
"const readline = require('node:readline');",
|
|
235
|
+
`const PORT = ${JSON.stringify(port)};`,
|
|
236
|
+
`const TOKEN = ${JSON.stringify(token)};`,
|
|
237
|
+
"function req(method, path, body) {",
|
|
238
|
+
" return new Promise((resolve, reject) => {",
|
|
239
|
+
" const data = body === undefined ? null : JSON.stringify(body);",
|
|
240
|
+
" const r = http.request({ host: '127.0.0.1', port: PORT, path, method, headers: {",
|
|
241
|
+
" authorization: 'Bearer ' + TOKEN,",
|
|
242
|
+
" ...(data ? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(data) } : {}),",
|
|
243
|
+
" }}, (res) => {",
|
|
244
|
+
" let raw = '';",
|
|
245
|
+
" res.on('data', (c) => { raw += c.toString('utf8'); });",
|
|
246
|
+
" res.on('end', () => {",
|
|
247
|
+
" try { resolve(JSON.parse(raw || '{}')); } catch { resolve({}); }",
|
|
248
|
+
" });",
|
|
249
|
+
" });",
|
|
250
|
+
" r.on('error', reject);",
|
|
251
|
+
" if (data) r.write(data);",
|
|
252
|
+
" r.end();",
|
|
253
|
+
" });",
|
|
254
|
+
"}",
|
|
255
|
+
"function reply(id, result) {",
|
|
256
|
+
" if (id === undefined || id === null) return;",
|
|
257
|
+
" process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result }) + '\\n');",
|
|
258
|
+
"}",
|
|
259
|
+
"function replyErr(id, code, message) {",
|
|
260
|
+
" if (id === undefined || id === null) return;",
|
|
261
|
+
" process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } }) + '\\n');",
|
|
262
|
+
"}",
|
|
263
|
+
"const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });",
|
|
264
|
+
"rl.on('line', async (line) => {",
|
|
265
|
+
" const trimmed = line.trim();",
|
|
266
|
+
" if (!trimmed) return;",
|
|
267
|
+
" let msg;",
|
|
268
|
+
" try { msg = JSON.parse(trimmed); } catch { return; }",
|
|
269
|
+
" const { id, method, params } = msg;",
|
|
270
|
+
" if (method === 'initialize') {",
|
|
271
|
+
" reply(id, { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'wide', version: '1.0.0' } });",
|
|
272
|
+
" return;",
|
|
273
|
+
" }",
|
|
274
|
+
" if (method === 'notifications/initialized') return;",
|
|
275
|
+
" if (method === 'tools/list') {",
|
|
276
|
+
" try {",
|
|
277
|
+
" const data = await req('GET', '/tools');",
|
|
278
|
+
" reply(id, { tools: Array.isArray(data.tools) ? data.tools : [] });",
|
|
279
|
+
" } catch (e) {",
|
|
280
|
+
" replyErr(id, -32603, String(e && e.message || e));",
|
|
281
|
+
" }",
|
|
282
|
+
" return;",
|
|
283
|
+
" }",
|
|
284
|
+
" if (method === 'tools/call') {",
|
|
285
|
+
" try {",
|
|
286
|
+
" const name = String(params && params.name || '');",
|
|
287
|
+
" const args = (params && params.arguments) || {};",
|
|
288
|
+
" const data = await req('POST', '/tool', { name, arguments: args });",
|
|
289
|
+
" reply(id, { content: [{ type: 'text', text: String(data.result ?? '') }], isError: Boolean(data.isError) });",
|
|
290
|
+
" } catch (e) {",
|
|
291
|
+
" reply(id, { content: [{ type: 'text', text: String(e && e.message || e) }], isError: true });",
|
|
292
|
+
" }",
|
|
293
|
+
" return;",
|
|
294
|
+
" }",
|
|
295
|
+
" replyErr(id, -32601, 'Method not found');",
|
|
296
|
+
"});",
|
|
297
|
+
].join("\n");
|
|
298
|
+
}
|
|
299
|
+
export async function startCliToolBridge(getTools) {
|
|
300
|
+
const token = randomBytes(18).toString("hex");
|
|
301
|
+
const server = createServer((req, res) => {
|
|
302
|
+
if (String(req.headers.authorization || "") !== `Bearer ${token}`) {
|
|
303
|
+
res.writeHead(401, { "content-type": "application/json" });
|
|
304
|
+
res.end(JSON.stringify({ error: "unauthorized" }));
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
const reqPath = String(req.url || "/").split("?")[0];
|
|
308
|
+
if (req.method === "GET" && reqPath === "/tools") {
|
|
309
|
+
const specs = filterCliToolsForClaudeMcp(getTools()).map((t) => ({
|
|
310
|
+
name: t.name,
|
|
311
|
+
description: t.description,
|
|
312
|
+
inputSchema: t.parameters || { type: "object", properties: {} },
|
|
313
|
+
}));
|
|
314
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
315
|
+
res.end(JSON.stringify({ tools: specs }));
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
if (req.method === "DELETE" && reqPath === "/mcp") {
|
|
319
|
+
res.writeHead(204);
|
|
320
|
+
res.end();
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
if (req.method === "POST" && reqPath === "/mcp") {
|
|
324
|
+
let body = "";
|
|
325
|
+
req.on("data", (chunk) => {
|
|
326
|
+
body += chunk.toString("utf8");
|
|
327
|
+
});
|
|
328
|
+
req.on("end", async () => {
|
|
329
|
+
let parsed;
|
|
330
|
+
try {
|
|
331
|
+
parsed = JSON.parse(body || "{}");
|
|
332
|
+
}
|
|
333
|
+
catch {
|
|
334
|
+
res.writeHead(400, { "content-type": "application/json" });
|
|
335
|
+
res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }));
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
const id = parsed.id;
|
|
339
|
+
const method = String(parsed.method || "");
|
|
340
|
+
const params = (parsed.params && typeof parsed.params === "object" ? parsed.params : {});
|
|
341
|
+
if (id === undefined || id === null || method.startsWith("notifications/")) {
|
|
342
|
+
res.writeHead(202);
|
|
343
|
+
res.end();
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
if (method === "initialize") {
|
|
347
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
348
|
+
res.end(JSON.stringify({
|
|
349
|
+
jsonrpc: "2.0",
|
|
350
|
+
id,
|
|
351
|
+
result: {
|
|
352
|
+
protocolVersion: String(params.protocolVersion || "2025-03-26"),
|
|
353
|
+
capabilities: { tools: {} },
|
|
354
|
+
serverInfo: { name: "wide", version: "2.0.0" },
|
|
355
|
+
},
|
|
356
|
+
}));
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
if (method === "ping") {
|
|
360
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
361
|
+
res.end(JSON.stringify({ jsonrpc: "2.0", id, result: {} }));
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
if (method === "tools/list") {
|
|
365
|
+
const specs = filterCliToolsForClaudeMcp(getTools()).map((t) => ({
|
|
366
|
+
name: t.name,
|
|
367
|
+
description: t.description || "",
|
|
368
|
+
inputSchema: t.parameters || { type: "object", properties: {} },
|
|
369
|
+
}));
|
|
370
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
371
|
+
res.end(JSON.stringify({ jsonrpc: "2.0", id, result: { tools: specs } }));
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
if (method === "tools/call") {
|
|
375
|
+
const name = String(params.name || "").trim();
|
|
376
|
+
const args = params.arguments && typeof params.arguments === "object" ? params.arguments : {};
|
|
377
|
+
const allowed = filterCliToolsForClaudeMcp(getTools());
|
|
378
|
+
if (!allowed.some((t) => t.name === name)) {
|
|
379
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
380
|
+
res.end(JSON.stringify({
|
|
381
|
+
jsonrpc: "2.0",
|
|
382
|
+
id,
|
|
383
|
+
result: {
|
|
384
|
+
content: [{ type: "text", text: `Tool "${name}" is disabled or handled natively.` }],
|
|
385
|
+
isError: true,
|
|
386
|
+
},
|
|
387
|
+
}));
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
try {
|
|
391
|
+
const cfg = configManager.get();
|
|
392
|
+
const out = await executeTool(name, args, {
|
|
393
|
+
workingDirectory: process.cwd(),
|
|
394
|
+
toolMode: cfg.toolMode || "full",
|
|
395
|
+
allowBrowser: cfg.allowBrowser !== false,
|
|
396
|
+
strictValidation: true,
|
|
397
|
+
autoApproveRead: cfg.autoApproveRead,
|
|
398
|
+
autoApproveWrite: cfg.autoApproveWrite,
|
|
399
|
+
autoApproveRun: cfg.autoApproveRun,
|
|
400
|
+
});
|
|
401
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
402
|
+
res.end(JSON.stringify({
|
|
403
|
+
jsonrpc: "2.0",
|
|
404
|
+
id,
|
|
405
|
+
result: {
|
|
406
|
+
content: [{ type: "text", text: String(out.output || out.error || "") }],
|
|
407
|
+
isError: !out.success,
|
|
408
|
+
},
|
|
409
|
+
}));
|
|
410
|
+
}
|
|
411
|
+
catch (err) {
|
|
412
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
413
|
+
res.end(JSON.stringify({
|
|
414
|
+
jsonrpc: "2.0",
|
|
415
|
+
id,
|
|
416
|
+
result: {
|
|
417
|
+
content: [{ type: "text", text: String(err?.message || err) }],
|
|
418
|
+
isError: true,
|
|
419
|
+
},
|
|
420
|
+
}));
|
|
421
|
+
}
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
425
|
+
res.end(JSON.stringify({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } }));
|
|
426
|
+
});
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
if (req.method === "POST" && reqPath === "/tool") {
|
|
430
|
+
let body = "";
|
|
431
|
+
req.on("data", (chunk) => {
|
|
432
|
+
body += chunk.toString("utf8");
|
|
433
|
+
});
|
|
434
|
+
req.on("end", async () => {
|
|
435
|
+
try {
|
|
436
|
+
const parsed = JSON.parse(body || "{}");
|
|
437
|
+
const name = String(parsed.name || "").trim();
|
|
438
|
+
const args = parsed.arguments && typeof parsed.arguments === "object" ? parsed.arguments : {};
|
|
439
|
+
const allowed = filterCliToolsForClaudeMcp(getTools());
|
|
440
|
+
if (!allowed.some((t) => t.name === name)) {
|
|
441
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
442
|
+
res.end(JSON.stringify({ result: `Tool "${name}" is disabled or handled natively by Claude Code.`, isError: true }));
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
const cfg = configManager.get();
|
|
446
|
+
const out = await executeTool(name, args, {
|
|
447
|
+
workingDirectory: process.cwd(),
|
|
448
|
+
toolMode: cfg.toolMode || "full",
|
|
449
|
+
allowBrowser: cfg.allowBrowser !== false,
|
|
450
|
+
strictValidation: true,
|
|
451
|
+
autoApproveRead: cfg.autoApproveRead,
|
|
452
|
+
autoApproveWrite: cfg.autoApproveWrite,
|
|
453
|
+
autoApproveRun: cfg.autoApproveRun,
|
|
454
|
+
});
|
|
455
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
456
|
+
res.end(JSON.stringify({ result: out.output, isError: !out.success }));
|
|
457
|
+
}
|
|
458
|
+
catch (err) {
|
|
459
|
+
res.writeHead(500, { "content-type": "application/json" });
|
|
460
|
+
res.end(JSON.stringify({ result: String(err?.message || err), isError: true }));
|
|
461
|
+
}
|
|
462
|
+
});
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
res.writeHead(404);
|
|
466
|
+
res.end();
|
|
467
|
+
});
|
|
468
|
+
return await new Promise((resolveBridge, rejectBridge) => {
|
|
469
|
+
server.once("error", rejectBridge);
|
|
470
|
+
server.listen(0, "127.0.0.1", () => {
|
|
471
|
+
server.removeListener("error", rejectBridge);
|
|
472
|
+
const addr = server.address();
|
|
473
|
+
const port = typeof addr === "object" && addr ? addr.port : 0;
|
|
474
|
+
resolveBridge({
|
|
475
|
+
port,
|
|
476
|
+
token,
|
|
477
|
+
mcpUrl: `http://127.0.0.1:${port}/mcp`,
|
|
478
|
+
close: () => {
|
|
479
|
+
try {
|
|
480
|
+
server.close();
|
|
481
|
+
}
|
|
482
|
+
catch { }
|
|
483
|
+
},
|
|
484
|
+
});
|
|
485
|
+
});
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
export class ClaudeStreamAccumulator {
|
|
489
|
+
streamedText = "";
|
|
490
|
+
rootTextTotal = "";
|
|
491
|
+
sessionId = "";
|
|
492
|
+
isError = false;
|
|
493
|
+
resultText = "";
|
|
494
|
+
resetTurn() {
|
|
495
|
+
this.streamedText = "";
|
|
496
|
+
this.rootTextTotal = "";
|
|
497
|
+
this.isError = false;
|
|
498
|
+
this.resultText = "";
|
|
499
|
+
}
|
|
500
|
+
getFullText() {
|
|
501
|
+
return this.rootTextTotal || this.resultText;
|
|
502
|
+
}
|
|
503
|
+
feedLine(line, onChunk) {
|
|
504
|
+
const trimmed = line.trim();
|
|
505
|
+
if (!trimmed)
|
|
506
|
+
return { done: false, sessionNotFound: false };
|
|
507
|
+
let obj;
|
|
508
|
+
try {
|
|
509
|
+
obj = JSON.parse(trimmed);
|
|
510
|
+
}
|
|
511
|
+
catch {
|
|
512
|
+
return { done: false, sessionNotFound: false };
|
|
513
|
+
}
|
|
514
|
+
if (!obj || typeof obj !== "object")
|
|
515
|
+
return { done: false, sessionNotFound: false };
|
|
516
|
+
if (typeof obj.session_id === "string" && obj.session_id.trim()) {
|
|
517
|
+
this.sessionId = obj.session_id.trim();
|
|
518
|
+
}
|
|
519
|
+
if (obj.type === "stream_event" && obj.event && !obj.parent_tool_use_id) {
|
|
520
|
+
const ev = obj.event;
|
|
521
|
+
if (ev.type === "message_start") {
|
|
522
|
+
this.streamedText = "";
|
|
523
|
+
}
|
|
524
|
+
else if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && typeof ev.delta.text === "string") {
|
|
525
|
+
this.streamedText += ev.delta.text;
|
|
526
|
+
this.rootTextTotal += ev.delta.text;
|
|
527
|
+
onChunk(ev.delta.text);
|
|
528
|
+
}
|
|
529
|
+
return { done: false, sessionNotFound: false };
|
|
530
|
+
}
|
|
531
|
+
if (obj.type === "assistant" && Array.isArray(obj.message?.content) && !obj.parent_tool_use_id) {
|
|
532
|
+
let full = "";
|
|
533
|
+
for (const b of obj.message.content) {
|
|
534
|
+
if (b && b.type === "text" && typeof b.text === "string") {
|
|
535
|
+
full += b.text;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
if (full) {
|
|
539
|
+
if (!this.streamedText) {
|
|
540
|
+
this.rootTextTotal += full;
|
|
541
|
+
onChunk(full);
|
|
542
|
+
}
|
|
543
|
+
else if (full.length > this.streamedText.length && full.startsWith(this.streamedText)) {
|
|
544
|
+
const suffix = full.slice(this.streamedText.length);
|
|
545
|
+
if (suffix) {
|
|
546
|
+
this.rootTextTotal += suffix;
|
|
547
|
+
onChunk(suffix);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
this.streamedText = "";
|
|
552
|
+
return { done: false, sessionNotFound: false };
|
|
553
|
+
}
|
|
554
|
+
if (obj.type === "result") {
|
|
555
|
+
this.isError = Boolean(obj.is_error || String(obj.subtype || "").startsWith("error"));
|
|
556
|
+
const rawErrors = Array.isArray(obj.errors) ? obj.errors.join("\n") : "";
|
|
557
|
+
this.resultText = typeof obj.result === "string" && obj.result ? obj.result : rawErrors;
|
|
558
|
+
if (!this.isError && !this.rootTextTotal && this.resultText) {
|
|
559
|
+
this.rootTextTotal = this.resultText;
|
|
560
|
+
onChunk(this.resultText);
|
|
561
|
+
}
|
|
562
|
+
const lower = this.resultText.toLowerCase();
|
|
563
|
+
const sessionNotFound = this.isError &&
|
|
564
|
+
(lower.includes("no conversation found") ||
|
|
565
|
+
lower.includes("could not resume") ||
|
|
566
|
+
(lower.includes("session") && lower.includes("not found")));
|
|
567
|
+
return { done: true, sessionNotFound };
|
|
568
|
+
}
|
|
569
|
+
return { done: false, sessionNotFound: false };
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
export class ClaudeCodeProvider {
|
|
573
|
+
name = "claude-code";
|
|
574
|
+
model;
|
|
575
|
+
proc = null;
|
|
576
|
+
bridge = null;
|
|
577
|
+
tempFiles = [];
|
|
578
|
+
activeTools = [];
|
|
579
|
+
claudeSessionId = "";
|
|
580
|
+
syncedMessageCount = 0;
|
|
581
|
+
workerSignature = "";
|
|
582
|
+
authVerified = false;
|
|
583
|
+
activeTurnFinish = null;
|
|
584
|
+
activeAccumulator = new ClaudeStreamAccumulator();
|
|
585
|
+
activeChunkCb = () => { };
|
|
586
|
+
activeStderr = [];
|
|
587
|
+
stdoutBuf = "";
|
|
588
|
+
constructor(model = "default") {
|
|
589
|
+
this.model = model || "default";
|
|
590
|
+
}
|
|
591
|
+
dispose() {
|
|
592
|
+
if (this.proc) {
|
|
593
|
+
try {
|
|
594
|
+
this.proc.stdin.end();
|
|
595
|
+
}
|
|
596
|
+
catch { }
|
|
597
|
+
try {
|
|
598
|
+
this.proc.kill("SIGKILL");
|
|
599
|
+
}
|
|
600
|
+
catch { }
|
|
601
|
+
this.proc = null;
|
|
602
|
+
}
|
|
603
|
+
if (this.bridge) {
|
|
604
|
+
this.bridge.close();
|
|
605
|
+
this.bridge = null;
|
|
606
|
+
}
|
|
607
|
+
for (const file of this.tempFiles) {
|
|
608
|
+
try {
|
|
609
|
+
unlinkSync(file);
|
|
610
|
+
}
|
|
611
|
+
catch { }
|
|
612
|
+
}
|
|
613
|
+
this.tempFiles = [];
|
|
614
|
+
}
|
|
615
|
+
normalizeModelArg() {
|
|
616
|
+
const clean = this.model.trim();
|
|
617
|
+
if (!clean || clean.toLowerCase() === "default")
|
|
618
|
+
return "";
|
|
619
|
+
return clean;
|
|
620
|
+
}
|
|
621
|
+
formatPriorHistory(messages, lastUserIdx) {
|
|
622
|
+
const lines = [];
|
|
623
|
+
for (const msg of messages.slice(0, lastUserIdx)) {
|
|
624
|
+
if (msg.role === "system" || !msg.content.trim())
|
|
625
|
+
continue;
|
|
626
|
+
lines.push(`${msg.role === "assistant" ? "Assistant" : "User"}: ${msg.content.trim().slice(0, 2000)}`);
|
|
627
|
+
}
|
|
628
|
+
if (lines.length === 0)
|
|
629
|
+
return "";
|
|
630
|
+
return `[Previous conversation context]\n${lines.join("\n\n")}\n[End of previous context]\n\n`;
|
|
631
|
+
}
|
|
632
|
+
async chatStream(messages, tools, onChunk, signal) {
|
|
633
|
+
const binPath = await claudeCodeBinaryPath();
|
|
634
|
+
if (!binPath) {
|
|
635
|
+
throw new Error("Claude Code CLI is not installed. Run 'npm install -g @anthropic-ai/claude-code' and 'claude auth login'.");
|
|
636
|
+
}
|
|
637
|
+
if (!this.authVerified && !process.env.WIDE_CLAUDE_SKIP_AUTH_CHECK) {
|
|
638
|
+
const auth = await checkClaudeCodeAuth(binPath);
|
|
639
|
+
if (auth && !auth.loggedIn && !process.env.ANTHROPIC_API_KEY) {
|
|
640
|
+
throw new Error("Claude Code is not signed in. Run 'claude auth login' in your terminal first.");
|
|
641
|
+
}
|
|
642
|
+
this.authVerified = true;
|
|
643
|
+
}
|
|
644
|
+
const systemMsg = messages.find((m) => m.role === "system")?.content || "";
|
|
645
|
+
let lastUserIdx = -1;
|
|
646
|
+
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
|
647
|
+
if (messages[i].role === "user") {
|
|
648
|
+
lastUserIdx = i;
|
|
649
|
+
break;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
const lastUserText = lastUserIdx >= 0 ? messages[lastUserIdx].content : messages.map((m) => m.content).join("\n");
|
|
653
|
+
const oneShotCompletion = tools.length === 0;
|
|
654
|
+
if (oneShotCompletion) {
|
|
655
|
+
return await this.runOneShot(binPath, systemMsg, lastUserText, onChunk, signal);
|
|
656
|
+
}
|
|
657
|
+
const allowDiskWrites = tools.some((t) => t.name === "write_file" || t.name === "edit_file");
|
|
658
|
+
const mcpTools = filterCliToolsForClaudeMcp(tools);
|
|
659
|
+
const sig = JSON.stringify([this.normalizeModelArg(), allowDiskWrites, mcpTools.map((t) => t.name)]);
|
|
660
|
+
if (messages.length <= this.syncedMessageCount && this.syncedMessageCount > 0) {
|
|
661
|
+
this.dispose();
|
|
662
|
+
this.claudeSessionId = "";
|
|
663
|
+
this.syncedMessageCount = 0;
|
|
664
|
+
}
|
|
665
|
+
if (!this.proc || !this.proc.stdin.writable || this.workerSignature !== sig) { // wide-ignore wide/timing-secret-nonconst-eq
|
|
666
|
+
this.dispose();
|
|
667
|
+
this.activeTools = tools;
|
|
668
|
+
const useResume = Boolean(this.claudeSessionId && this.syncedMessageCount > 0);
|
|
669
|
+
await this.spawnPersistentWorker(binPath, sig, systemMsg, allowDiskWrites, mcpTools, useResume);
|
|
670
|
+
const firstPrompt = useResume ? lastUserText : `${this.formatPriorHistory(messages, lastUserIdx)}${lastUserText}`;
|
|
671
|
+
const res = await this.sendTurn(firstPrompt, onChunk, signal);
|
|
672
|
+
if (res.retryFresh) {
|
|
673
|
+
this.dispose();
|
|
674
|
+
this.claudeSessionId = "";
|
|
675
|
+
this.syncedMessageCount = 0;
|
|
676
|
+
await this.spawnPersistentWorker(binPath, sig, systemMsg, allowDiskWrites, mcpTools, false);
|
|
677
|
+
const retryPrompt = `${this.formatPriorHistory(messages, lastUserIdx)}${lastUserText}`;
|
|
678
|
+
const retryRes = await this.sendTurn(retryPrompt, onChunk, signal);
|
|
679
|
+
if (retryRes.error)
|
|
680
|
+
throw new Error(retryRes.error);
|
|
681
|
+
this.syncedMessageCount = messages.length;
|
|
682
|
+
return { content: retryRes.content };
|
|
683
|
+
}
|
|
684
|
+
if (res.error)
|
|
685
|
+
throw new Error(res.error);
|
|
686
|
+
this.syncedMessageCount = messages.length;
|
|
687
|
+
return { content: res.content };
|
|
688
|
+
}
|
|
689
|
+
this.activeTools = tools;
|
|
690
|
+
const res = await this.sendTurn(lastUserText, onChunk, signal);
|
|
691
|
+
if (res.error)
|
|
692
|
+
throw new Error(res.error);
|
|
693
|
+
this.syncedMessageCount = messages.length;
|
|
694
|
+
return { content: res.content };
|
|
695
|
+
}
|
|
696
|
+
async spawnPersistentWorker(binPath, signature, systemPrompt, allowDiskWrites, mcpTools, resume) {
|
|
697
|
+
this.workerSignature = signature;
|
|
698
|
+
if (!resume || !this.claudeSessionId) {
|
|
699
|
+
this.claudeSessionId = randomUUID();
|
|
700
|
+
}
|
|
701
|
+
const dir = join(tmpdir(), "wide-cli-cc");
|
|
702
|
+
mkdirSync(dir, { recursive: true });
|
|
703
|
+
const stamp = `${Date.now()}-${randomBytes(4).toString("hex")}`;
|
|
704
|
+
let mcpConfigPath = "";
|
|
705
|
+
if (mcpTools.length > 0) {
|
|
706
|
+
this.bridge = await startCliToolBridge(() => this.activeTools);
|
|
707
|
+
const mcpScriptPath = join(dir, `mcp-${stamp}.cjs`);
|
|
708
|
+
writeFileSync(mcpScriptPath, buildStdioMcpScriptSource(this.bridge.port, this.bridge.token), "utf8");
|
|
709
|
+
this.tempFiles.push(mcpScriptPath);
|
|
710
|
+
mcpConfigPath = join(dir, `mcp-${stamp}.json`);
|
|
711
|
+
writeFileSync(mcpConfigPath, JSON.stringify({
|
|
712
|
+
mcpServers: {
|
|
713
|
+
wide: {
|
|
714
|
+
command: process.execPath,
|
|
715
|
+
args: [mcpScriptPath],
|
|
716
|
+
},
|
|
717
|
+
},
|
|
718
|
+
}), "utf8");
|
|
719
|
+
this.tempFiles.push(mcpConfigPath);
|
|
720
|
+
}
|
|
721
|
+
let promptFilePath = "";
|
|
722
|
+
const mcpHint = mcpTools.length > 0
|
|
723
|
+
? `Additional Wide CLI / Security / Browser / DB tools are attached on MCP server "wide": ${mcpTools.map((t) => t.name).join(", ")}.`
|
|
724
|
+
: "";
|
|
725
|
+
const fullSystem = [systemPrompt.trim(), mcpHint].filter(Boolean).join("\n\n");
|
|
726
|
+
if (fullSystem) {
|
|
727
|
+
promptFilePath = join(dir, `sys-${stamp}.txt`);
|
|
728
|
+
writeFileSync(promptFilePath, fullSystem, "utf8");
|
|
729
|
+
this.tempFiles.push(promptFilePath);
|
|
730
|
+
}
|
|
731
|
+
const cliArgs = [
|
|
732
|
+
"--print",
|
|
733
|
+
"--input-format",
|
|
734
|
+
"stream-json",
|
|
735
|
+
"--output-format",
|
|
736
|
+
"stream-json",
|
|
737
|
+
"--verbose",
|
|
738
|
+
"--include-partial-messages",
|
|
739
|
+
];
|
|
740
|
+
if (resume) {
|
|
741
|
+
cliArgs.push("--resume", this.claudeSessionId);
|
|
742
|
+
}
|
|
743
|
+
else {
|
|
744
|
+
cliArgs.push("--session-id", this.claudeSessionId);
|
|
745
|
+
}
|
|
746
|
+
if (promptFilePath) {
|
|
747
|
+
cliArgs.push("--append-system-prompt-file", promptFilePath);
|
|
748
|
+
}
|
|
749
|
+
if (mcpConfigPath) {
|
|
750
|
+
cliArgs.push("--mcp-config", mcpConfigPath);
|
|
751
|
+
}
|
|
752
|
+
const modelArg = this.normalizeModelArg();
|
|
753
|
+
if (modelArg) {
|
|
754
|
+
cliArgs.push("--model", modelArg);
|
|
755
|
+
}
|
|
756
|
+
if (allowDiskWrites) {
|
|
757
|
+
cliArgs.push("--permission-mode", "bypassPermissions");
|
|
758
|
+
}
|
|
759
|
+
else {
|
|
760
|
+
cliArgs.push("--permission-mode", "bypassPermissions", "--disallowedTools", "Edit", "Write", "MultiEdit", "NotebookEdit");
|
|
761
|
+
}
|
|
762
|
+
const spec = buildSpawnSpec(binPath, cliArgs);
|
|
763
|
+
this.proc = spawn(spec.command, spec.args, {
|
|
764
|
+
cwd: process.cwd(),
|
|
765
|
+
env: sanitizedClaudeEnv(),
|
|
766
|
+
windowsHide: true,
|
|
767
|
+
shell: spec.shell,
|
|
768
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
769
|
+
});
|
|
770
|
+
this.stdoutBuf = "";
|
|
771
|
+
this.proc.stdout.on("data", (chunk) => {
|
|
772
|
+
this.stdoutBuf += chunk.toString("utf8");
|
|
773
|
+
const lines = this.stdoutBuf.split(/\r?\n/);
|
|
774
|
+
this.stdoutBuf = lines.pop() ?? "";
|
|
775
|
+
for (const line of lines) {
|
|
776
|
+
if (!this.activeTurnFinish)
|
|
777
|
+
continue;
|
|
778
|
+
const { done, sessionNotFound } = this.activeAccumulator.feedLine(line, this.activeChunkCb);
|
|
779
|
+
if (this.activeAccumulator.sessionId) {
|
|
780
|
+
this.claudeSessionId = this.activeAccumulator.sessionId;
|
|
781
|
+
}
|
|
782
|
+
if (done) {
|
|
783
|
+
const finish = this.activeTurnFinish;
|
|
784
|
+
this.activeTurnFinish = null;
|
|
785
|
+
if (sessionNotFound) {
|
|
786
|
+
finish({ content: "", retryFresh: true, error: this.activeAccumulator.resultText });
|
|
787
|
+
}
|
|
788
|
+
else if (this.activeAccumulator.isError) {
|
|
789
|
+
finish({ content: "", error: this.activeAccumulator.resultText || "Claude Code execution failed." });
|
|
790
|
+
}
|
|
791
|
+
else {
|
|
792
|
+
finish({ content: this.activeAccumulator.getFullText() });
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
});
|
|
797
|
+
this.proc.stderr.on("data", (chunk) => {
|
|
798
|
+
this.activeStderr.push(chunk.toString("utf8"));
|
|
799
|
+
});
|
|
800
|
+
this.proc.on("close", (code) => {
|
|
801
|
+
if (this.stdoutBuf.trim() && this.activeTurnFinish) {
|
|
802
|
+
this.activeAccumulator.feedLine(this.stdoutBuf, this.activeChunkCb);
|
|
803
|
+
this.stdoutBuf = "";
|
|
804
|
+
}
|
|
805
|
+
if (this.activeTurnFinish) {
|
|
806
|
+
const finish = this.activeTurnFinish;
|
|
807
|
+
this.activeTurnFinish = null;
|
|
808
|
+
const errText = this.activeStderr.join("").trim() || `Claude Code exited unexpectedly (code ${code ?? "unknown"}).`;
|
|
809
|
+
const lower = errText.toLowerCase();
|
|
810
|
+
finish({
|
|
811
|
+
content: "",
|
|
812
|
+
retryFresh: lower.includes("no conversation found") || (lower.includes("session") && lower.includes("not found")),
|
|
813
|
+
error: errText,
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
this.proc = null;
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
sendTurn(promptText, onChunk, signal) {
|
|
820
|
+
return new Promise((resolveTurn) => {
|
|
821
|
+
if (!this.proc || !this.proc.stdin.writable) {
|
|
822
|
+
resolveTurn({ content: "", error: "Claude Code worker process is not running." });
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
this.activeAccumulator.resetTurn();
|
|
826
|
+
this.activeChunkCb = onChunk;
|
|
827
|
+
this.activeStderr = [];
|
|
828
|
+
const cleanup = () => {
|
|
829
|
+
if (signal)
|
|
830
|
+
signal.removeEventListener("abort", onAbort);
|
|
831
|
+
};
|
|
832
|
+
const onAbort = () => {
|
|
833
|
+
if (this.activeTurnFinish) {
|
|
834
|
+
const finish = this.activeTurnFinish;
|
|
835
|
+
this.activeTurnFinish = null;
|
|
836
|
+
cleanup();
|
|
837
|
+
this.dispose();
|
|
838
|
+
finish({ content: "", error: "Aborted" });
|
|
839
|
+
}
|
|
840
|
+
};
|
|
841
|
+
if (signal) {
|
|
842
|
+
if (signal.aborted) {
|
|
843
|
+
onAbort();
|
|
844
|
+
return;
|
|
845
|
+
}
|
|
846
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
847
|
+
}
|
|
848
|
+
this.activeTurnFinish = (res) => {
|
|
849
|
+
cleanup();
|
|
850
|
+
resolveTurn(res);
|
|
851
|
+
};
|
|
852
|
+
const line = JSON.stringify({
|
|
853
|
+
type: "user",
|
|
854
|
+
message: { role: "user", content: promptText },
|
|
855
|
+
});
|
|
856
|
+
try {
|
|
857
|
+
this.proc.stdin.write(`${line}\n`);
|
|
858
|
+
}
|
|
859
|
+
catch (err) {
|
|
860
|
+
if (this.activeTurnFinish) {
|
|
861
|
+
const finish = this.activeTurnFinish;
|
|
862
|
+
this.activeTurnFinish = null;
|
|
863
|
+
cleanup();
|
|
864
|
+
finish({ content: "", error: String(err?.message || err) });
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
async runOneShot(binPath, systemPrompt, userPrompt, onChunk, signal) {
|
|
870
|
+
const cliArgs = [
|
|
871
|
+
"--print",
|
|
872
|
+
"--output-format",
|
|
873
|
+
"stream-json",
|
|
874
|
+
"--verbose",
|
|
875
|
+
"--include-partial-messages",
|
|
876
|
+
"--tools",
|
|
877
|
+
"",
|
|
878
|
+
"--no-session-persistence",
|
|
879
|
+
];
|
|
880
|
+
const modelArg = this.normalizeModelArg();
|
|
881
|
+
if (modelArg) {
|
|
882
|
+
cliArgs.push("--model", modelArg);
|
|
883
|
+
}
|
|
884
|
+
let promptFile = "";
|
|
885
|
+
if (systemPrompt.trim()) {
|
|
886
|
+
const dir = join(tmpdir(), "wide-cli-cc");
|
|
887
|
+
mkdirSync(dir, { recursive: true });
|
|
888
|
+
promptFile = join(dir, `oneshot-${Date.now()}-${randomBytes(4).toString("hex")}.txt`);
|
|
889
|
+
writeFileSync(promptFile, systemPrompt.trim(), "utf8");
|
|
890
|
+
cliArgs.push("--append-system-prompt-file", promptFile);
|
|
891
|
+
}
|
|
892
|
+
const spec = buildSpawnSpec(binPath, cliArgs);
|
|
893
|
+
return await new Promise((resolveShot, rejectShot) => {
|
|
894
|
+
const acc = new ClaudeStreamAccumulator();
|
|
895
|
+
let buf = "";
|
|
896
|
+
let stderr = "";
|
|
897
|
+
let settled = false;
|
|
898
|
+
const finish = (err) => {
|
|
899
|
+
if (settled)
|
|
900
|
+
return;
|
|
901
|
+
settled = true;
|
|
902
|
+
if (promptFile) {
|
|
903
|
+
try {
|
|
904
|
+
unlinkSync(promptFile);
|
|
905
|
+
}
|
|
906
|
+
catch { }
|
|
907
|
+
}
|
|
908
|
+
if (err)
|
|
909
|
+
rejectShot(err);
|
|
910
|
+
else
|
|
911
|
+
resolveShot({ content: acc.getFullText() });
|
|
912
|
+
};
|
|
913
|
+
const child = spawn(spec.command, spec.args, {
|
|
914
|
+
cwd: process.cwd(),
|
|
915
|
+
env: sanitizedClaudeEnv(),
|
|
916
|
+
windowsHide: true,
|
|
917
|
+
shell: spec.shell,
|
|
918
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
919
|
+
});
|
|
920
|
+
const onAbort = () => {
|
|
921
|
+
try {
|
|
922
|
+
child.kill("SIGKILL");
|
|
923
|
+
}
|
|
924
|
+
catch { }
|
|
925
|
+
finish(Object.assign(new Error("Aborted"), { name: "AbortError" }));
|
|
926
|
+
};
|
|
927
|
+
if (signal) {
|
|
928
|
+
if (signal.aborted) {
|
|
929
|
+
onAbort();
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
933
|
+
}
|
|
934
|
+
child.stdout.on("data", (chunk) => {
|
|
935
|
+
buf += chunk.toString("utf8");
|
|
936
|
+
const lines = buf.split(/\r?\n/);
|
|
937
|
+
buf = lines.pop() ?? "";
|
|
938
|
+
for (const line of lines) {
|
|
939
|
+
acc.feedLine(line, onChunk);
|
|
940
|
+
}
|
|
941
|
+
});
|
|
942
|
+
child.stderr.on("data", (chunk) => {
|
|
943
|
+
stderr += chunk.toString("utf8");
|
|
944
|
+
});
|
|
945
|
+
child.on("error", (err) => {
|
|
946
|
+
if (signal)
|
|
947
|
+
signal.removeEventListener("abort", onAbort);
|
|
948
|
+
finish(err);
|
|
949
|
+
});
|
|
950
|
+
child.on("close", (code) => {
|
|
951
|
+
if (signal)
|
|
952
|
+
signal.removeEventListener("abort", onAbort);
|
|
953
|
+
if (buf.trim())
|
|
954
|
+
acc.feedLine(buf, onChunk);
|
|
955
|
+
if (acc.isError) {
|
|
956
|
+
finish(new Error(acc.resultText || stderr.trim() || "Claude Code execution failed."));
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
959
|
+
if (code !== 0 && !acc.getFullText()) {
|
|
960
|
+
finish(new Error(stderr.trim() || `Claude Code exited with code ${code}`));
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
finish();
|
|
964
|
+
});
|
|
965
|
+
try {
|
|
966
|
+
child.stdin.write(userPrompt);
|
|
967
|
+
child.stdin.end();
|
|
968
|
+
}
|
|
969
|
+
catch { }
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
//# sourceMappingURL=claude-code.js.map
|