forked from nexu-io/html-anything
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathargv.ts
More file actions
421 lines (402 loc) · 16.3 KB
/
argv.ts
File metadata and controls
421 lines (402 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
export type AgentArgvOpts = {
model?: string;
cwd?: string;
/** When the adapter takes the prompt as a positional argv (deepseek). */
prompt?: string;
/**
* For openclaw only — pre-resolved agent id (e.g. "main" or "ops") that
* gets injected into the argv as `--agent <id>`. invoke.ts is responsible
* for resolving this via `resolveOpenclawAgentId` before calling buildArgv.
*/
openclawAgentId?: string;
};
export class UnsupportedAgentProtocolError extends Error {
constructor(public readonly agent: string, public readonly protocol: string) {
super(
`${agent} uses the ${protocol} protocol, which is not yet wired up in this build. ` +
`Pick one of: claude / codex / cursor-agent / gemini / copilot / opencode / qwen / qoder / deepseek / aider.`,
);
}
}
export function buildArgv(agent: string, _opts: AgentArgvOpts = {}): string[] {
const { model } = _opts;
switch (agent) {
case "claude":
return [
"-p",
"--output-format",
"stream-json",
"--verbose",
"--include-partial-messages",
"--permission-mode",
"bypassPermissions",
...(model ? ["--model", model] : []),
];
case "openclaw":
// OpenClaw is a multi-channel agent gateway — invocation is
// openclaw agent --local --json --agent <id> [--model <id>]
// and the prompt is appended later via `--message <text>` by invoke.ts
// (see protocol === "argv-message"). The agent id is resolved at
// invocation time by `resolveOpenclawAgentId`.
return [
"agent",
"--local",
"--json",
"--agent",
_opts.openclawAgentId ?? "main",
...(model ? ["--model", model] : []),
];
case "codex":
return [
"exec",
"--json",
"--skip-git-repo-check",
"--sandbox",
"workspace-write",
"-c",
"sandbox_workspace_write.network_access=true",
...(model ? ["--model", model] : []),
];
case "cursor-agent":
return [
"--print",
"--output-format",
"stream-json",
"--stream-partial-output",
"--force",
"--trust",
...(model ? ["--model", model] : []),
];
case "gemini":
return [
"--output-format",
"stream-json",
"--yolo",
...(model ? ["--model", model] : []),
];
case "copilot":
return [
"--allow-all-tools",
"--output-format",
"json",
...(model ? ["--model", model] : []),
];
case "opencode":
return [
"run",
"--format",
"json",
"--dangerously-skip-permissions",
...(model ? ["--model", model] : []),
"-",
];
case "qwen":
return ["--yolo", ...(model ? ["--model", model] : []), "-"];
case "aider":
return [
"--no-pretty",
"--no-stream",
"--yes-always",
"--message-file",
"-",
...(model ? ["--model", model] : []),
];
case "qoder":
// Qoder CLI mirrors `claude -p`'s shape: print mode + stream-json + yolo
// for non-interactive approval. Prompt arrives via stdin (handled in
// invoke.ts). See open-design's apps/daemon/src/agents.ts.
return [
"-p",
"--output-format",
"stream-json",
"--yolo",
...(model ? ["--model", model] : []),
];
case "deepseek":
// DeepSeek's `exec --auto` requires the prompt as a positional arg;
// there's no `-` stdin sentinel. invoke.ts appends opts.prompt at
// spawn time, so we leave the trailing slot empty here.
return ["exec", "--auto", ...(model ? ["--model", model] : [])];
case "hermes":
case "kimi":
case "devin":
case "kiro":
case "kilo":
case "vibe":
throw new UnsupportedAgentProtocolError(agent, "ACP JSON-RPC");
case "pi":
throw new UnsupportedAgentProtocolError(agent, "pi-rpc");
default:
throw new Error(`unknown agent: ${agent}`);
}
}
export function envFor(agent: string): NodeJS.ProcessEnv {
const base = { ...process.env };
if (agent === "gemini") base.GEMINI_CLI_TRUST_WORKSPACE = "true";
return base;
}
export type AgentParse =
| { kind: "delta"; text: string }
| { kind: "meta"; key: string; value: unknown }
/**
* Canonical HTML rescued from a file-write tool call (e.g. Claude's `Write`
* tool). Replaces any previously streamed text — the preamble like
* "I'll save it as output.html\n已输出至 …" is junk; the tool's input is the
* real HTML. Downstream calls `setHtmlFor`, not `appendHtmlFor`.
*/
| { kind: "html"; text: string }
| { kind: "noise" };
/**
* Cross-line state that the parser carries between calls. Currently used to
* dedupe text deltas: when an agent emits both fine-grained `stream_event`
* `text_delta` blocks AND a final `assistant` message containing the same
* text concatenated, we keep the streamed tokens and skip the assistant
* message body. Without this dedupe, every Claude/Cursor/Gemini/Qoder run
* with `--include-partial-messages` (or the equivalent) writes its output
* twice.
*/
export type ParseState = { sawStreamEventText?: boolean };
/**
* Build a stateful per-invocation parser. Feed every stdout line through the
* returned function — it carries the cross-line state needed for dedupe.
*/
export function makeParser(agent: string): (line: string) => AgentParse[] {
const state: ParseState = {};
return (line: string) => parseLineWithState(agent, line, state);
}
/**
* Parse a single line of agent stdout. Stateless wrapper kept for callers
* that only need one-shot parsing (e.g. `extractTextFromLine`). Streaming
* callers should use `makeParser` so dedupe state survives across lines.
*/
export function parseLine(agent: string, line: string): AgentParse[] {
return parseLineWithState(agent, line, {});
}
/**
* Some agents (Claude + bypassPermissions, qoder, …) ignore the "stream HTML
* inline" prompt and decide to dump the document into a file via the `Write`
* tool, leaving the assistant text as just a confirmation ("已输出至 …").
* Rescue the HTML from the tool_use input so the preview still gets the real
* content. Returns an empty string if no Write/create_file tool_use was found
* or its input has no usable content field.
*/
function rescueHtmlFromToolUse(
content: Array<{ type?: string; name?: string; input?: unknown }> | undefined,
): string {
if (!Array.isArray(content)) return "";
const parts: string[] = [];
for (const block of content) {
if (!block || block.type !== "tool_use") continue;
const name = (block.name ?? "").toLowerCase();
// Match the common file-write tool names across agents.
if (
name !== "write" &&
name !== "create_file" &&
name !== "createfile" &&
name !== "writefile" &&
name !== "write_file" &&
name !== "filewrite"
)
continue;
const input = block.input as Record<string, unknown> | undefined;
if (!input || typeof input !== "object") continue;
const path = String(input.file_path ?? input.path ?? input.filename ?? "").toLowerCase();
// Only rescue HTML-ish targets — never grab content for a .md / .txt
// sidecar the agent might also be writing.
if (path && !/\.(html?|htm)$/.test(path)) continue;
const text =
typeof input.content === "string"
? input.content
: typeof input.text === "string"
? input.text
: typeof input.file_content === "string"
? input.file_content
: "";
if (text) parts.push(text);
}
return parts.join("");
}
function parseLineWithState(agent: string, line: string, state: ParseState): AgentParse[] {
const trimmed = line.trim();
if (!trimmed) return [];
// Aider / DeepSeek — plain text streaming on stdout (DeepSeek tool calls
// go to stderr, which is forwarded as `stderr` events, not parsed here).
if (agent === "aider" || agent === "deepseek") {
return [{ kind: "delta", text: trimmed.endsWith("\n") ? trimmed : trimmed + "\n" }];
}
let parsed: unknown;
try {
parsed = JSON.parse(trimmed);
} catch {
return [{ kind: "noise" }];
}
if (!parsed || typeof parsed !== "object") return [];
const obj = parsed as Record<string, unknown>;
const out: AgentParse[] = [];
if (agent === "claude") {
// Init / system metadata
if (obj.type === "system" && obj.subtype === "init") {
out.push({ kind: "meta", key: "model", value: obj.model });
out.push({ kind: "meta", key: "session", value: obj.session_id });
if (obj.cwd) out.push({ kind: "meta", key: "cwd", value: obj.cwd });
}
// Stream events (--include-partial-messages → fine-grained text_delta)
if (obj.type === "stream_event" && obj.event && typeof obj.event === "object") {
const ev = obj.event as { type?: string; delta?: { type?: string; text?: string; thinking?: string } };
if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && typeof ev.delta.text === "string") {
state.sawStreamEventText = true;
out.push({ kind: "delta", text: ev.delta.text });
} else if (ev.type === "content_block_delta" && ev.delta?.type === "thinking_delta") {
out.push({ kind: "meta", key: "thinking", value: ev.delta.thinking });
}
}
// Full assistant messages — fallback only when stream_event text deltas
// were absent (e.g. older claude without --include-partial-messages).
if (obj.type === "assistant" && obj.message && typeof obj.message === "object") {
const msg = obj.message as {
content?: Array<{ type?: string; text?: string; name?: string; input?: unknown }>;
usage?: Record<string, number>;
model?: string;
};
const toolHtml = rescueHtmlFromToolUse(msg.content);
if (toolHtml) {
out.push({ kind: "html", text: toolHtml });
// suppress the chatty assistant text fallback below; the Write input
// is authoritative for this turn.
state.sawStreamEventText = true;
}
if (!state.sawStreamEventText) {
const text = (msg.content ?? [])
.filter((c) => c?.type === "text" && typeof c.text === "string")
.map((c) => c.text!)
.join("");
if (text) out.push({ kind: "delta", text });
}
if (msg.usage) out.push({ kind: "meta", key: "usage_partial", value: msg.usage });
}
if (obj.type === "result") {
if (obj.usage) out.push({ kind: "meta", key: "usage", value: obj.usage });
if (typeof obj.duration_ms === "number") out.push({ kind: "meta", key: "duration_ms", value: obj.duration_ms });
if (typeof obj.total_cost_usd === "number") out.push({ kind: "meta", key: "cost_usd", value: obj.total_cost_usd });
if (typeof obj.subtype === "string") out.push({ kind: "meta", key: "result", value: obj.subtype });
}
if (obj.type === "rate_limit_event" && obj.rate_limit_info) {
out.push({ kind: "meta", key: "rate_limit", value: obj.rate_limit_info });
}
}
if (agent === "codex") {
if (obj.type === "item.completed" && obj.item && typeof obj.item === "object") {
const item = obj.item as { item_type?: string; type?: string; text?: string };
const itemType = item.item_type ?? item.type;
if (
(itemType === "assistant_message" || itemType === "agent_message") &&
typeof item.text === "string"
) {
out.push({ kind: "delta", text: item.text });
}
}
if (obj.type === "item.delta" && typeof obj.text === "string") {
out.push({ kind: "delta", text: obj.text });
}
if (obj.msg && typeof obj.msg === "object") {
const msg = obj.msg as { type?: string; message?: string };
if (msg.type === "agent_message" && typeof msg.message === "string") {
out.push({ kind: "delta", text: msg.message });
}
}
if (obj.type === "task_complete" && obj.usage) {
out.push({ kind: "meta", key: "usage", value: obj.usage });
}
if (obj.type === "turn.completed" && obj.usage) {
out.push({ kind: "meta", key: "usage", value: obj.usage });
}
}
if (agent === "cursor-agent" || agent === "gemini") {
if (obj.type === "stream_event" && obj.event && typeof obj.event === "object") {
const ev = obj.event as { type?: string; delta?: { type?: string; text?: string } };
if (ev.delta?.type === "text_delta" && typeof ev.delta.text === "string") {
state.sawStreamEventText = true;
out.push({ kind: "delta", text: ev.delta.text });
}
}
if (obj.type === "assistant" && obj.message && typeof obj.message === "object") {
const msg = obj.message as { content?: Array<{ type?: string; text?: string; name?: string; input?: unknown }> };
const toolHtml = rescueHtmlFromToolUse(msg.content);
if (toolHtml) {
out.push({ kind: "html", text: toolHtml });
state.sawStreamEventText = true;
}
if (!state.sawStreamEventText) {
const text = (msg.content ?? [])
.filter((c) => c?.type === "text" && typeof c.text === "string")
.map((c) => c.text!)
.join("");
if (text) out.push({ kind: "delta", text });
}
}
// Bare `text` field — only honor it when we haven't already emitted a
// streamed delta or an assistant body, otherwise it duplicates the same
// payload (cursor-agent / gemini both ship this redundancy on some
// versions).
if (typeof obj.text === "string" && !state.sawStreamEventText && obj.type !== "assistant") {
out.push({ kind: "delta", text: obj.text as string });
}
}
if (agent === "copilot") {
if (typeof obj.response === "string") out.push({ kind: "delta", text: obj.response });
if (typeof obj.text === "string") out.push({ kind: "delta", text: obj.text });
}
if (agent === "opencode" || agent === "qwen") {
if (typeof obj.text === "string") out.push({ kind: "delta", text: obj.text });
if (typeof obj.content === "string") out.push({ kind: "delta", text: obj.content });
if (typeof obj.message === "string") out.push({ kind: "delta", text: obj.message });
}
if (agent === "qoder") {
// Qoder's stream-json output mirrors claude's envelope shape (init/system,
// stream_event with content_block_delta/text_delta, assistant message,
// result with usage). Parse generously across both fine-grained deltas and
// full assistant turns. Falls back to a bare `text` field for
// forward-compatibility with future Qoder JSON variants.
if (obj.type === "system" && obj.subtype === "init") {
if (obj.model) out.push({ kind: "meta", key: "model", value: obj.model });
if (obj.session_id) out.push({ kind: "meta", key: "session", value: obj.session_id });
}
if (obj.type === "stream_event" && obj.event && typeof obj.event === "object") {
const ev = obj.event as { type?: string; delta?: { type?: string; text?: string } };
if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && typeof ev.delta.text === "string") {
state.sawStreamEventText = true;
out.push({ kind: "delta", text: ev.delta.text });
}
}
if (obj.type === "assistant" && obj.message && typeof obj.message === "object") {
const msg = obj.message as { content?: Array<{ type?: string; text?: string; name?: string; input?: unknown }> };
const toolHtml = rescueHtmlFromToolUse(msg.content);
if (toolHtml) {
out.push({ kind: "html", text: toolHtml });
state.sawStreamEventText = true;
}
if (!state.sawStreamEventText) {
const text = (msg.content ?? [])
.filter((c) => c?.type === "text" && typeof c.text === "string")
.map((c) => c.text!)
.join("");
if (text) out.push({ kind: "delta", text });
}
}
if (obj.type === "result") {
if (obj.usage) out.push({ kind: "meta", key: "usage", value: obj.usage });
if (typeof obj.duration_ms === "number") out.push({ kind: "meta", key: "duration_ms", value: obj.duration_ms });
}
if (typeof obj.text === "string" && !state.sawStreamEventText && obj.type !== "assistant") {
out.push({ kind: "delta", text: obj.text });
}
}
return out;
}
/** Back-compat shim for callers that just want plain text. */
export function extractTextFromLine(agent: string, line: string): string {
return parseLine(agent, line)
.filter((p): p is Extract<AgentParse, { kind: "delta" }> => p.kind === "delta")
.map((p) => p.text)
.join("");
}