@clarity-js/agent 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/src/ci.js ADDED
@@ -0,0 +1,121 @@
1
+ // @clarity-js/agent — the agent as a job of a pipeline: files for GitHub Actions and GitLab CI that run one task
2
+ // headless and leave what it changed as a pull request (a merge request), never on the main branch.
3
+ //
4
+ // clarity agent ci github [--schedule "0 6 * * 1" --task "…"] [--write] .github/workflows/clarity-agent.yml
5
+ // clarity agent ci gitlab [--schedule …] [--write] .clarity/agent/gitlab-ci.yml (to include)
6
+ //
7
+ // The provider's key is a secret of the repository, read from the environment; it is in no file. What somebody
8
+ // wrote in an issue comment reaches the agent through an environment variable, never as text of the script.
9
+
10
+ const q = (s) => `'${String(s).replace(/'/g, "''")}'`;
11
+
12
+ /** A workflow for GitHub Actions. keyEnv: the secret's name (ANTHROPIC_API_KEY). */
13
+ export function githubWorkflow({ schedule = null, task = '', model = '', keyEnv = 'ANTHROPIC_API_KEY', allow = ['npm test'], node = 22 } = {}) {
14
+ const allows = allow.map((a) => ` --allow ${JSON.stringify(a)}`).join('');
15
+ return `# Clarity Agent as a job: run it by hand (Actions → Clarity Agent → Run workflow), by a comment that starts
16
+ # with "/clarity " on an issue (from somebody who may write to the repository)${schedule ? ', and at set times' : ''}.
17
+ # It works on a branch of its own and opens a pull request; it cannot push to the default branch from here.
18
+ name: Clarity Agent
19
+ on:
20
+ workflow_dispatch:
21
+ inputs:
22
+ task:
23
+ description: What to do
24
+ required: true
25
+ issue_comment:
26
+ types: [created]${schedule ? `\n schedule:\n - cron: ${q(schedule)}` : ''}
27
+
28
+ permissions:
29
+ contents: write
30
+ pull-requests: write
31
+ issues: write
32
+
33
+ concurrency:
34
+ group: clarity-agent-\${{ github.event.issue.number || github.run_id }}
35
+ cancel-in-progress: false
36
+
37
+ jobs:
38
+ agent:
39
+ if: >-
40
+ github.event_name != 'issue_comment' ||
41
+ (startsWith(github.event.comment.body, '/clarity ') &&
42
+ contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.comment.author_association))
43
+ runs-on: ubuntu-latest
44
+ timeout-minutes: 45
45
+ env:
46
+ ${keyEnv}: \${{ secrets.${keyEnv} }}${model ? `\n CLARITY_MODEL: ${q(model)}` : ''}
47
+ # what was asked, as data: never pasted into a script
48
+ TASK_INPUT: \${{ inputs.task }}
49
+ TASK_COMMENT: \${{ github.event.comment.body }}
50
+ TASK_SCHEDULED: ${q(task)}
51
+ ISSUE: \${{ github.event.issue.number }}
52
+ GH_TOKEN: \${{ github.token }}
53
+ steps:
54
+ - uses: actions/checkout@v4
55
+ - uses: actions/setup-node@v4
56
+ with:
57
+ node-version: ${node}
58
+ cache: npm
59
+ - run: npm ci
60
+ - name: The task
61
+ run: |
62
+ if [ -n "$TASK_INPUT" ]; then printf '%s' "$TASK_INPUT" > "$RUNNER_TEMP/task.txt"
63
+ elif [ -n "$TASK_COMMENT" ]; then printf '%s' "\${TASK_COMMENT#/clarity }" > "$RUNNER_TEMP/task.txt"
64
+ else printf '%s' "$TASK_SCHEDULED" > "$RUNNER_TEMP/task.txt"; fi
65
+ test -s "$RUNNER_TEMP/task.txt"
66
+ - name: Clarity Agent
67
+ id: agent
68
+ run: npx clarity agent --headless --mode auto${allows} --summary "$RUNNER_TEMP/summary.md" --task-file "$RUNNER_TEMP/task.txt"
69
+ - name: A pull request with what it changed
70
+ if: always() && steps.agent.outcome != 'skipped'
71
+ run: |
72
+ cat "$RUNNER_TEMP/summary.md" >> "$GITHUB_STEP_SUMMARY" 2>/dev/null || true
73
+ # (its own notes, .clarity/agent, stay out of the pull request)
74
+ if [ -z "$(git status --porcelain -- . ':(exclude).clarity/agent')" ]; then echo "Nothing changed."; exit 0; fi
75
+ branch="clarity-agent/run-$GITHUB_RUN_ID"
76
+ git config user.name "clarity-agent"
77
+ git config user.email "clarity-agent@users.noreply.github.com"
78
+ git checkout -b "$branch"
79
+ git add -A -- . ':(exclude).clarity/agent'
80
+ git commit -m "Clarity Agent: $(head -c 60 "$RUNNER_TEMP/task.txt" | tr '\\n' ' ')"
81
+ git push origin "$branch"
82
+ gh pr create --head "$branch" --title "Clarity Agent: $(head -c 60 "$RUNNER_TEMP/task.txt" | tr '\\n' ' ')" --body-file "$RUNNER_TEMP/summary.md"
83
+ if [ -n "$ISSUE" ]; then gh issue comment "$ISSUE" --body "Done on branch \\\`$branch\\\`; a pull request is open."; fi
84
+ `;
85
+ }
86
+
87
+ /** A job for GitLab CI: run from "Run pipeline" with CLARITY_TASK, from a pipeline schedule, or by a trigger. */
88
+ export function gitlabJob({ task = '', model = '', keyEnv = 'ANTHROPIC_API_KEY', allow = ['npm test'], node = 22 } = {}) {
89
+ const allows = allow.map((a) => ` --allow ${JSON.stringify(a)}`).join('');
90
+ return `# Clarity Agent as a job. Add to .gitlab-ci.yml: include: { local: .clarity/agent/gitlab-ci.yml }
91
+ # Run it from Build → Pipelines → Run pipeline with the variable CLARITY_TASK, or from a pipeline schedule
92
+ # (Build → Pipeline schedules) that sets CLARITY_TASK. Settings → CI/CD → Variables, masked: ${keyEnv} (the
93
+ # provider's key) and CLARITY_PUSH_TOKEN (a project access token that may write to the repository).
94
+ # It works on a branch of its own and opens a merge request; it does not push to the default branch.
95
+ clarity-agent:
96
+ image: node:${node}
97
+ rules:
98
+ - if: '$CLARITY_TASK && ($CI_PIPELINE_SOURCE == "web" || $CI_PIPELINE_SOURCE == "schedule" || $CI_PIPELINE_SOURCE == "trigger" || $CI_PIPELINE_SOURCE == "api")'
99
+ variables:
100
+ GIT_DEPTH: "0"${model ? `\n CLARITY_MODEL: ${q(model)}` : ''}${task ? `\n CLARITY_TASK: ${q(task)}` : ''}
101
+ script:
102
+ - npm ci
103
+ - printf '%s' "$CLARITY_TASK" > /tmp/task.txt
104
+ - npx clarity agent --headless --mode auto${allows} --summary /tmp/summary.md --task-file /tmp/task.txt
105
+ after_script:
106
+ - cat /tmp/summary.md || true
107
+ - if [ -z "$(git status --porcelain -- . ':(exclude).clarity/agent')" ]; then echo "Nothing changed."; exit 0; fi
108
+ - git config user.name "clarity-agent"
109
+ - git config user.email "clarity-agent@noreply.gitlab.com"
110
+ - git checkout -b "clarity-agent/run-$CI_PIPELINE_ID"
111
+ - git add -A -- . ':(exclude).clarity/agent'
112
+ - git commit -m "Clarity Agent, pipeline $CI_PIPELINE_ID"
113
+ - git push -o merge_request.create -o merge_request.title="Clarity Agent, pipeline $CI_PIPELINE_ID" "https://clarity-agent:$CLARITY_PUSH_TOKEN@$CI_SERVER_HOST/$CI_PROJECT_PATH.git" "clarity-agent/run-$CI_PIPELINE_ID"
114
+ artifacts:
115
+ when: always
116
+ paths: [ .clarity/agent/ ]
117
+ expire_in: 1 week
118
+ `;
119
+ }
120
+
121
+ export const CI_FILES = { github: '.github/workflows/clarity-agent.yml', gitlab: '.clarity/agent/gitlab-ci.yml' };
package/src/clarity.js ADDED
@@ -0,0 +1,16 @@
1
+ // @clarity-js/agent — Clarity's own tools for the agent: the language reference, the compiler, a server render,
2
+ // a look at a page in a headless browser, and the game engine. They come from @ozsarman/clarityjs/make, the same
3
+ // ones `clarity mcp --make` gives other agents. Without Clarity installed, the agent works without them.
4
+
5
+ const RISK = { clarity_docs: 'read', clarity_validate: 'read', clarity_look: 'read', clarity_run: 'run', game_kits: 'read', game_validate: 'read', game_play: 'run', game_new: 'write', game_export: 'write' };
6
+
7
+ /** The tools, ready for runAgent(); [] when @ozsarman/clarityjs is not there. */
8
+ export async function clarityTools({ importer = (s) => import(s) } = {}) {
9
+ let M;
10
+ try { M = await importer('@ozsarman/clarityjs/make'); } catch { return []; }
11
+ return M.MAKE_TOOL_LIST.map((t) => ({
12
+ name: t.name, description: t.description, inputSchema: t.inputSchema, risk: RISK[t.name] ?? 'run',
13
+ summary: (a) => `${t.name}${a.file ? ' ' + a.file : a.dir ? ' ' + a.dir : a.pitch ? ` "${a.pitch}"` : a.url ? ' ' + a.url : a.topic ? ` "${a.topic}"` : ''}`,
14
+ run: async (args, ctx) => { const r = await M.callMakeTool(t.name, args, ctx.root); return { text: r.text + (r.image ? '\n(A picture of the page was taken; it is shown to the user.)' : ''), data: r.data, error: r.error, image: r.image }; },
15
+ }));
16
+ }
package/src/cli.js ADDED
@@ -0,0 +1,340 @@
1
+ #!/usr/bin/env node
2
+ // @clarity-js/agent — the command line. `clarity agent`, `clarity dream`, `clarity gen`, `clarity keys` and
3
+ // `clarity models` and `clarity ship` (the clarity command hands these here), or `npx clarity-agent …`.
4
+
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import readline from 'node:readline';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { createAgent, loadConfig, saveUserConfig, envNameOf, chooseModel, keyStore, ledger, usd, provider, PROVIDERS, parseModel, generator, ADAPTERS, KINDS, VERSION, mask, shipper, TARGETS, providerKey, CHAT_KEYS, CHAT_PLATFORMS, chatAdapters, serveChat } from './index.js';
10
+
11
+ const tty = process.stdout.isTTY && !process.env.NO_COLOR;
12
+ const c = { dim: tty ? '\x1b[2m' : '', bold: tty ? '\x1b[1m' : '', cyan: tty ? '\x1b[36m' : '', green: tty ? '\x1b[32m' : '', yellow: tty ? '\x1b[33m' : '', red: tty ? '\x1b[31m' : '', reset: tty ? '\x1b[0m' : '' };
13
+ const out = (s = '') => process.stdout.write(s + '\n'), errOut = (s) => process.stderr.write(`${c.red}${s}${c.reset}\n`);
14
+
15
+ export const USAGE = `Clarity Agent ${VERSION} — builds apps, sites and games with Clarity, on your own model.
16
+
17
+ clarity agent ["what to do"] work in this project (a conversation; with words, one task and exit)
18
+ --model <provider:model> anthropic:claude-sonnet-5-5, openai:<model>, gemini:<model>, deepseek:deepseek-chat,
19
+ kimi:<model>, minimax:<model>, qwen:<model>, ollama:qwen3, lmstudio:<model> …
20
+ --mode ask|edits|auto ask before every change (ask), let it edit files (edits), or also run allowed commands (auto)
21
+ --allow "npm test" a command it may run without asking (again for more)
22
+ clarity agent app the same conversation in a window of its own (--model, --mode, --port n, --no-open)
23
+ clarity agent --headless "…" one task with nobody there (a CI job): nothing is asked, what would be is refused
24
+ --json --summary run.md --task-file f --max-steps n --strict --yes exit 0 done · 2 steps ran out · 3 refused (--strict)
25
+ clarity agent ci github|gitlab a job that runs the agent and opens a pull request (--schedule "0 6 * * 1" --task "…" --write)
26
+ clarity agent schedule add "<cron>" "<task>" | list | remove <id> | run | due tasks at set times, headless
27
+ clarity agent chat answer in Slack, Discord, Telegram and Linear (--port 8787, --host, --mode); first:
28
+ clarity agent chat allow <slack|discord|telegram|linear> <user id> who may talk to it (nobody, until named)
29
+ clarity dream "<idea>" idea → dream.md, style.json, assets.yaml (--mode app|site|game, --dir, --yes: no questions)
30
+ clarity gen <kind> "<prompt>" make an asset: ${KINDS.join(', ')} (--via <connector>, --model, --out, --aspect, --seconds, --yes)
31
+ clarity gen --list the connectors, what each makes, which have keys
32
+ clarity keys list | set <id> [key] | remove <id> | limits [--daily n] [--monthly n]
33
+ clarity models <provider> the models a provider offers for your key
34
+ clarity ship <target> [--dir dist] publish a build: ${Object.keys(TARGETS).join(', ')}
35
+ --site, --project, --domain, --game user/game, --channel html5 what the host needs; --dry: only show the command
36
+
37
+ Keys stay on this computer (the environment, the system keychain, or a file only you can read).
38
+ Paid generations are priced and asked first; the limits stop spending past them.`;
39
+
40
+ const flag = (args, name, fallback = undefined) => { const i = args.indexOf('--' + name); return i >= 0 && args[i + 1] !== undefined && !args[i + 1].startsWith('--') ? args[i + 1] : fallback; };
41
+ const flags = (args, name) => args.flatMap((a, i) => (a === '--' + name && args[i + 1] ? [args[i + 1]] : []));
42
+ const words = (args, valued = []) => { const rest = []; for (let i = 0; i < args.length; i++) { if (args[i].startsWith('--')) { if (valued.includes(args[i].slice(2))) i++; continue; } rest.push(args[i]); } return rest; };
43
+
44
+ function question(rl, q) { return new Promise((resolve) => rl.question(q, (a) => resolve(a))); }
45
+ function asker(rl, { yes = false } = {}) {
46
+ return async ({ summary, risk, usd: price, note }) => {
47
+ if (yes && risk !== 'publish') return true;
48
+ if (!rl) return false;
49
+ const cost = risk === 'spend' ? ` ${c.yellow}${price != null ? `about ${usd(price)}` : 'price set by the service'}${note ? ` — ${note}` : ''}${c.reset}` : '';
50
+ const a = (await question(rl, `${c.yellow}?${c.reset} ${summary}${cost} ${c.dim}[y]es / [n]o${risk === 'exec' ? ' / [a]lways' : ''}${c.reset} `)).trim().toLowerCase();
51
+ return a === 'a' && risk === 'exec' ? 'always' : a === 'y' || a === 'yes' || a === 'e' || a === 'evet';
52
+ };
53
+ }
54
+ function logEvents(root) {
55
+ const dir = path.join(root, '.clarity', 'agent'); fs.mkdirSync(dir, { recursive: true });
56
+ const file = path.join(dir, `session-${new Date().toISOString().replace(/[:.]/g, '-')}.jsonl`);
57
+ return (e) => {
58
+ const line = { at: new Date().toISOString(), type: e.type, ...(e.text ? { text: e.text } : {}), ...(e.call ? { tool: e.call.name, args: e.call.args } : {}), ...(e.result ? { error: !!e.result.error, result: String(e.result.text).slice(0, 2000) } : {}), ...(e.usage ? { usage: e.usage } : {}) };
59
+ fs.appendFileSync(file, JSON.stringify(line) + '\n');
60
+ };
61
+ }
62
+
63
+ // The agent in a window: a server on this computer alone, and a page (app.js). It stays until Ctrl+C.
64
+ async function cmdApp(args) {
65
+ const { startApp } = await import('./app.js');
66
+ let app;
67
+ try { app = await startApp({ root: process.cwd(), model: flag(args, 'model') ?? null, mode: flag(args, 'mode') ?? 'ask', port: Number(flag(args, 'port', 0)) || 0, open: !args.includes('--no-open'), options: { allow: flags(args, 'allow') } }); }
68
+ catch (e) { errOut(e.message); return 1; }
69
+ out(`${c.bold}Clarity Agent${c.reset} ${c.dim}in a window · ${process.cwd()}${c.reset}`);
70
+ out(`${app.shown?.window ? 'Opened as a window.' : app.shown ? 'Opened in your browser.' : 'Open this address:'} ${c.cyan}${app.url}${c.reset}`);
71
+ out(`${c.dim}The address works on this computer only, and only while this runs. Ctrl+C closes it.${c.reset}`);
72
+ await new Promise((done) => process.once('SIGINT', done));
73
+ await app.close();
74
+ return 0;
75
+ }
76
+
77
+ // One task with nobody there (headless.js).
78
+ async function cmdHeadless(args) {
79
+ const { runHeadless } = await import('./headless.js');
80
+ const file = flag(args, 'task-file');
81
+ let task = words(args, ['model', 'mode', 'allow', 'max-steps', 'summary', 'task-file']).join(' ').trim();
82
+ if (file) { try { task = fs.readFileSync(file, 'utf8'); } catch (e) { errOut(`The task file cannot be read: ${e.message}`); return 1; } }
83
+ else if (!task && !process.stdin.isTTY) task = fs.readFileSync(0, 'utf8');
84
+ const r = await runHeadless({ root: process.cwd(), task, model: flag(args, 'model'), mode: flag(args, 'mode') ?? 'ask', allow: flags(args, 'allow'), yes: args.includes('--yes'), json: args.includes('--json'), strict: args.includes('--strict'), maxSteps: Number(flag(args, 'max-steps', 0)) || undefined, summary: flag(args, 'summary') ?? null });
85
+ if (!args.includes('--json')) out(`${c.dim}${r.state} · ${r.steps} step${r.steps === 1 ? '' : 's'} · ${r.changed.length} file${r.changed.length === 1 ? '' : 's'} changed${r.refused.length ? ` · ${r.refused.length} refused (nobody to ask)` : ''}${c.reset}`);
86
+ return r.code;
87
+ }
88
+
89
+ // A pipeline job that runs the agent (ci.js): printed, or written where the pipeline looks for it.
90
+ async function cmdCi(args) {
91
+ const { githubWorkflow, gitlabJob, CI_FILES } = await import('./ci.js'), where = args[0];
92
+ if (!CI_FILES[where]) { errOut('clarity agent ci github | gitlab [--schedule "0 6 * * 1" --task "…"] [--model provider:model] [--key-env NAME] [--write]'); return 1; }
93
+ const schedule = flag(args, 'schedule') ?? null, task = flag(args, 'task') ?? '';
94
+ if (schedule) { try { (await import('./schedule.js')).parseCron(schedule); } catch (e) { errOut(e.message); return 1; } if (!task) { errOut('A schedule needs --task: what to do when its time comes.'); return 1; } }
95
+ const options = { schedule, task, model: flag(args, 'model') ?? '', keyEnv: flag(args, 'key-env') ?? 'ANTHROPIC_API_KEY', allow: flags(args, 'allow').length ? flags(args, 'allow') : ['npm test'] };
96
+ const text = where === 'github' ? githubWorkflow(options) : gitlabJob(options);
97
+ if (!args.includes('--write')) { out(text); return 0; }
98
+ const file = path.join(process.cwd(), CI_FILES[where]);
99
+ if (fs.existsSync(file) && !args.includes('--force')) { errOut(`${CI_FILES[where]} is there already (--force writes over it).`); return 1; }
100
+ fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, text);
101
+ out(`Wrote ${CI_FILES[where]}. ${where === 'github' ? `Add the secret ${options.keyEnv} to the repository (Settings → Secrets and variables → Actions).` : `Include it from .gitlab-ci.yml, and add the variables ${options.keyEnv} and CLARITY_PUSH_TOKEN (masked).`}`);
102
+ return 0;
103
+ }
104
+
105
+ // Tasks at set times (schedule.js).
106
+ async function cmdSchedule(args) {
107
+ const { schedules, serveSchedules } = await import('./schedule.js'), root = process.cwd(), store = schedules({ root }), sub = args[0];
108
+ try {
109
+ if (sub === 'add') {
110
+ const [cron, ...rest] = words(args.slice(1), ['model', 'mode', 'allow']);
111
+ const e = store.add({ cron, task: rest.join(' '), model: flag(args, 'model') ?? null, mode: flag(args, 'mode') ?? 'edits', allow: flags(args, 'allow') });
112
+ out(`Schedule ${e.id}: "${e.cron}" → ${e.task}\n${c.dim}next: ${new Date(store.list().find((x) => x.id === e.id).next).toLocaleString()} · it runs while "clarity agent schedule run" does, or when "clarity agent schedule due" is called${c.reset}`);
113
+ return 0;
114
+ }
115
+ if (sub === 'list' || !sub) { const list = store.list(); if (!list.length) out('No schedules. clarity agent schedule add "0 7 * * 1-5" "what to do"'); for (const e of list) out(`${e.id} ${e.cron.padEnd(14)} ${e.mode.padEnd(5)} next ${e.next ? new Date(e.next).toLocaleString() : 'never'}${e.last ? ` · last ${e.state}` : ''}\n ${e.task}`); return 0; }
116
+ if (sub === 'remove') { if (!store.remove(args[1])) { errOut(`No schedule ${args[1]}.`); return 1; } out(`Removed schedule ${args[1]}.`); return 0; }
117
+ if (sub === 'due') { const done = await serveSchedules({ root, once: true, log: out }); if (!done.length) out('Nothing is due.'); return done.some((d) => d.code === 1) ? 1 : 0; }
118
+ if (sub === 'run') {
119
+ out(`${c.bold}Clarity Agent${c.reset} ${c.dim}schedules of ${root} · Ctrl+C stops${c.reset}`);
120
+ const stop = new AbortController(); process.once('SIGINT', () => { stop.abort(); process.exit(0); });
121
+ await serveSchedules({ root, signal: stop.signal, log: out });
122
+ return 0;
123
+ }
124
+ } catch (e) { errOut(e.message); return 1; }
125
+ errOut('clarity agent schedule add "<cron>" "<task>" [--mode edits|auto] [--allow "npm test"] | list | remove <id> | run | due');
126
+ return 1;
127
+ }
128
+
129
+ // The agent in a team's chat (chat.js).
130
+ async function cmdChat(args) {
131
+ const root = process.cwd(), sub = args[0], file = path.join(root, '.clarity', 'agent.json');
132
+ const read = () => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return {}; } };
133
+ if (sub === 'allow' || sub === 'deny') {
134
+ const platform = args[1], user = args[2];
135
+ if (!CHAT_PLATFORMS.includes(platform) || !user) { errOut(`clarity agent chat ${sub} <${CHAT_PLATFORMS.join('|')}> <user id>`); return 1; }
136
+ const cfg = read(), chat = cfg.chat ?? {}, list = new Set((chat[platform]?.allow ?? []).map(String));
137
+ if (sub === 'allow') list.add(String(user)); else list.delete(String(user));
138
+ cfg.chat = { ...chat, [platform]: { ...(chat[platform] ?? {}), allow: [...list] } };
139
+ fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(cfg, null, 2) + '\n');
140
+ out(`${platform}: ${list.size ? [...list].join(', ') : 'nobody'} may talk to the agent of this project.`);
141
+ return 0;
142
+ }
143
+ const keys = keyStore({ envName: envNameOf }), config = loadConfig({ root }).chat ?? {}, adapters = chatAdapters({ keys, config, log: (l) => out(`${c.dim}${l}${c.reset}`) });
144
+ if (sub === 'discord-register') { if (!adapters.discord || !config.discord?.appId) { errOut('Discord needs its bot token (clarity keys set discord-bot) and, in .clarity/agent.json, "chat": { "discord": { "appId": "…", "publicKey": "…" } }.'); return 1; } try { await adapters.discord.register(); out('Discord knows the command: /clarity task:<what to do>'); return 0; } catch (e) { errOut(e.message); return 1; } }
145
+ if (!Object.keys(adapters).length) { errOut('No chat service has its keys yet. Telegram: clarity keys set telegram-bot · Slack: slack-bot and slack-signing · Discord: discord-bot (and its public key in .clarity/agent.json) · Linear: linear and linear-webhook'); return 1; }
146
+ const allow = Object.fromEntries(CHAT_PLATFORMS.map((p) => [p, config[p]?.allow ?? []]));
147
+ let app;
148
+ try { app = await serveChat({ root, adapters, allow, mode: flag(args, 'mode') ?? 'ask', port: Number(flag(args, 'port', 8787)), host: flag(args, 'host') ?? '127.0.0.1', log: (l) => out(`${c.dim}${l}${c.reset}`) }); }
149
+ catch (e) { errOut(e.message); return 1; }
150
+ out(`${c.bold}Clarity Agent${c.reset} ${c.dim}in chat · ${root}${c.reset}`);
151
+ for (const p of Object.keys(adapters)) out(`${allow[p].length ? c.green + '●' : c.yellow + '○'}${c.reset} ${p.padEnd(9)}${allow[p].length ? `${allow[p].length} may talk to it` : `nobody may talk to it yet: clarity agent chat allow ${p} <user id>`}`);
152
+ if (app.url) {
153
+ out(`${c.dim}Listening on ${app.url} (this computer; a tunnel or a reverse proxy brings the services' requests here). Give each service its address:${c.reset}`);
154
+ if (adapters.slack) out(` Slack Event Subscriptions → <public address>/slack/events · Interactivity → <public address>/slack/actions`);
155
+ if (adapters.discord) out(` Discord Interactions Endpoint URL → <public address>/discord/interactions (then: clarity agent chat discord-register)`);
156
+ if (adapters.linear) out(` Linear Webhooks → <public address>/linear/webhook (Comments)`);
157
+ }
158
+ out(`${c.dim}Ctrl+C stops it.${c.reset}`);
159
+ await new Promise((done) => process.once('SIGINT', done));
160
+ await app.close();
161
+ return 0;
162
+ }
163
+
164
+ async function cmdAgent(args) {
165
+ if (args[0] === 'app') return cmdApp(args.slice(1));
166
+ if (args[0] === 'chat') return cmdChat(args.slice(1));
167
+ if (args[0] === 'ci') return cmdCi(args.slice(1));
168
+ if (args[0] === 'schedule') return cmdSchedule(args.slice(1));
169
+ if (args.includes('--headless') || args.includes('--json')) return cmdHeadless(args);
170
+ const root = process.cwd(), prompt = words(args, ['model', 'mode', 'allow']).join(' ').trim();
171
+ const rl = process.stdin.isTTY ? readline.createInterface({ input: process.stdin, output: process.stdout }) : null;
172
+ const log = logEvents(root);
173
+ const show = (e) => {
174
+ log(e);
175
+ if (e.type === 'text') out(`\n${e.text}\n`);
176
+ else if (e.type === 'tool') out(`${c.dim}· ${e.summary}${c.reset}`);
177
+ else if (e.type === 'result' && e.result.error) out(`${c.dim} ↳ ${String(e.result.text).split('\n')[0].slice(0, 160)}${c.reset}`);
178
+ if (e.type === 'result' && e.checkpoint?.files.length) out(`${c.dim} ± ${e.checkpoint.files.map((f) => `${f.path} ${c.green}+${f.added}${c.dim} ${c.red}−${f.removed}${c.dim}`).join(', ')}${e.checkpoint.id ? ` (checkpoint ${e.checkpoint.id})` : ''}${c.reset}`);
179
+ };
180
+ let agent;
181
+ try { agent = await createAgent({ root, model: flag(args, 'model'), mode: flag(args, 'mode'), allow: flags(args, 'allow'), ask: asker(rl, { yes: args.includes('--yes') }), on: show }); }
182
+ catch (e) { errOut(e.message); rl?.close(); return 1; }
183
+ out(`${c.bold}Clarity Agent${c.reset} ${c.dim}${agent.model} · ${agent.policy.mode} · ${root}${c.reset}`);
184
+ for (const n of agent.mcpNotes ?? []) out(`${c.yellow}MCP ${n}${c.reset}`);
185
+ let ctl = null;
186
+ process.on('SIGINT', () => { if (ctl) { ctl.abort(new Error('Stopped.')); ctl = null; out(`${c.dim}(stopped)${c.reset}`); } else { rl?.close(); process.exit(130); } });
187
+ const once = async (text) => {
188
+ ctl = new AbortController();
189
+ try { const r = await agent.run(text, { signal: ctl.signal }); out(`${c.dim}${r.steps} step${r.steps === 1 ? '' : 's'} · ${r.total.input + r.total.output} tokens this session${c.reset}`); }
190
+ catch (e) { errOut(e.message); }
191
+ finally { ctl = null; }
192
+ };
193
+ if (prompt) { await once(prompt); rl?.close(); await agent.close?.(); return 0; }
194
+ if (!rl) { errOut('Say what to do: clarity agent "…" (there is no terminal to talk in).'); return 1; }
195
+ out(`${c.dim}Say what to build or change. /help for commands, /exit to leave.${c.reset}`);
196
+ for (;;) {
197
+ const line = (await question(rl, `${c.cyan}›${c.reset} `)).trim();
198
+ if (!line) continue;
199
+ if (line === '/exit' || line === '/quit') break;
200
+ if (line === '/help') { out('/changes what each step changed\n/diff <n> a checkpoint\'s diff\n/undo [n] put the files back as before checkpoint n (the last one)\n/cost what was spent today and this month\n/mode ask|edits|auto\n/clear forget the conversation\n/exit'); continue; }
201
+ if (line === '/changes') { const list = agent.checkpoints?.list() ?? []; out(list.length ? list.map((k) => `${k.id} ${k.label} ${k.files.map((f) => `${f.path} +${f.added} −${f.removed}`).join(', ')}`).join('\n') : 'Nothing changed yet.'); continue; }
202
+ if (line.startsWith('/diff')) { const k = agent.checkpoints?.get(Number(line.split(/\s+/)[1])); out(k ? k.files.map((f) => f.diff).join('\n') : 'Which checkpoint? /changes lists them.'); continue; }
203
+ if (line.startsWith('/undo')) {
204
+ const list = agent.checkpoints?.list() ?? [], id = Number(line.split(/\s+/)[1]) || list.at(-1)?.id;
205
+ if (!id) { out('Nothing to undo.'); continue; }
206
+ let r = agent.checkpoints.undo(id);
207
+ if (!r.done && r.conflicts.length && /^(y|yes|e|evet)$/i.test((await question(rl, `${c.yellow}?${c.reset} You changed ${r.conflicts.join(', ')} since. Undo anyway, and lose that? [y/n] `)).trim())) r = agent.checkpoints.undo(id, { force: true });
208
+ if (r.done) { out(`Put back: ${r.restored.join(', ')}`); agent.messages.push({ role: 'user', content: `(I undid your changes to ${r.restored.join(', ')}; read them again before changing them.)` }, { role: 'assistant', content: 'Understood.' }); }
209
+ else out('Not undone.');
210
+ continue;
211
+ }
212
+ if (line === '/cost') { out(`today ${usd(agent.ledger.today())} of ${usd(agent.ledger.limits.daily)} · this month ${usd(agent.ledger.thisMonth())} of ${usd(agent.ledger.limits.monthly)}`); continue; }
213
+ if (line.startsWith('/mode')) { const m = line.split(/\s+/)[1]; if (['ask', 'edits', 'auto'].includes(m)) { agent.policy.mode = m; out(`mode: ${m}`); } else out('mode: ask | edits | auto'); continue; }
214
+ if (line === '/clear') { agent.messages.length = 0; out('(forgotten)'); continue; }
215
+ await once(line);
216
+ }
217
+ rl.close();
218
+ await agent.close?.();
219
+ return 0;
220
+ }
221
+
222
+ async function cmdDream(args) {
223
+ const root = process.cwd(), idea = words(args, ['mode', 'dir', 'model']).join(' ').trim();
224
+ if (!idea) { errOut('Say the idea: clarity dream "a booking app for hairdressers"'); return 1; }
225
+ const yes = args.includes('--yes'), rl = !yes && process.stdin.isTTY ? readline.createInterface({ input: process.stdin, output: process.stdout }) : null;
226
+ let agent;
227
+ try { agent = await createAgent({ root, model: flag(args, 'model') }); } catch (e) { errOut(e.message); rl?.close(); return 1; }
228
+ const STEPS = { listen: 'Reading the idea', ask: 'Questions', originate: 'Three concepts', design: 'The design', style: 'The style guide', assets: 'The assets', write: 'Writing the files' };
229
+ try {
230
+ const r = await agent.dream(idea, {
231
+ mode: flag(args, 'mode'), dir: flag(args, 'dir', '.'),
232
+ on: (s) => out(`${c.dim}· ${STEPS[s]}…${c.reset}`),
233
+ answer: rl ? async (qs) => { const a = {}; for (const q of qs) { out(`\n${c.bold}${q.question}${c.reset}`); (q.options ?? []).forEach((o, i) => out(` ${i + 1}. ${o}`)); const x = (await question(rl, `${c.dim}a number, your own words, or Enter for "you decide": ${c.reset}`)).trim(); a[q.id] = /^\d+$/.test(x) ? q.options?.[Number(x) - 1] ?? x : x || 'you decide'; } return a; } : undefined,
234
+ choose: rl ? async (cs) => { out(''); cs.forEach((x, i) => out(`${c.bold}${i + 1}. ${x.name}${c.reset} — ${x.hook}\n ${c.dim}${x.look}${c.reset}`)); const x = (await question(rl, `${c.dim}which one (1–${cs.length}): ${c.reset}`)).trim(); return Math.max(0, (Number(x) || 1) - 1); } : undefined,
235
+ });
236
+ out(`\n${c.green}${r.design.title ?? r.chosen.name}${c.reset} (${r.mode}) — ${r.files.join(', ')}`);
237
+ out(`${r.assets.length} assets listed. Next: clarity agent "Build the first version from dream.md"`);
238
+ } catch (e) { errOut(e.message); rl?.close(); return 1; }
239
+ rl?.close();
240
+ return 0;
241
+ }
242
+
243
+ async function cmdGen(args) {
244
+ const root = process.cwd(), env = process.env, config = loadConfig({ root }), keys = keyStore({ env, envName: envNameOf });
245
+ const gen = generator({ root, keys, ledger: ledger({ env, limits: config.limits }), config: config.connectors, onProgress: () => process.stdout.write('.') });
246
+ if (args.includes('--list') || !args.length) {
247
+ for (const a of gen.available()) out(`${a.ready ? c.green + '●' : c.dim + '○'}${c.reset} ${a.id.padEnd(16)} ${a.kinds.join(', ').padEnd(44)} ${c.dim}${a.local ? 'this computer' : a.ready ? 'key set' : 'clarity keys set ' + a.id}${c.reset}`);
248
+ return 0;
249
+ }
250
+ const [kind, ...rest] = words(args, ['via', 'model', 'out', 'aspect', 'seconds', 'voice', 'negative']), prompt = rest.join(' ');
251
+ const req = { kind, prompt, via: flag(args, 'via'), model: flag(args, 'model'), out: flag(args, 'out'), aspect: flag(args, 'aspect'), seconds: flag(args, 'seconds') ? Number(flag(args, 'seconds')) : undefined, voice: flag(args, 'voice'), negative: flag(args, 'negative') };
252
+ try {
253
+ const q = gen.quote(req);
254
+ if (q.refuse) { errOut(q.refuse); return 1; }
255
+ if (!args.includes('--yes') && q.usd !== 0) {
256
+ if (!process.stdin.isTTY) { errOut(`This costs money (${q.usd != null ? 'about ' + usd(q.usd) : 'priced by ' + q.name}). Run again with --yes.`); return 1; }
257
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
258
+ const ok = await asker(rl)({ summary: `make ${kind} with ${q.name}`, risk: 'spend', usd: q.usd, note: q.note }); rl.close();
259
+ if (!ok) return 1;
260
+ }
261
+ const r = await gen.make(req);
262
+ out(`\n${c.green}${r.cached ? 'From the cache' : 'Made'}${c.reset}: ${r.files.join(', ')}${r.usd != null ? ` (${usd(r.usd)})` : ''}`);
263
+ return 0;
264
+ } catch (e) { errOut(e.message); return 1; }
265
+ }
266
+
267
+ async function cmdKeys(args) {
268
+ const env = process.env, keys = keyStore({ env, envName: envNameOf }), [sub = 'list', id, value] = words(args, ['daily', 'monthly']);
269
+ const ids = [...new Set([...Object.keys(PROVIDERS).filter((k) => !PROVIDERS[k].local), ...ADAPTERS.filter((a) => !a.local).map((a) => a.id), ...Object.keys(TARGETS).filter((k) => TARGETS[k].keyEnv), ...Object.keys(CHAT_KEYS)])];
270
+ if (sub === 'list') { for (const k of keys.list(ids)) out(`${k.set ? c.green + '●' : c.dim + '○'}${c.reset} ${k.id.padEnd(16)} ${k.set ? `${k.masked} ${c.dim}${k.where}${c.reset}` : `${c.dim}${envNameOf(k.id) ? '$' + [envNameOf(k.id)].flat()[0] + ' or ' : ''}clarity keys set ${k.id}${c.reset}`}`); return 0; }
271
+ if (sub === 'set') {
272
+ if (!id || !ids.includes(id)) { errOut(`Which one? ${ids.join(', ')}`); return 1; }
273
+ let v = value;
274
+ if (!v) { if (!process.stdin.isTTY) { errOut('Give the key after the name, or run this in a terminal.'); return 1; } const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl._writeToOutput = (s) => { if (s.includes('key for')) process.stdout.write(s); }; v = (await question(rl, `The key for ${id}${ADAPTERS.find((a) => a.id === id)?.keyHint ? ` (${ADAPTERS.find((a) => a.id === id).keyHint})` : ''}: `)).trim(); rl.close(); out(''); }
275
+ const where = keys.set(id, v); out(`Saved the key for ${id} (${mask(v)}) in ${where}.`); return 0;
276
+ }
277
+ if (sub === 'remove') { keys.remove(id); out(`Removed the key for ${id}.`); return 0; }
278
+ if (sub === 'limits') {
279
+ const cfg = loadConfig({ env }), lim = { ...cfg.limits };
280
+ if (flag(args, 'daily')) lim.daily = Number(flag(args, 'daily'));
281
+ if (flag(args, 'monthly')) lim.monthly = Number(flag(args, 'monthly'));
282
+ if (flag(args, 'daily') || flag(args, 'monthly')) saveUserConfig({ limits: lim });
283
+ const book = ledger({ env, limits: lim });
284
+ out(`Limits: ${usd(book.limits.daily)} a day, ${usd(book.limits.monthly)} a month. Spent: ${usd(book.today())} today, ${usd(book.thisMonth())} this month.`);
285
+ return 0;
286
+ }
287
+ errOut('clarity keys list | set <id> [key] | remove <id> | limits [--daily n] [--monthly n]'); return 1;
288
+ }
289
+
290
+ async function cmdModels(args) {
291
+ const [spec] = words(args); if (!spec) { out(Object.entries(PROVIDERS).map(([k, p]) => `${k.padEnd(10)} ${p.name}${p.local ? '' : ` ${c.dim}$${p.keyEnv}${c.reset}`}`).join('\n')); return 0; }
292
+ const { id } = parseModel(spec), keys = keyStore({ envName: envNameOf });
293
+ if (PROVIDERS[parseModel(id).id]?.noModelList) { out(`${PROVIDERS[parseModel(id).id].name} has no model list on this address: see its model cards.`); return 0; }
294
+ try { const list = await provider(id, { key: providerKey(parseModel(id).id, keys), ...(loadConfig({ root: process.cwd() }).providers?.[parseModel(id).id] ?? {}) }).models(); out(list.sort().join('\n') || '(none)'); return 0; } catch (e) { errOut(e.message); return 1; }
295
+ }
296
+
297
+ async function cmdShip(args) {
298
+ const root = process.cwd(), env = process.env, config = loadConfig({ root }), keys = keyStore({ env, envName: envNameOf });
299
+ const [target] = words(args, ['dir', 'site', 'project', 'domain', 'game', 'channel', 'branch', 'host', 'path', 'app', 'user', 'vdf', 'aab', 'package', 'jsonKey', 'ipa', 'apiKey', 'issuer', 'appId', 'apk', 'service', 'remote', 'track', 'platform']);
300
+ if (!target) { for (const [k, t] of Object.entries(TARGETS)) out(`${k.padEnd(14)} ${t.name}${t.keyEnv ? ` ${c.dim}${keys.get(k) || env[t.keyEnv] ? 'key set' : `$${t.keyEnv} or clarity keys set ${k}`}${c.reset}` : ` ${c.dim}${t.note ?? ''}${c.reset}`}`); return 0; }
301
+ const s = shipper({ root, keys, config: config.ship, env });
302
+ const a = { target, dir: flag(args, 'dir') };
303
+ for (const k of ['site', 'project', 'domain', 'game', 'channel', 'branch', 'host', 'path', 'app', 'user', 'vdf', 'aab', 'package', 'jsonKey', 'ipa', 'apiKey', 'issuer', 'appId', 'apk', 'service', 'remote', 'track', 'platform']) a[k] = flag(args, k);
304
+ for (const k of Object.keys(a)) if (a[k] === undefined) delete a[k];
305
+ try {
306
+ const p = s.plan(a);
307
+ out(`${c.bold}${p.name}${c.reset}: ${p.command}${p.note ? ` ${c.dim}(${p.note})${c.reset}` : ''}`);
308
+ if (p.missing.length) { errOut(`Missing: ${p.missing.join('; ')}`); return 1; }
309
+ if (!p.keySet) out(`${c.yellow}No key for ${p.name}: its tool may ask you to sign in. (clarity keys set ${target})${c.reset}`);
310
+ if (args.includes('--dry')) return 0;
311
+ if (!args.includes('--yes')) {
312
+ if (!process.stdin.isTTY) { errOut('Publishing is asked first. Run again with --yes.'); return 1; }
313
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
314
+ const ok = /^y/i.test((await question(rl, `Publish ${p.dir} to ${p.name}? [y/N] `)).trim()); rl.close();
315
+ if (!ok) return 1;
316
+ }
317
+ const r = await s.ship(a, { onOutput: (t) => process.stdout.write(`${c.dim}${t}${c.reset}`) });
318
+ out(r.ok ? `\n${c.green}Published${c.reset}${r.url ? `: ${r.url}` : ''}` : `\n${c.red}${p.name} stopped with code ${r.code}.${c.reset}`);
319
+ return r.ok ? 0 : 1;
320
+ } catch (e) { errOut(e.message); return 1; }
321
+ }
322
+
323
+ /** The entry: argv after the program name. → exit code */
324
+ export async function main(argv = process.argv.slice(2)) {
325
+ const [cmd, ...args] = argv;
326
+ if (!cmd || cmd === 'help' || cmd === '--help' || cmd === '-h') { out(USAGE); return 0; }
327
+ if (cmd === '--version' || cmd === 'version') { out(VERSION); return 0; }
328
+ if (cmd === 'agent') return cmdAgent(args);
329
+ if (cmd === 'dream') return cmdDream(args);
330
+ if (cmd === 'gen') return cmdGen(args);
331
+ if (cmd === 'keys') return cmdKeys(args);
332
+ if (cmd === 'models') return cmdModels(args);
333
+ if (cmd === 'ship') return cmdShip(args);
334
+ return cmdAgent(argv); // clarity-agent "do this"
335
+ }
336
+
337
+ const self = fileURLToPath(import.meta.url);
338
+ let direct = false; try { direct = !!process.argv[1] && fs.realpathSync(process.argv[1]) === self; } catch { /* not a file */ }
339
+ if (direct) main().then((code) => process.exit(code ?? 0));
340
+ void chooseModel;