@jantcz/webai 0.0.0-stage → 0.2.0
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/LICENSE +135 -0
- package/README.md +24 -2
- package/agents/.claude-plugin/plugin.json +4 -0
- package/agents/README.md +17 -0
- package/agents/agents/a11y-reviewer.md +16 -0
- package/agents/agents/copy-editor.md +14 -0
- package/agents/skills/czech-copy/SKILL.md +18 -0
- package/agents/skills/element-edit/SKILL.md +51 -0
- package/agents/skills/stock-images/SKILL.md +25 -0
- package/agents/skills/verify-change/SKILL.md +19 -0
- package/agents/skills/web-styling/SKILL.md +20 -0
- package/bin/webai-agent.js +355 -0
- package/bin/webai-bridge.js +5 -0
- package/bin/webai.js +4 -0
- package/package.json +85 -4
- package/src/agents/claude.js +161 -0
- package/src/agents/codex.js +111 -0
- package/src/agents/custom.js +64 -0
- package/src/agents/docker.js +46 -0
- package/src/agents/gemini.js +102 -0
- package/src/agents/index.js +25 -0
- package/src/agents/opencode.js +117 -0
- package/src/agents/pack.js +99 -0
- package/src/agents/pi.js +143 -0
- package/src/agents/webai.js +66 -0
- package/src/astro/annotate.js +163 -0
- package/src/astro/index.d.ts +5 -0
- package/src/astro/index.js +40 -0
- package/src/bridge.js +62 -0
- package/src/cli.js +108 -0
- package/src/client/overlay.js +887 -0
- package/src/config.js +23 -0
- package/src/core.js +102 -0
- package/src/history.js +108 -0
- package/src/html.js +43 -0
- package/src/index.d.ts +228 -0
- package/src/index.js +10 -0
- package/src/inject.js +80 -0
- package/src/next/index.d.ts +8 -0
- package/src/next/index.js +59 -0
- package/src/next/script.d.ts +3 -0
- package/src/next/script.js +13 -0
- package/src/prompt.js +17 -0
- package/src/proxy.js +68 -0
- package/src/server.js +211 -0
- package/src/session.js +455 -0
- package/src/static.js +64 -0
- package/src/vite.d.ts +5 -0
- package/src/vite.js +42 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { linkSkills, tomlString, writeCodexAgents } from './pack.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Adapter for the OpenAI Codex CLI (`codex exec --json`).
|
|
6
|
+
*
|
|
7
|
+
* Codex doesn't let us set the conversation ID up front: it assigns one in the first
|
|
8
|
+
* `thread.started` event and later messages resume via `codex exec resume <id>`.
|
|
9
|
+
* Codex reports no costs, only tokens.
|
|
10
|
+
*
|
|
11
|
+
* Written from the docs and the codex-rs sources (exec_events.rs), not yet
|
|
12
|
+
* tested for real.
|
|
13
|
+
*
|
|
14
|
+
* @param {object} [opts]
|
|
15
|
+
* @param {string} [opts.bin]
|
|
16
|
+
* @param {string} [opts.model]
|
|
17
|
+
* @param {string[]} [opts.models] models offered in the panel
|
|
18
|
+
* @param {string} [opts.sandbox] default `workspace-write`
|
|
19
|
+
* @param {string[]} [opts.extraArgs]
|
|
20
|
+
*/
|
|
21
|
+
export function codexAgent(opts = {}) {
|
|
22
|
+
const bin = opts.bin ?? 'codex';
|
|
23
|
+
return {
|
|
24
|
+
name: 'codex',
|
|
25
|
+
label: 'Codex',
|
|
26
|
+
bin,
|
|
27
|
+
presetSessionId: false,
|
|
28
|
+
|
|
29
|
+
settings: {
|
|
30
|
+
model: [
|
|
31
|
+
{ value: '', label: opts.model ? `Default (${opts.model})` : 'Default from ~/.codex/config.toml' },
|
|
32
|
+
...(opts.models ?? []).map((m) => ({ value: m, label: m })),
|
|
33
|
+
],
|
|
34
|
+
effort: [{ value: '', label: 'Default' }, ...['low', 'medium', 'high'].map((v) => ({ value: v, label: v }))],
|
|
35
|
+
},
|
|
36
|
+
|
|
37
|
+
prepare({ root }) {
|
|
38
|
+
return [...linkSkills(root), ...writeCodexAgents(root)];
|
|
39
|
+
},
|
|
40
|
+
|
|
41
|
+
command({ sessionId, resume, systemPrompt, settings = {} }) {
|
|
42
|
+
const flags = [
|
|
43
|
+
'--json',
|
|
44
|
+
'--skip-git-repo-check',
|
|
45
|
+
'--sandbox', opts.sandbox ?? 'workspace-write',
|
|
46
|
+
'-c', 'approval_policy="never"',
|
|
47
|
+
'-c', `developer_instructions=${tomlString(systemPrompt)}`,
|
|
48
|
+
];
|
|
49
|
+
const model = settings.model || opts.model;
|
|
50
|
+
if (model) flags.push('--model', model);
|
|
51
|
+
if (settings.effort) flags.push('-c', `model_reasoning_effort="${settings.effort}"`);
|
|
52
|
+
flags.push(...(opts.extraArgs ?? []));
|
|
53
|
+
// `-` = prompt from stdin. Flags belong to `exec`, hence before the `resume` subcommand.
|
|
54
|
+
const args = resume ? ['exec', ...flags, 'resume', sessionId, '-'] : ['exec', ...flags, '-'];
|
|
55
|
+
return { cmd: bin, args, stdin: true };
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
parse(msg, ctx) {
|
|
59
|
+
switch (msg.type) {
|
|
60
|
+
case 'thread.started':
|
|
61
|
+
return [{ type: 'session', id: msg.thread_id }];
|
|
62
|
+
case 'item.started':
|
|
63
|
+
if (msg.item?.type === 'command_execution') {
|
|
64
|
+
return [{ type: 'tool', id: msg.item.id, name: 'Bash', summary: String(msg.item.command ?? '').slice(0, 160) }];
|
|
65
|
+
}
|
|
66
|
+
return [];
|
|
67
|
+
case 'item.completed':
|
|
68
|
+
return item(msg.item, ctx);
|
|
69
|
+
case 'turn.completed':
|
|
70
|
+
return [{ type: 'done', ok: true, tokens: msg.usage }];
|
|
71
|
+
case 'turn.failed':
|
|
72
|
+
return [{ type: 'done', ok: false, error: msg.error?.message ?? 'Codex failed.' }];
|
|
73
|
+
case 'error':
|
|
74
|
+
return [{ type: 'tool-error', text: msg.message }];
|
|
75
|
+
default:
|
|
76
|
+
return [];
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
|
|
80
|
+
isMissingSession(stderr) {
|
|
81
|
+
return /no (session|thread|rollout).*found|not find (session|thread|rollout)/i.test(stderr);
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function item(it, ctx) {
|
|
87
|
+
if (!it) return [];
|
|
88
|
+
switch (it.type) {
|
|
89
|
+
case 'agent_message':
|
|
90
|
+
return it.text?.trim() ? [{ type: 'text', text: it.text }] : [];
|
|
91
|
+
case 'file_change':
|
|
92
|
+
return (it.changes ?? []).map((c) => ({
|
|
93
|
+
type: 'tool',
|
|
94
|
+
id: it.id,
|
|
95
|
+
name: c.kind === 'add' ? 'Write' : 'Edit',
|
|
96
|
+
summary: path.isAbsolute(c.path) ? path.relative(ctx.root, c.path) : c.path,
|
|
97
|
+
}));
|
|
98
|
+
case 'command_execution':
|
|
99
|
+
return it.status === 'failed' || it.status === 'declined'
|
|
100
|
+
? [{ type: 'tool-error', id: it.id, text: `${it.command}: ${it.status === 'declined' ? 'declined' : `exit code ${it.exit_code}`}` }]
|
|
101
|
+
: [];
|
|
102
|
+
case 'mcp_tool_call':
|
|
103
|
+
return [{ type: 'tool', id: it.id, name: `${it.server}.${it.tool}`, summary: '' }];
|
|
104
|
+
case 'web_search':
|
|
105
|
+
return [{ type: 'tool', id: it.id, name: 'WebSearch', summary: it.query ?? '' }];
|
|
106
|
+
case 'error':
|
|
107
|
+
return [{ type: 'tool-error', id: it.id, text: it.message }];
|
|
108
|
+
default:
|
|
109
|
+
return [];
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* "Other": an arbitrary command from the config (`custom.command`), or from the
|
|
3
|
+
* panel with `editable: true`. Runs via /bin/sh in the project
|
|
4
|
+
* root. The prompt goes to stdin, or in place of `{prompt}`. `{session}` is a
|
|
5
|
+
* stable conversation ID (new after "New") so the command can resume.
|
|
6
|
+
* Output is treated as plain text.
|
|
7
|
+
*/
|
|
8
|
+
export function customAgent(opts = {}) {
|
|
9
|
+
// Off by default: any script on the dev page can read the overlay token, and an
|
|
10
|
+
// editable command would let it run anything on this machine.
|
|
11
|
+
const editable = opts.editable ?? false;
|
|
12
|
+
return {
|
|
13
|
+
name: 'custom',
|
|
14
|
+
label: 'Other',
|
|
15
|
+
bin: null, // nothing to detect
|
|
16
|
+
presetSessionId: true,
|
|
17
|
+
raw: true,
|
|
18
|
+
|
|
19
|
+
settings: {
|
|
20
|
+
command: {
|
|
21
|
+
type: 'text',
|
|
22
|
+
label: 'Command',
|
|
23
|
+
placeholder: 'e.g. aider --yes --message {prompt}',
|
|
24
|
+
hint: editable
|
|
25
|
+
? 'Runs via /bin/sh in the project root. The prompt goes to stdin, or in place of {prompt}; {session} is the conversation ID. Both are substituted already quoted, don\'t wrap them in more quotes.'
|
|
26
|
+
: 'Set in the config (custom.command); custom: { editable: true } allows changing it here.',
|
|
27
|
+
default: opts.command ?? '',
|
|
28
|
+
readonly: !editable,
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
|
|
32
|
+
command({ sessionId, settings = {}, prompt }) {
|
|
33
|
+
const template = ((editable && settings.command) || opts.command || '').trim();
|
|
34
|
+
if (!template) {
|
|
35
|
+
throw new Error(editable ? 'Enter a command for "Other" in the settings (⚙).' : 'The command for "Other" is not set in the config (custom.command).');
|
|
36
|
+
}
|
|
37
|
+
const usesPrompt = template.includes('{prompt}');
|
|
38
|
+
const line = template
|
|
39
|
+
.replaceAll('{prompt}', shellQuote(prompt))
|
|
40
|
+
.replaceAll('{session}', shellQuote(sessionId));
|
|
41
|
+
// Always POSIX sh: with fish or nushell the template and quotes would mean something else.
|
|
42
|
+
return { cmd: '/bin/sh', args: ['-c', line], stdin: !usesPrompt, promptInArgs: usesPrompt };
|
|
43
|
+
},
|
|
44
|
+
|
|
45
|
+
parse(line, ctx) {
|
|
46
|
+
ctx.text = (ctx.text ?? '') + line + '\n';
|
|
47
|
+
return [{ type: 'delta', text: line + '\n', plain: true }];
|
|
48
|
+
},
|
|
49
|
+
|
|
50
|
+
onExit({ code, signal }, ctx) {
|
|
51
|
+
const text = ctx.text?.trim();
|
|
52
|
+
return [
|
|
53
|
+
...(text ? [{ type: 'text', text, plain: true }] : []),
|
|
54
|
+
signal
|
|
55
|
+
? { type: 'done', ok: false, error: 'Stopped.' }
|
|
56
|
+
: { type: 'done', ok: code === 0, error: code === 0 ? undefined : `Command exited with code ${code}.${ctx.stderr ? `\n${ctx.stderr.trim().slice(-600)}` : ''}` },
|
|
57
|
+
];
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function shellQuote(s) {
|
|
63
|
+
return `'${String(s).replaceAll("'", `'\\''`)}'`;
|
|
64
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Agent in a container: each message = `docker compose run --rm <service> <cli> …`.
|
|
6
|
+
* The container exits with the process; state (sessions) lives in the service's volumes.
|
|
7
|
+
*
|
|
8
|
+
* @param {{ service: string, workdir: string }} docker compose service and the project root inside it
|
|
9
|
+
*/
|
|
10
|
+
export function inDocker(docker) {
|
|
11
|
+
return {
|
|
12
|
+
/**
|
|
13
|
+
* Command for `spawn`: `docker` and its arguments, including `-e KEY=…` variables.
|
|
14
|
+
* The container gets its own name: killing the `docker compose run` client
|
|
15
|
+
* does not stop it, so Stop removes it via `cleanup` (`docker rm -f`).
|
|
16
|
+
*/
|
|
17
|
+
command(bin, args, env = {}) {
|
|
18
|
+
const name = `webai-${docker.service}-${randomBytes(4).toString('hex')}`;
|
|
19
|
+
const envArgs = Object.entries(env).flatMap(([k, v]) => ['-e', `${k}=${v}`]);
|
|
20
|
+
return {
|
|
21
|
+
cmd: 'docker',
|
|
22
|
+
args: ['compose', 'run', '--rm', '-T', '--no-deps', '--name', name, ...envArgs, docker.service, bin, ...args],
|
|
23
|
+
cleanup: { cmd: 'docker', args: ['rm', '-f', name] },
|
|
24
|
+
};
|
|
25
|
+
},
|
|
26
|
+
/** Host path (inside the project or repo) → path in the container. */
|
|
27
|
+
path(hostPath, root) {
|
|
28
|
+
return path.posix.join(docker.workdir, path.relative(root, hostPath).split(path.sep).join('/'));
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Stderr without `docker compose` messages about containers and volumes. */
|
|
34
|
+
export function cleanStderr(stderr = '') {
|
|
35
|
+
return stderr
|
|
36
|
+
.split('\n')
|
|
37
|
+
.filter((l) => !/^\s*(Container|Volume|Network) \S+ (Creating|Created|Starting|Started|Removing|Removed)\s*$/.test(l))
|
|
38
|
+
.join('\n')
|
|
39
|
+
.trim();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Shortens an absolute path from an agent tool to one relative to the project root. */
|
|
43
|
+
export function relPath(file, base) {
|
|
44
|
+
if (typeof file !== 'string') return '';
|
|
45
|
+
return path.posix.isAbsolute(file) ? path.posix.relative(base, file) || file : file;
|
|
46
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { linkMarkdownAgents, linkSkills } from './pack.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Adapter for the Google Gemini CLI (`gemini -p … --output-format stream-json`).
|
|
6
|
+
*
|
|
7
|
+
* We pick the conversation ID ourselves (`--session-id` first, then `--resume`).
|
|
8
|
+
* Gemini can only replace the system prompt, not append to it, so the instructions
|
|
9
|
+
* go at the start of the first message, where they stay in the history.
|
|
10
|
+
*
|
|
11
|
+
* Written from the gemini-cli docs (headless.md, output/types.ts), not yet
|
|
12
|
+
* tested for real.
|
|
13
|
+
*
|
|
14
|
+
* @param {object} [opts]
|
|
15
|
+
* @param {string} [opts.bin]
|
|
16
|
+
* @param {string} [opts.model]
|
|
17
|
+
* @param {string} [opts.approvalMode] default `auto_edit`
|
|
18
|
+
* @param {string[]} [opts.extraArgs]
|
|
19
|
+
*/
|
|
20
|
+
export function geminiAgent(opts = {}) {
|
|
21
|
+
const bin = opts.bin ?? 'gemini';
|
|
22
|
+
return {
|
|
23
|
+
name: 'gemini',
|
|
24
|
+
label: 'Gemini CLI',
|
|
25
|
+
bin,
|
|
26
|
+
presetSessionId: true,
|
|
27
|
+
|
|
28
|
+
settings: {
|
|
29
|
+
model: [
|
|
30
|
+
{ value: '', label: opts.model ? `Default (${opts.model})` : 'Default' },
|
|
31
|
+
...['auto', 'pro', 'flash', 'flash-lite'].map((m) => ({ value: m, label: m })),
|
|
32
|
+
],
|
|
33
|
+
},
|
|
34
|
+
|
|
35
|
+
prepare({ root }) {
|
|
36
|
+
return [...linkSkills(root), ...linkMarkdownAgents(root, '.gemini/agents')];
|
|
37
|
+
},
|
|
38
|
+
|
|
39
|
+
wrapPrompt(prompt, { systemPrompt, resume }) {
|
|
40
|
+
return resume ? prompt : `${systemPrompt}\n\n${prompt}`;
|
|
41
|
+
},
|
|
42
|
+
|
|
43
|
+
command({ sessionId, resume, settings = {}, prompt }) {
|
|
44
|
+
const args = [
|
|
45
|
+
'--output-format', 'stream-json',
|
|
46
|
+
'--approval-mode', opts.approvalMode ?? 'auto_edit',
|
|
47
|
+
resume ? '--resume' : '--session-id', sessionId,
|
|
48
|
+
];
|
|
49
|
+
const model = settings.model || opts.model;
|
|
50
|
+
if (model) args.push('--model', model);
|
|
51
|
+
args.push(...(opts.extraArgs ?? []));
|
|
52
|
+
// `--prompt=…` as one argument: a message starting with "-" would otherwise be read as a flag.
|
|
53
|
+
args.push(`--prompt=${prompt}`);
|
|
54
|
+
return { cmd: bin, args, promptInArgs: true };
|
|
55
|
+
},
|
|
56
|
+
|
|
57
|
+
parse(msg, ctx) {
|
|
58
|
+
switch (msg.type) {
|
|
59
|
+
case 'init':
|
|
60
|
+
return [{ type: 'session', id: msg.session_id }, { type: 'status', text: `${msg.model ?? 'gemini'} ready` }];
|
|
61
|
+
case 'message':
|
|
62
|
+
if (msg.role !== 'assistant') return [];
|
|
63
|
+
if (msg.delta) {
|
|
64
|
+
ctx.text = (ctx.text ?? '') + msg.content;
|
|
65
|
+
return [{ type: 'delta', text: msg.content }];
|
|
66
|
+
}
|
|
67
|
+
ctx.text = '';
|
|
68
|
+
return msg.content?.trim() ? [{ type: 'text', text: msg.content }] : [];
|
|
69
|
+
case 'tool_use':
|
|
70
|
+
return [...flush(ctx), { type: 'tool', id: msg.tool_id, name: msg.tool_name, summary: summarize(msg.parameters, ctx.root) }];
|
|
71
|
+
case 'tool_result':
|
|
72
|
+
return msg.status === 'error' ? [{ type: 'tool-error', id: msg.tool_id, text: msg.error?.message ?? 'error' }] : [];
|
|
73
|
+
case 'error':
|
|
74
|
+
return msg.severity === 'error' ? [{ type: 'tool-error', text: msg.message }] : [];
|
|
75
|
+
case 'result':
|
|
76
|
+
return [
|
|
77
|
+
...flush(ctx),
|
|
78
|
+
{ type: 'done', ok: msg.status !== 'error', error: msg.error?.message, durationMs: msg.stats?.duration_ms, tokens: msg.stats },
|
|
79
|
+
];
|
|
80
|
+
default:
|
|
81
|
+
return [];
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
|
|
85
|
+
isMissingSession(stderr) {
|
|
86
|
+
return /session.*not found|no session/i.test(stderr);
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Join the deltas into one finished text so it gets saved to the history. */
|
|
92
|
+
function flush(ctx) {
|
|
93
|
+
const text = ctx.text?.trim();
|
|
94
|
+
ctx.text = '';
|
|
95
|
+
return text ? [{ type: 'text', text }] : [];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function summarize(params = {}, root) {
|
|
99
|
+
const file = params.file_path ?? params.absolute_path ?? params.path;
|
|
100
|
+
if (file) return path.isAbsolute(file) ? path.relative(root, file) : file;
|
|
101
|
+
return String(params.command ?? params.pattern ?? params.query ?? '').slice(0, 160);
|
|
102
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { claudeAgent } from './claude.js';
|
|
2
|
+
import { codexAgent } from './codex.js';
|
|
3
|
+
import { customAgent } from './custom.js';
|
|
4
|
+
import { geminiAgent } from './gemini.js';
|
|
5
|
+
import { opencodeAgent } from './opencode.js';
|
|
6
|
+
import { piAgent } from './pi.js';
|
|
7
|
+
import { webaiAgent } from './webai.js';
|
|
8
|
+
|
|
9
|
+
export { claudeAgent, codexAgent, customAgent, geminiAgent, opencodeAgent, piAgent, webaiAgent };
|
|
10
|
+
|
|
11
|
+
/** Built-in agents + custom ones from options, "Other" always last in the menu. */
|
|
12
|
+
export function resolveAgents(options = {}) {
|
|
13
|
+
const agents = {
|
|
14
|
+
claude: claudeAgent(options.claude),
|
|
15
|
+
codex: codexAgent(options.codex),
|
|
16
|
+
gemini: geminiAgent(options.gemini),
|
|
17
|
+
opencode: opencodeAgent(options.opencode),
|
|
18
|
+
pi: piAgent(options.pi),
|
|
19
|
+
webai: webaiAgent(options.webai),
|
|
20
|
+
};
|
|
21
|
+
for (const agent of options.agents ?? []) agents[agent.name] = agent;
|
|
22
|
+
agents.custom = customAgent(options.custom);
|
|
23
|
+
for (const [name, agent] of Object.entries(agents)) agent.label ??= name;
|
|
24
|
+
return agents;
|
|
25
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { cleanStderr, inDocker, relPath } from './docker.js';
|
|
2
|
+
import { linkSkills } from './pack.js';
|
|
3
|
+
|
|
4
|
+
const TOOL_NAMES = { read: 'Read', edit: 'Edit', write: 'Write', glob: 'Glob', grep: 'Grep', list: 'LS', bash: 'Bash', webfetch: 'WebFetch' };
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* May edit files, but not use the shell or the web (same as Claude without allowedTools).
|
|
8
|
+
* Passed via OPENCODE_CONFIG_CONTENT, which takes precedence over the project's opencode.json.
|
|
9
|
+
*/
|
|
10
|
+
const PERMISSIONS = { edit: 'allow', bash: 'deny', webfetch: 'deny' };
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Adapter for OpenCode (`opencode run --format json`). Its `-free` models
|
|
14
|
+
* (OpenCode Zen) work without an account or API key, but only from the OpenCode client.
|
|
15
|
+
*
|
|
16
|
+
* OpenCode assigns the session ID (`ses_…`), later messages resume via `-s`.
|
|
17
|
+
* It can't append a system prompt from the command line, so it goes at the start
|
|
18
|
+
* of the first message. JSON mode has no deltas, text arrives in blocks.
|
|
19
|
+
*
|
|
20
|
+
* @param {object} [opts]
|
|
21
|
+
* @param {string} [opts.bin] default `opencode`
|
|
22
|
+
* @param {{ service: string, workdir: string }} [opts.docker] run in a container, see docker-compose.yml
|
|
23
|
+
* @param {string} [opts.model] default `opencode/deepseek-v4.1-flash-free`
|
|
24
|
+
* @param {{ value: string, label: string }[]} [opts.models]
|
|
25
|
+
* @param {Record<string, string>} [opts.permission] default edit: allow, bash and webfetch: deny
|
|
26
|
+
* @param {string[]} [opts.extraArgs]
|
|
27
|
+
*/
|
|
28
|
+
export function opencodeAgent(opts = {}) {
|
|
29
|
+
const bin = opts.bin ?? 'opencode';
|
|
30
|
+
const docker = opts.docker && inDocker(opts.docker);
|
|
31
|
+
const run = (args, env) => (docker ? docker.command(bin, args, env) : { cmd: bin, args, env });
|
|
32
|
+
const defaultModel = opts.model ?? 'opencode/deepseek-v4.1-flash-free';
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
name: 'opencode',
|
|
36
|
+
label: docker ? 'OpenCode (Docker)' : 'OpenCode',
|
|
37
|
+
bin: docker ? 'docker' : bin,
|
|
38
|
+
versionArgs: run(['--version']).args,
|
|
39
|
+
presetSessionId: false,
|
|
40
|
+
|
|
41
|
+
settings: {
|
|
42
|
+
model: [
|
|
43
|
+
{ value: '', label: `Default (${defaultModel})` },
|
|
44
|
+
...(opts.models ?? DEFAULT_MODELS),
|
|
45
|
+
],
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
prepare({ root }) {
|
|
49
|
+
return linkSkills(root);
|
|
50
|
+
},
|
|
51
|
+
|
|
52
|
+
wrapPrompt(prompt, { systemPrompt, resume }) {
|
|
53
|
+
return resume ? prompt : `${systemPrompt}\n\n${prompt}`;
|
|
54
|
+
},
|
|
55
|
+
|
|
56
|
+
command({ sessionId, resume, settings = {}, prompt }) {
|
|
57
|
+
const args = ['run', '--format', 'json', '--model', settings.model || defaultModel];
|
|
58
|
+
if (resume && sessionId) args.push('--session', sessionId);
|
|
59
|
+
args.push(...(opts.extraArgs ?? []), '--', prompt);
|
|
60
|
+
const env = { OPENCODE_CONFIG_CONTENT: JSON.stringify({ permission: { ...PERMISSIONS, ...opts.permission } }) };
|
|
61
|
+
return { ...run(args, env), promptInArgs: true };
|
|
62
|
+
},
|
|
63
|
+
|
|
64
|
+
parse(msg, ctx) {
|
|
65
|
+
const out = [];
|
|
66
|
+
if (msg.sessionID && !ctx.session) {
|
|
67
|
+
ctx.session = msg.sessionID;
|
|
68
|
+
out.push({ type: 'session', id: msg.sessionID });
|
|
69
|
+
}
|
|
70
|
+
const part = msg.part ?? {};
|
|
71
|
+
switch (msg.type) {
|
|
72
|
+
case 'text':
|
|
73
|
+
if (part.text?.trim()) out.push({ type: 'text', text: part.text });
|
|
74
|
+
break;
|
|
75
|
+
case 'tool_use': {
|
|
76
|
+
const state = part.state ?? {};
|
|
77
|
+
if (part.tool === 'invalid') {
|
|
78
|
+
out.push({ type: 'tool-error', id: part.callID, text: String(state.input?.error ?? 'Invalid tool call.').slice(0, 400) });
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
const input = state.input ?? {};
|
|
82
|
+
const base = opts.docker?.workdir ?? ctx.root;
|
|
83
|
+
out.push({
|
|
84
|
+
type: 'tool',
|
|
85
|
+
id: part.callID,
|
|
86
|
+
name: TOOL_NAMES[part.tool] ?? part.tool,
|
|
87
|
+
summary: relPath(input.filePath ?? input.path, base) || String(input.pattern ?? input.command ?? '').slice(0, 160),
|
|
88
|
+
});
|
|
89
|
+
if (state.status === 'error') out.push({ type: 'tool-error', id: part.callID, text: String(state.error ?? '').slice(0, 400) });
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
case 'step_finish':
|
|
93
|
+
ctx.costUsd = (ctx.costUsd ?? 0) + (part.cost ?? 0);
|
|
94
|
+
break;
|
|
95
|
+
case 'error':
|
|
96
|
+
ctx.error = msg.error?.data?.message ?? msg.error?.name ?? 'OpenCode error.';
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
return out;
|
|
100
|
+
},
|
|
101
|
+
|
|
102
|
+
// OpenCode doesn't report the end of a run in JSON; the exit code and any error decide.
|
|
103
|
+
onExit({ code, signal }, ctx) {
|
|
104
|
+
if (signal) return [{ type: 'done', ok: false, error: 'Stopped.' }];
|
|
105
|
+
const error = ctx.error ?? (code === 0 ? undefined : cleanStderr(ctx.stderr).slice(-600) || `OpenCode exited with code ${code}.`);
|
|
106
|
+
return [{ type: 'done', ok: !error, error, costUsd: ctx.costUsd ?? 0 }];
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Free OpenCode Zen models. The lineup changes, current list: `opencode models opencode`. */
|
|
112
|
+
const DEFAULT_MODELS = [
|
|
113
|
+
{ value: 'opencode/deepseek-v4.1-flash-free', label: 'DeepSeek V4.1 Flash (free)' },
|
|
114
|
+
{ value: 'opencode/mimo-v2.6-flash-free', label: 'MiMo V2.6 Flash (free)' },
|
|
115
|
+
{ value: 'opencode/nemotron-3-ultra-free', label: 'Nemotron 3 Ultra (free)' },
|
|
116
|
+
{ value: 'opencode/step-5-preview-free', label: 'Step 5 Preview (free)' },
|
|
117
|
+
];
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
|
|
5
|
+
/** Pack of skills and subagents (`@jantcz/webai/agents`), shared by all CLIs. */
|
|
6
|
+
export const PACK_DIR = fileURLToPath(new URL('../../agents/', import.meta.url));
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Codex and Gemini look for skills only in the project (`.agents/skills/`), not in
|
|
10
|
+
* an arbitrary folder, so we link them there. An existing file with the same name
|
|
11
|
+
* is not overwritten, it belongs to the user.
|
|
12
|
+
*
|
|
13
|
+
* @returns {string[]} relative paths of newly created links
|
|
14
|
+
*/
|
|
15
|
+
export function linkSkills(root, targetDir = '.agents/skills') {
|
|
16
|
+
const created = [];
|
|
17
|
+
const src = path.join(PACK_DIR, 'skills');
|
|
18
|
+
for (const name of fs.readdirSync(src)) {
|
|
19
|
+
const dest = path.join(root, targetDir, name);
|
|
20
|
+
if (exists(dest)) continue;
|
|
21
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
22
|
+
fs.symlinkSync(relativeTo(dest, path.join(src, name)), dest, 'dir');
|
|
23
|
+
created.push(path.relative(root, dest));
|
|
24
|
+
}
|
|
25
|
+
return created;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Subagents in Markdown + frontmatter format (Claude Code, Gemini CLI). */
|
|
29
|
+
export function linkMarkdownAgents(root, targetDir) {
|
|
30
|
+
const created = [];
|
|
31
|
+
for (const { file } of readAgents()) {
|
|
32
|
+
const dest = path.join(root, targetDir, path.basename(file));
|
|
33
|
+
if (exists(dest)) continue;
|
|
34
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
35
|
+
fs.symlinkSync(relativeTo(dest, file), dest);
|
|
36
|
+
created.push(path.relative(root, dest));
|
|
37
|
+
}
|
|
38
|
+
return created;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Codex wants subagents in TOML (`name`, `description`, `developer_instructions`). */
|
|
42
|
+
export function writeCodexAgents(root, targetDir = '.codex/agents') {
|
|
43
|
+
const created = [];
|
|
44
|
+
for (const { name, description, body } of readAgents()) {
|
|
45
|
+
const dest = path.join(root, targetDir, `${name}.toml`);
|
|
46
|
+
if (exists(dest)) continue;
|
|
47
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
48
|
+
const toml = [
|
|
49
|
+
'# Generated from @jantcz/webai/agents, edit the source there.',
|
|
50
|
+
`name = ${tomlString(name)}`,
|
|
51
|
+
`description = ${tomlString(description)}`,
|
|
52
|
+
`developer_instructions = ${tomlString(body)}`,
|
|
53
|
+
'',
|
|
54
|
+
].join('\n');
|
|
55
|
+
fs.writeFileSync(dest, toml);
|
|
56
|
+
created.push(path.relative(root, dest));
|
|
57
|
+
}
|
|
58
|
+
return created;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function readAgents() {
|
|
62
|
+
const dir = path.join(PACK_DIR, 'agents');
|
|
63
|
+
return fs
|
|
64
|
+
.readdirSync(dir)
|
|
65
|
+
.filter((f) => f.endsWith('.md'))
|
|
66
|
+
.map((f) => {
|
|
67
|
+
const file = path.join(dir, f);
|
|
68
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
69
|
+
const [, front = '', body = text] = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/) ?? [];
|
|
70
|
+
const field = (key) => front.match(new RegExp(`^${key}:\\s*(.*)$`, 'm'))?.[1].trim() ?? '';
|
|
71
|
+
return { file, name: field('name') || path.basename(f, '.md'), description: field('description'), body: body.trim() };
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A JSON string is a valid TOML basic string (escapes \n, \", \\, \uXXXX). */
|
|
76
|
+
export function tomlString(s) {
|
|
77
|
+
return JSON.stringify(s);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* A relative link works in a container and in another clone of the repo too. It is
|
|
82
|
+
* computed from the folder's real path: if the path to the project goes through a symlink,
|
|
83
|
+
* the system resolves ".." from the symlink target, not from the path we gave.
|
|
84
|
+
*/
|
|
85
|
+
function relativeTo(link, target) {
|
|
86
|
+
return path.relative(fs.realpathSync(path.dirname(link)), fs.realpathSync(target));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Exists, or is a link that still points somewhere. A broken link gets replaced. */
|
|
90
|
+
function exists(p) {
|
|
91
|
+
try {
|
|
92
|
+
fs.lstatSync(p);
|
|
93
|
+
} catch {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
if (fs.existsSync(p)) return true;
|
|
97
|
+
fs.rmSync(p, { force: true });
|
|
98
|
+
return false;
|
|
99
|
+
}
|