@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.
@@ -0,0 +1,200 @@
1
+ // @clarity-js/agent — the models, from the user's own keys (BYOK). Three ways of talking cover them all:
2
+ // Anthropic's Messages API, Google's Gemini API, and the OpenAI-compatible chat API that most others
3
+ // speak (DeepSeek, Kimi, MiniMax, Qwen, GLM, Mistral, xAI, Groq, Together, Fireworks, Cerebras, DeepInfra,
4
+ // NVIDIA, Meta's Model API, Ollama's cloud, and local servers: Ollama, LM Studio, vLLM, llama.cpp, MLX, Jan).
5
+ // One shape goes in and comes out:
6
+ //
7
+ // const p = provider('deepseek', { key })
8
+ // const r = await p.chat({ model, system, messages, tools })
9
+ // r.text, r.toolCalls [{ id, name, args }], r.usage { input, output }
10
+ //
11
+ // messages: { role: 'user' | 'assistant', content, toolCalls? } and { role: 'tool', toolCallId, name, content }.
12
+ // No dependencies: fetch, as in Node 18 and every browser.
13
+
14
+ /** The providers a key can be given for, and where each listens. `kind` is the way it is spoken to. */
15
+ export const PROVIDERS = {
16
+ anthropic: { name: 'Anthropic', kind: 'anthropic', baseUrl: 'https://api.anthropic.com', keyEnv: 'ANTHROPIC_API_KEY', model: 'claude-sonnet-5-5' },
17
+ openai: { name: 'OpenAI', kind: 'openai', baseUrl: 'https://api.openai.com/v1', keyEnv: 'OPENAI_API_KEY' },
18
+ gemini: { name: 'Google Gemini', kind: 'gemini', baseUrl: 'https://generativelanguage.googleapis.com/v1beta', keyEnv: 'GEMINI_API_KEY' },
19
+ deepseek: { name: 'DeepSeek', kind: 'openai', baseUrl: 'https://api.deepseek.com', keyEnv: 'DEEPSEEK_API_KEY' },
20
+ moonshot: { name: 'Kimi (Moonshot)', kind: 'openai', baseUrl: 'https://api.moonshot.ai/v1', keyEnv: 'MOONSHOT_API_KEY', aliases: ['kimi'] },
21
+ minimax: { name: 'MiniMax', kind: 'openai', baseUrl: 'https://api.minimax.io/v1', keyEnv: 'MINIMAX_API_KEY' },
22
+ qwen: { name: 'Qwen (Alibaba Cloud)', kind: 'openai', baseUrl: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1', keyEnv: 'DASHSCOPE_API_KEY', aliases: ['dashscope'] },
23
+ zhipu: { name: 'GLM (Z.ai)', kind: 'openai', baseUrl: 'https://api.z.ai/api/paas/v4', keyEnv: 'ZAI_API_KEY', aliases: ['glm', 'zai'] },
24
+ mistral: { name: 'Mistral', kind: 'openai', baseUrl: 'https://api.mistral.ai/v1', keyEnv: 'MISTRAL_API_KEY' },
25
+ xai: { name: 'xAI', kind: 'openai', baseUrl: 'https://api.x.ai/v1', keyEnv: 'XAI_API_KEY', aliases: ['grok'] },
26
+ meta: { name: 'Meta Model API (Muse)', kind: 'openai', baseUrl: 'https://api.meta.ai/v1', keyEnv: 'META_API_KEY', aliases: ['llama', 'muse'] },
27
+ groq: { name: 'Groq', kind: 'openai', baseUrl: 'https://api.groq.com/openai/v1', keyEnv: 'GROQ_API_KEY' },
28
+ together: { name: 'Together AI', kind: 'openai', baseUrl: 'https://api.together.ai/v1', keyEnv: 'TOGETHER_API_KEY' },
29
+ fireworks: { name: 'Fireworks AI', kind: 'openai', baseUrl: 'https://api.fireworks.ai/inference/v1', keyEnv: 'FIREWORKS_API_KEY' },
30
+ cerebras: { name: 'Cerebras', kind: 'openai', baseUrl: 'https://api.cerebras.ai/v1', keyEnv: 'CEREBRAS_API_KEY' },
31
+ deepinfra: { name: 'DeepInfra', kind: 'openai', baseUrl: 'https://api.deepinfra.com/v1/openai', keyEnv: 'DEEPINFRA_API_KEY' },
32
+ nvidia: { name: 'NVIDIA (build.nvidia.com)', kind: 'openai', baseUrl: 'https://integrate.api.nvidia.com/v1', keyEnv: 'NVIDIA_API_KEY', aliases: ['nim'] },
33
+ 'ollama-cloud': { name: 'Ollama Cloud', kind: 'openai', baseUrl: 'https://ollama.com/v1', keyEnv: 'OLLAMA_API_KEY' },
34
+ cohere: { name: 'Cohere', kind: 'openai', baseUrl: 'https://api.cohere.ai/compatibility/v1', keyEnv: 'COHERE_API_KEY' },
35
+ byteplus: { name: 'BytePlus ModelArk (Seed)', kind: 'openai', baseUrl: 'https://ark.{region}.bytepluses.com/api/v3', vars: { region: { env: 'ARK_REGION', default: 'ap-southeast' } }, keyEnv: 'ARK_API_KEY', aliases: ['ark', 'modelark', 'seed'] },
36
+ // the clouds: the address names your account, so it is filled from the environment or .clarity/agent.json
37
+ azure: { name: 'Azure OpenAI (Foundry)', kind: 'openai', baseUrl: 'https://{resource}.openai.azure.com/openai/v1', vars: { resource: { env: 'AZURE_OPENAI_RESOURCE' } }, keyEnv: 'AZURE_OPENAI_API_KEY', note: 'the model is your deployment\'s name' },
38
+ bedrock: { name: 'Amazon Bedrock', kind: 'openai', baseUrl: 'https://bedrock-runtime.{region}.amazonaws.com/openai/v1', vars: { region: { env: 'AWS_REGION', default: 'us-east-1' } }, keyEnv: 'AWS_BEARER_TOKEN_BEDROCK', aliases: ['aws'], noModelList: true },
39
+ vertex: { name: 'Google Vertex AI', kind: 'openai', baseUrl: 'https://aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/openapi', vars: { project: { env: 'GOOGLE_CLOUD_PROJECT' }, location: { env: 'GOOGLE_CLOUD_LOCATION', default: 'global' } }, keyEnv: 'VERTEX_ACCESS_TOKEN', keyCommand: ['gcloud', 'auth', 'print-access-token'], model: 'google/gemini-3.5-flash', aliases: ['vertex-ai', 'gcp'] },
40
+ ollama: { name: 'Ollama (this computer)', kind: 'openai', baseUrl: 'http://127.0.0.1:11434/v1', local: true },
41
+ lmstudio: { name: 'LM Studio (this computer)', kind: 'openai', baseUrl: 'http://127.0.0.1:1234/v1', local: true },
42
+ vllm: { name: 'vLLM (this computer)', kind: 'openai', baseUrl: 'http://127.0.0.1:8000/v1', local: true },
43
+ // llama-server's README gives 9931 as its port now; older builds used 8080 (set providers.llamacpp.baseUrl)
44
+ llamacpp: { name: 'llama.cpp server (this computer)', kind: 'openai', baseUrl: 'http://127.0.0.1:9931/v1', local: true, aliases: ['llama.cpp'] },
45
+ mlx: { name: 'MLX (mlx_lm.server, this Mac)', kind: 'openai', baseUrl: 'http://127.0.0.1:8080/v1', local: true, aliases: ['mlx-lm'] },
46
+ jan: { name: 'Jan (this computer)', kind: 'openai', baseUrl: 'http://127.0.0.1:1337/v1', local: true },
47
+ };
48
+
49
+ /** 'deepseek' | 'kimi' | 'anthropic:claude-sonnet-5-5' → { id, model }. A model may itself hold colons (ollama's 'qwen3:32b'). */
50
+ export function parseModel(spec = '') {
51
+ const s = String(spec).trim(), i = s.indexOf(':');
52
+ const head = (i < 0 ? s : s.slice(0, i)).toLowerCase(), rest = i < 0 ? '' : s.slice(i + 1);
53
+ if (head === 'custom') return { id: 'custom', model: rest || null };
54
+ const id = PROVIDERS[head] ? head : Object.keys(PROVIDERS).find((k) => PROVIDERS[k].aliases?.includes(head));
55
+ if (!id) throw new Error(`Unknown provider "${head}". Known: ${Object.keys(PROVIDERS).join(', ')}, or custom (with providers.custom.baseUrl in .clarity/agent.json) for any OpenAI-compatible server.`);
56
+ return { id, model: rest || PROVIDERS[id].model || null };
57
+ }
58
+
59
+ export class ProviderError extends Error {
60
+ constructor(message, { status, provider, body } = {}) { super(message); this.name = 'ProviderError'; this.status = status; this.provider = provider; this.body = body; }
61
+ }
62
+
63
+ const trimSlash = (u) => String(u).replace(/\/+$/, '');
64
+ async function post(url, headers, body, { fetchImpl = globalThis.fetch, signal, provider, timeout = 300000 } = {}) {
65
+ const ctl = new AbortController(), t = setTimeout(() => ctl.abort(new Error('timed out')), timeout);
66
+ const stop = () => ctl.abort(signal.reason); signal?.addEventListener?.('abort', stop, { once: true });
67
+ try {
68
+ const res = await fetchImpl(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body), signal: ctl.signal });
69
+ const text = await res.text();
70
+ let json = null; try { json = text ? JSON.parse(text) : null; } catch { /* not JSON */ }
71
+ if (!res.ok) throw new ProviderError(`${provider}: ${res.status} ${json?.error?.message ?? json?.message ?? text.slice(0, 300)}`, { status: res.status, provider, body: json ?? text });
72
+ return json;
73
+ } catch (e) {
74
+ if (e instanceof ProviderError) throw e;
75
+ throw new ProviderError(`${provider}: ${e?.cause?.code === 'ECONNREFUSED' ? 'nothing is listening at ' + url.replace(/\/[^/]*$/, '') + ' (is the server running?)' : e.message}`, { provider });
76
+ } finally { clearTimeout(t); signal?.removeEventListener?.('abort', stop); }
77
+ }
78
+ async function get(url, headers, { fetchImpl = globalThis.fetch, provider } = {}) {
79
+ const res = await fetchImpl(url, { headers });
80
+ const json = await res.json().catch(() => null);
81
+ if (!res.ok) throw new ProviderError(`${provider}: ${res.status} ${json?.error?.message ?? ''}`, { status: res.status, provider, body: json });
82
+ return json;
83
+ }
84
+ const parseArgs = (s) => { if (s && typeof s === 'object') return s; try { return JSON.parse(s || '{}'); } catch { return { _raw: String(s) }; } };
85
+ const asText = (c) => (typeof c === 'string' ? c : JSON.stringify(c));
86
+
87
+ // ── Anthropic ────────────────────────────────────────────────────────────────────────────────
88
+ function anthropicMessages(messages) {
89
+ const out = [];
90
+ const push = (role, block) => { const last = out.at(-1); if (last && last.role === role) last.content.push(block); else out.push({ role, content: [block] }); };
91
+ for (const m of messages) {
92
+ if (m.role === 'tool') push('user', { type: 'tool_result', tool_use_id: m.toolCallId, content: asText(m.content), ...(m.isError ? { is_error: true } : {}) });
93
+ else if (m.role === 'assistant') {
94
+ if (m.content) push('assistant', { type: 'text', text: asText(m.content) });
95
+ for (const c of m.toolCalls ?? []) push('assistant', { type: 'tool_use', id: c.id, name: c.name, input: c.args ?? {} });
96
+ } else push('user', { type: 'text', text: asText(m.content) });
97
+ }
98
+ return out;
99
+ }
100
+ const anthropic = (cfg, opt) => ({
101
+ async chat({ model, system, messages, tools = [], maxTokens = 8192, temperature, signal }) {
102
+ const body = { model, max_tokens: maxTokens, messages: anthropicMessages(messages), ...(system ? { system } : {}), ...(tools.length ? { tools: tools.map((t) => ({ name: t.name, description: t.description, input_schema: t.inputSchema })) } : {}), ...(temperature != null ? { temperature } : {}) };
103
+ const r = await post(`${trimSlash(cfg.baseUrl)}/v1/messages`, { 'x-api-key': opt.key ?? '', 'anthropic-version': '2023-06-01' }, body, { ...opt, signal, provider: cfg.name });
104
+ const blocks = r?.content ?? [];
105
+ return { text: blocks.filter((b) => b.type === 'text').map((b) => b.text).join(''), toolCalls: blocks.filter((b) => b.type === 'tool_use').map((b) => ({ id: b.id, name: b.name, args: b.input ?? {} })), usage: { input: r?.usage?.input_tokens ?? 0, output: r?.usage?.output_tokens ?? 0 }, stop: r?.stop_reason ?? null, raw: r };
106
+ },
107
+ async models() { const r = await get(`${trimSlash(cfg.baseUrl)}/v1/models`, { 'x-api-key': opt.key ?? '', 'anthropic-version': '2023-06-01' }, { ...opt, provider: cfg.name }); return (r?.data ?? []).map((m) => m.id); },
108
+ });
109
+
110
+ // ── OpenAI-compatible ────────────────────────────────────────────────────────────────────────
111
+ function openaiMessages(system, messages) {
112
+ const out = system ? [{ role: 'system', content: system }] : [];
113
+ for (const m of messages) {
114
+ if (m.role === 'tool') out.push({ role: 'tool', tool_call_id: m.toolCallId, content: asText(m.content) });
115
+ // a reasoning model's thinking goes back with its tool calls (DeepSeek and MiniMax ask for it)
116
+ else if (m.role === 'assistant') out.push({ role: 'assistant', content: m.content ? asText(m.content) : null, ...(m.reasoning ? { reasoning_content: m.reasoning } : {}), ...(m.toolCalls?.length ? { tool_calls: m.toolCalls.map((c) => ({ id: c.id, type: 'function', function: { name: c.name, arguments: JSON.stringify(c.args ?? {}) } })) } : {}) });
117
+ else out.push({ role: 'user', content: asText(m.content) });
118
+ }
119
+ return out;
120
+ }
121
+ // a model that cannot call tools natively (some local ones) is told to write a call in a fenced block
122
+ const TEXT_TOOLS = (tools) => `\n\nYou can use these tools. To use one, answer with only a fenced block:\n\`\`\`tool\n{"name": "<tool>", "args": { ... }}\n\`\`\`\nYou will get its result, then continue. Tools:\n${tools.map((t) => `- ${t.name}: ${t.description} Arguments (JSON Schema): ${JSON.stringify(t.inputSchema)}`).join('\n')}`;
123
+ export function readTextToolCalls(text) {
124
+ const calls = [];
125
+ for (const m of String(text ?? '').matchAll(/```tool\s*\n([\s\S]*?)```/g)) { try { const j = JSON.parse(m[1]); if (j?.name) calls.push({ id: `t${calls.length + 1}_${Date.now().toString(36)}`, name: j.name, args: j.args ?? j.arguments ?? {} }); } catch { /* not a call */ } }
126
+ return calls;
127
+ }
128
+ const openai = (cfg, opt) => ({
129
+ async chat({ model, system, messages, tools = [], maxTokens = 8192, temperature, signal, json = false }) {
130
+ const textTools = tools.length && (opt.toolMode ?? cfg.toolMode) === 'text';
131
+ // in text mode the earlier calls and results go back as words
132
+ const msgs = textTools ? messages.map((m) => (m.role === 'tool' ? { role: 'user', content: `Result of ${m.name}:\n${asText(m.content)}` } : m.role === 'assistant' && m.toolCalls?.length ? { role: 'assistant', content: (m.content ?? '') + m.toolCalls.map((c) => `\n\`\`\`tool\n${JSON.stringify({ name: c.name, args: c.args })}\n\`\`\``).join('') } : m)) : messages;
133
+ const body = { model, messages: openaiMessages(system ? system + (textTools ? TEXT_TOOLS(tools) : '') : textTools ? TEXT_TOOLS(tools) : null, msgs), max_tokens: maxTokens, ...(tools.length && !textTools ? { tools: tools.map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.inputSchema } })) } : {}), ...(temperature != null ? { temperature } : {}), ...(json ? { response_format: { type: 'json_object' } } : {}) };
134
+ const r = await post(`${trimSlash(opt.baseUrl ?? cfg.baseUrl)}/chat/completions`, opt.key ? { authorization: `Bearer ${opt.key}` } : {}, body, { ...opt, signal, provider: cfg.name });
135
+ const msg = r?.choices?.[0]?.message ?? {};
136
+ // some reasoning models put their thinking beside the answer; it is not the answer
137
+ const text = typeof msg.content === 'string' ? msg.content.replace(/<think>[\s\S]*?<\/think>\s*/g, '') : Array.isArray(msg.content) ? msg.content.map((p) => p.text ?? '').join('') : '';
138
+ const toolCalls = textTools ? readTextToolCalls(text) : (msg.tool_calls ?? []).map((c) => ({ id: c.id, name: c.function?.name, args: parseArgs(c.function?.arguments) }));
139
+ const reasoning = typeof msg.reasoning_content === 'string' && msg.reasoning_content ? msg.reasoning_content : null;
140
+ return { text: textTools ? text.replace(/```tool\s*\n[\s\S]*?```/g, '').trim() : text, toolCalls, ...(reasoning ? { reasoning } : {}), usage: { input: r?.usage?.prompt_tokens ?? 0, output: r?.usage?.completion_tokens ?? 0 }, stop: r?.choices?.[0]?.finish_reason ?? null, raw: r };
141
+ },
142
+ async models() { const r = await get(`${trimSlash(opt.baseUrl ?? cfg.baseUrl)}/models`, opt.key ? { authorization: `Bearer ${opt.key}` } : {}, { ...opt, provider: cfg.name }); return (r?.data ?? r?.models ?? []).map((m) => m.id ?? m.name); },
143
+ });
144
+
145
+ // ── Gemini ───────────────────────────────────────────────────────────────────────────────────
146
+ // its schemas are a subset of JSON Schema: no additionalProperties, $schema, default
147
+ export function geminiSchema(s) {
148
+ if (Array.isArray(s)) return s.map(geminiSchema);
149
+ if (!s || typeof s !== 'object') return s;
150
+ const out = {};
151
+ for (const [k, v] of Object.entries(s)) if (!['additionalProperties', '$schema', 'default', 'examples', '$id'].includes(k)) out[k] = typeof v === 'object' ? geminiSchema(v) : v;
152
+ return out;
153
+ }
154
+ function geminiContents(messages) {
155
+ const out = [];
156
+ const push = (role, part) => { const last = out.at(-1); if (last && last.role === role) last.parts.push(part); else out.push({ role, parts: [part] }); };
157
+ for (const m of messages) {
158
+ if (m.role === 'tool') push('user', { functionResponse: { name: m.name, response: { content: m.content } } });
159
+ else if (m.role === 'assistant') { if (m.content) push('model', { text: asText(m.content) }); for (const c of m.toolCalls ?? []) push('model', { functionCall: { name: c.name, args: c.args ?? {} } }); }
160
+ else push('user', { text: asText(m.content) });
161
+ }
162
+ return out;
163
+ }
164
+ const gemini = (cfg, opt) => ({
165
+ async chat({ model, system, messages, tools = [], maxTokens = 8192, temperature, signal, json = false }) {
166
+ const body = { contents: geminiContents(messages), ...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}), ...(tools.length ? { tools: [{ functionDeclarations: tools.map((t) => ({ name: t.name, description: t.description, parameters: geminiSchema(t.inputSchema) })) }] } : {}), generationConfig: { maxOutputTokens: maxTokens, ...(temperature != null ? { temperature } : {}), ...(json ? { responseMimeType: 'application/json' } : {}) } };
167
+ const r = await post(`${trimSlash(cfg.baseUrl)}/models/${encodeURIComponent(model)}:generateContent`, { 'x-goog-api-key': opt.key ?? '' }, body, { ...opt, signal, provider: cfg.name });
168
+ const parts = r?.candidates?.[0]?.content?.parts ?? [];
169
+ return { text: parts.filter((p) => typeof p.text === 'string' && !p.thought).map((p) => p.text).join(''), toolCalls: parts.filter((p) => p.functionCall).map((p, i) => ({ id: `g${i}_${Date.now().toString(36)}`, name: p.functionCall.name, args: p.functionCall.args ?? {} })), usage: { input: r?.usageMetadata?.promptTokenCount ?? 0, output: r?.usageMetadata?.candidatesTokenCount ?? 0 }, stop: r?.candidates?.[0]?.finishReason ?? null, raw: r };
170
+ },
171
+ async models() { const r = await get(`${trimSlash(cfg.baseUrl)}/models`, { 'x-goog-api-key': opt.key ?? '' }, { ...opt, provider: cfg.name }); return (r?.models ?? []).map((m) => String(m.name).replace(/^models\//, '')); },
172
+ });
173
+
174
+ const KINDS = { anthropic, openai, gemini };
175
+ /**
176
+ * A provider to talk to: by id ('deepseek', 'kimi', 'ollama' …) or `custom` with a baseUrl (any OpenAI-compatible
177
+ * server). Options: key, baseUrl (to point a known one elsewhere), toolMode ('native' | 'text'), fetchImpl, timeout.
178
+ */
179
+ /** A preset's address with its {placeholders} filled: from options, then the environment, then the default. */
180
+ export function fillUrl(cfg, opt = {}, env = opt.env ?? process.env) {
181
+ return String(cfg.baseUrl).replace(/\{(\w+)\}/g, (_, name) => {
182
+ const v = cfg.vars?.[name], got = opt[name] ?? (v?.env ? env[v.env] : undefined) ?? v?.default;
183
+ if (got === undefined || got === '') throw new Error(`${cfg.name} needs its ${name}: set ${v?.env ?? name} or "providers": { "…": { "${name}": "…" } } in .clarity/agent.json.`);
184
+ return encodeURIComponent(got);
185
+ });
186
+ }
187
+
188
+ export function provider(id, opt = {}) {
189
+ const key = String(id).toLowerCase();
190
+ if (key === 'custom' || key.startsWith('http')) {
191
+ const baseUrl = key.startsWith('http') ? id : opt.baseUrl;
192
+ if (!baseUrl) throw new Error('A custom provider needs its baseUrl (an OpenAI-compatible server).');
193
+ return { id: 'custom', ...KINDS.openai({ name: baseUrl, kind: 'openai', baseUrl }, { ...opt, baseUrl }), config: { name: baseUrl, kind: 'openai', baseUrl } };
194
+ }
195
+ const { id: pid } = parseModel(key);
196
+ if (pid === 'custom') return provider(opt.baseUrl ?? 'custom', opt);
197
+ const cfg = { ...PROVIDERS[pid], ...(opt.baseUrl ? { baseUrl: opt.baseUrl } : {}) };
198
+ cfg.baseUrl = fillUrl(cfg, opt);
199
+ return { id: pid, ...KINDS[cfg.kind](cfg, opt), config: cfg };
200
+ }
@@ -0,0 +1,113 @@
1
+ // @clarity-js/agent — tasks at set times. A schedule is a line of cron (minute hour day-of-month month
2
+ // day-of-week, in this computer's time) and a task; it is kept in the project (.clarity/agent/schedule.json).
3
+ //
4
+ // clarity agent schedule add "0 7 * * 1-5" "Update the dependencies and run the tests" --mode auto --allow "npm test"
5
+ // clarity agent schedule list | remove <id>
6
+ // clarity agent schedule run stay, and do each when its time comes (one at a time)
7
+ // clarity agent schedule due do what has come due since it last ran, and leave (for cron, or a CI schedule)
8
+ //
9
+ // A scheduled run has nobody to ask: it is a headless run (headless.js). What would have been asked is refused.
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { runHeadless } from './headless.js';
14
+
15
+ const NAMES = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12, sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 };
16
+ const SHORT = { '@hourly': '0 * * * *', '@daily': '0 0 * * *', '@midnight': '0 0 * * *', '@weekly': '0 0 * * 0', '@monthly': '0 0 1 * *', '@yearly': '0 0 1 1 *', '@annually': '0 0 1 1 *' };
17
+ const FIELDS = [['minute', 0, 59], ['hour', 0, 23], ['day of the month', 1, 31], ['month', 1, 12], ['day of the week', 0, 7]];
18
+
19
+ /** A line of cron → what it allows: { minute, hour, day, month, weekday: Set, anyDay, anyWeekday }. Throws with the field that is wrong. */
20
+ export function parseCron(expr) {
21
+ const text = SHORT[String(expr).trim().toLowerCase()] ?? String(expr).trim(), parts = text.split(/\s+/);
22
+ if (parts.length !== 5) throw new Error(`A schedule has five fields (minute hour day-of-month month day-of-week), "${expr}" has ${parts.length}.`);
23
+ const sets = parts.map((field, i) => {
24
+ const [name, lo, hi] = FIELDS[i], out = new Set();
25
+ const num = (v) => { const n = /^\d+$/.test(v) ? Number(v) : NAMES[v.toLowerCase()]; if (n === undefined || n < lo || n > hi) throw new Error(`"${v}" is not a ${name} (${lo}–${hi}) in "${expr}".`); return n; };
26
+ for (const piece of field.split(',')) {
27
+ const [range, stepText] = piece.split('/'), step = stepText === undefined ? 1 : Number(stepText);
28
+ if (!Number.isInteger(step) || step < 1) throw new Error(`"${piece}" has no step a ${name} can go by in "${expr}".`);
29
+ let from, to;
30
+ if (range === '*') { from = lo; to = i === 4 ? 6 : hi; }
31
+ else if (range.includes('-')) { const [a, b] = range.split('-'); from = num(a); to = num(b); if (to < from) throw new Error(`"${range}" runs backwards in "${expr}".`); }
32
+ else { from = num(range); to = stepText === undefined ? from : (i === 4 ? 6 : hi); }
33
+ for (let v = from; v <= to; v += step) out.add(i === 4 && v === 7 ? 0 : v);
34
+ }
35
+ return out;
36
+ });
37
+ return { minute: sets[0], hour: sets[1], day: sets[2], month: sets[3], weekday: sets[4], anyDay: parts[2] === '*', anyWeekday: parts[4] === '*' };
38
+ }
39
+
40
+ /** The first time after `from` (a Date) that a schedule allows, in this computer's time (utc: true, in UTC). null: never within four years. */
41
+ export function nextRun(expr, from = new Date(), { utc = false } = {}) {
42
+ const c = typeof expr === 'string' ? parseCron(expr) : expr, g = utc ? 'getUTC' : 'get', s = utc ? 'setUTC' : 'set';
43
+ const t = new Date(from.getTime()); t[s + 'Seconds'](0, 0); t[s + 'Minutes'](t[g + 'Minutes']() + 1);
44
+ // a day is allowed by its date or by its weekday when both are named (as cron has it), by the one that is named otherwise
45
+ const dayOk = () => { const d = c.day.has(t[g + 'Date']()), w = c.weekday.has(t[g + 'Day']()); return c.anyDay && c.anyWeekday ? true : c.anyDay ? w : c.anyWeekday ? d : d || w; };
46
+ for (let guard = 0; guard < 200000; guard++) {
47
+ if (t.getTime() - from.getTime() > 4 * 366 * 86400000) return null;
48
+ if (!c.month.has(t[g + 'Month']() + 1)) { t[s + 'Month'](t[g + 'Month']() + 1, 1); t[s + 'Hours'](0, 0, 0, 0); continue; }
49
+ if (!dayOk()) { t[s + 'Date'](t[g + 'Date']() + 1); t[s + 'Hours'](0, 0, 0, 0); continue; }
50
+ if (!c.hour.has(t[g + 'Hours']())) { t[s + 'Hours'](t[g + 'Hours']() + 1, 0, 0, 0); continue; }
51
+ if (!c.minute.has(t[g + 'Minutes']())) { t[s + 'Minutes'](t[g + 'Minutes']() + 1, 0, 0); continue; }
52
+ return t;
53
+ }
54
+ return null;
55
+ }
56
+
57
+ /**
58
+ * The project's schedules.
59
+ * → { file, list(), add({ cron, task, model, mode, allow }), remove(id), due(now), ran(id, at, result) }
60
+ */
61
+ export function schedules({ root = process.cwd(), now = () => new Date() } = {}) {
62
+ const file = path.join(root, '.clarity', 'agent', 'schedule.json');
63
+ const read = () => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return []; } };
64
+ const save = (list) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(list, null, 2) + '\n'); };
65
+ return {
66
+ file,
67
+ list: () => read().map((e) => ({ ...e, next: nextRun(e.cron, now())?.toISOString() ?? null })),
68
+ add({ cron, task, model = null, mode = 'edits', allow = [] }) {
69
+ parseCron(cron);
70
+ if (!String(task ?? '').trim()) throw new Error('A schedule needs a task: what to do when its time comes.');
71
+ if (!['ask', 'edits', 'auto'].includes(mode)) throw new Error('mode: ask | edits | auto');
72
+ const list = read(), id = String(Math.max(0, ...list.map((e) => Number(e.id) || 0)) + 1);
73
+ const entry = { id, cron: String(cron).trim(), task: String(task).trim(), model, mode, allow, added: now().toISOString(), last: null, state: null };
74
+ save([...list, entry]);
75
+ return entry;
76
+ },
77
+ remove(id) { const list = read(), left = list.filter((e) => e.id !== String(id)); save(left); return left.length !== list.length; },
78
+ /** Those whose time has come since they last ran (or since they were added). */
79
+ due(at = now()) { return read().filter((e) => { const since = new Date(e.last ?? e.added), next = nextRun(e.cron, since); return next && next.getTime() <= at.getTime(); }); },
80
+ ran(id, at, result) { save(read().map((e) => (e.id === String(id) ? { ...e, last: at.toISOString(), state: result.state, code: result.code } : e))); },
81
+ };
82
+ }
83
+
84
+ /** Do one schedule's task now, headless; its summary is kept in .clarity/agent/runs/. → the run's result */
85
+ export async function runScheduled(entry, { root = process.cwd(), store = schedules({ root }), now = () => new Date(), run = runHeadless, write = () => {}, env = process.env, create = null } = {}) {
86
+ const at = now(), dir = path.join(root, '.clarity', 'agent', 'runs');
87
+ fs.mkdirSync(dir, { recursive: true });
88
+ const summary = path.join(dir, `schedule-${entry.id}-${at.toISOString().replace(/[:.]/g, '-')}.md`);
89
+ const result = await run({ root, task: entry.task, model: entry.model ?? undefined, mode: entry.mode, allow: entry.allow ?? [], summary, write, env: { ...env, GITHUB_STEP_SUMMARY: '' }, create });
90
+ store.ran(entry.id, at, result);
91
+ return { ...result, file: summary };
92
+ }
93
+
94
+ /**
95
+ * Stay and run each schedule when its time comes, one at a time. `once`: run what is due now and return.
96
+ * @param options root · once · now, sleep(ms) (a test gives its own) · signal · log(line)
97
+ */
98
+ export async function serveSchedules({ root = process.cwd(), once = false, now = () => new Date(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), signal = null, log = () => {}, run = runHeadless, env = process.env, create = null } = {}) {
99
+ const store = schedules({ root, now }), done = [];
100
+ for (;;) {
101
+ for (const entry of store.due(now())) {
102
+ if (signal?.aborted) return done;
103
+ log(`${now().toISOString()} schedule ${entry.id}: ${entry.task.slice(0, 80)}`);
104
+ const r = await runScheduled(entry, { root, store, now, run, env, create });
105
+ log(`${now().toISOString()} schedule ${entry.id}: ${r.state} (${r.changed.length} file${r.changed.length === 1 ? '' : 's'} changed${r.refused.length ? `, ${r.refused.length} refused` : ''}) → ${path.relative(root, r.file)}`);
106
+ done.push({ id: entry.id, state: r.state, code: r.code });
107
+ }
108
+ if (once || signal?.aborted) return done;
109
+ // until the next one is due, and no longer than a minute (the clock may be set, the file may be edited)
110
+ const next = store.list().map((e) => (e.next ? new Date(e.next).getTime() : Infinity)).reduce((a, b) => Math.min(a, b), Infinity);
111
+ await sleep(Math.max(1000, Math.min(60000, next - now().getTime())));
112
+ }
113
+ }
package/src/session.js ADDED
@@ -0,0 +1,126 @@
1
+ // @clarity-js/agent — a conversation with the agent, for a window to show.
2
+ //
3
+ // The command line draws the agent's work as text. A panel in an editor and a window on the desktop draw
4
+ // the same work as a page. Both talk to this: messages in (what the person did), messages out (what the
5
+ // page should show). It knows nothing of VS Code, of HTTP or of the page.
6
+ //
7
+ // const session = createSession({ root, post: (message) => view.postMessage(message) })
8
+ // view.onMessage((message) => session.handle(message))
9
+ //
10
+ // in: hello · send { text } · answer { id, value: true | false | 'always' } · stop · new ·
11
+ // model { spec } · mode { mode: 'ask' | 'edits' | 'auto' } · undo { id, force } (a checkpoint's id)
12
+ // out: state { busy, model, mode, root, problem, items, usage, spent } (the whole of it, on hello and
13
+ // after new) · item { item } (one more thing to show, or one that changed: same id) ·
14
+ // status { busy, model, mode, problem, usage, spent }
15
+ //
16
+ // An item is { id, kind, … }: 'user' { text } · 'text' { text } · 'tool' { name, summary, done, error, output,
17
+ // changes: [{ path, status, added, removed, diff }], checkpoint, others, undone } · 'ask' { summary, risk, usd, note,
18
+ // path, diff, added, removed, answer: null | true | false | 'always' } · 'refused' { summary } · 'error' { text } ·
19
+ // 'done' { steps, unfinished } · 'undone' { files, skipped } · 'undo-blocked' { checkpoint, conflicts }.
20
+
21
+ import path from 'node:path';
22
+ import { createCheckpoints } from './checkpoints.js';
23
+
24
+ /** What a tool gave back, short enough to show: its first lines. */
25
+ const brief = (text, most = 1200) => { const s = String(text ?? ''); return s.length > most ? s.slice(0, most) + `\n… ${s.length - most} more characters` : s; };
26
+
27
+ /**
28
+ * @param options
29
+ * root the project's folder
30
+ * post (message) => void: what the page should show
31
+ * make (options) => agent: createAgent() unless given (a test gives its own)
32
+ * model provider:model to start with (else the configured one, or the first provider with a key)
33
+ * mode 'ask' | 'edits' | 'auto' ('ask')
34
+ * options anything else createAgent() takes (env, fetchImpl, keys, config, allow)
35
+ * checkpoints createCheckpoints() unless given: what each step changes, kept through a change of model or mode
36
+ * → { handle(message), state(), busy, before(checkpoint, path), checkpoints, dispose() }
37
+ */
38
+ export function createSession({ root = process.cwd(), post = () => {}, make = null, model = null, mode = 'ask', options = {}, checkpoints = null } = {}) {
39
+ const cps = checkpoints ?? createCheckpoints({ root });
40
+ let note = null; // what the agent must be told with the next message (files were put back)
41
+ let agent = null, making = null, busy = false, stopper = null, problem = null, n = 0;
42
+ let items = [], usage = { input: 0, output: 0 }, want = { model, mode }, carry = []; // carry: what was said so far, for an agent made anew
43
+ const waiting = new Map(); // questions the page has not answered yet
44
+ const spent = () => { try { return agent?.ledger ? { today: agent.ledger.today(), month: agent.ledger.thisMonth() } : null; } catch { return null; } };
45
+ const status = () => ({ busy, model: agent?.model ?? want.model ?? null, mode: want.mode, problem, usage: { ...usage }, spent: spent() });
46
+ const tell = () => post({ type: 'status', ...status() });
47
+ const show = (item) => { const at = items.findIndex((i) => i.id === item.id); if (at < 0) items.push(item); else items[at] = item; post({ type: 'item', item: { ...item } }); return item; };
48
+ const add = (kind, more) => show({ id: 'i' + (++n), kind, ...more });
49
+
50
+ const ask = (q) => new Promise((answer) => {
51
+ const pv = q.preview && q.preview.text ? q.preview : null;
52
+ const item = add('ask', { tool: q.tool ?? null, summary: q.summary ?? String(q.tool ?? 'May I?'), risk: q.risk ?? null, usd: q.usd ?? null, note: q.note ?? null, path: pv?.path ?? null, diff: pv ? brief(pv.text, 12000) : null, added: pv?.added ?? 0, removed: pv?.removed ?? 0, answer: null });
53
+ waiting.set(item.id, (value) => { waiting.delete(item.id); show({ ...item, answer: value }); answer(value); });
54
+ });
55
+ const tools = new Map(); // a call's id → the item that shows it
56
+ const on = (e) => {
57
+ if (e.type === 'text') add('text', { text: e.text });
58
+ else if (e.type === 'tool') tools.set(e.call.id, add('tool', { name: e.call.name, summary: e.summary, done: false, error: false, output: '' }));
59
+ else if (e.type === 'result') {
60
+ const item = tools.get(e.call.id), cp = e.checkpoint ?? null;
61
+ if (item) { tools.delete(e.call.id); show({ ...item, done: true, error: !!e.result?.error, output: brief(e.result?.text), checkpoint: cp?.id ?? null, undone: false, others: (cp?.others ?? []).slice(0, 40), changes: (cp?.files ?? []).map((f) => ({ path: f.path, status: f.status, added: f.added, removed: f.removed, diff: brief(f.diff, 12000) })) }); }
62
+ }
63
+ else if (e.type === 'refused') add('refused', { summary: e.reason === 'user' ? `Not allowed: ${e.call.name}` : String(e.reason) });
64
+ else if (e.type === 'usage') { usage = { ...e.usage }; tell(); }
65
+ };
66
+ // one agent for the conversation: made when it is first needed, and again when the model or the mode changes
67
+ const ready = () => (making ??= (async () => {
68
+ const create = make ?? (await import('./index.js')).createAgent;
69
+ agent = await create({ root, ...options, ...(want.model ? { model: want.model } : {}), mode: want.mode, ask, on, checkpoints: cps });
70
+ if (carry.length && Array.isArray(agent.messages)) agent.messages.push(...carry);
71
+ carry = [];
72
+ return agent;
73
+ })().catch((e) => { making = null; throw e; }));
74
+ // let the agent go; keep: what was said goes on with the next one (another model or mode, the same conversation)
75
+ const drop = async (keep = false) => { const a = agent; agent = null; making = null; carry = keep ? (a?.messages?.slice() ?? carry) : []; try { await a?.close?.(); } catch { /* it is gone either way */ } };
76
+
77
+ async function send(text) {
78
+ text = String(text ?? '').trim();
79
+ if (!text || busy) return;
80
+ busy = true; problem = null; add('user', { text }); tell();
81
+ stopper = new AbortController();
82
+ try {
83
+ const a = await ready();
84
+ tell();
85
+ const said = note ? `${note}\n\n${text}` : text; note = null;
86
+ const r = await a.run(said, { signal: stopper.signal });
87
+ if (r?.total) usage = { ...r.total };
88
+ add('done', { steps: r?.steps ?? 0, unfinished: !!r?.unfinished });
89
+ } catch (e) {
90
+ const stopped = stopper.signal.aborted;
91
+ if (!agent) problem = e.message; // no model, no key: the page says how to give one
92
+ add(stopped ? 'done' : 'error', stopped ? { steps: 0, stopped: true } : { text: e.message });
93
+ } finally { busy = false; stopper = null; for (const answer of [...waiting.values()]) answer(false); tell(); }
94
+ }
95
+
96
+ // put the files back as they were before a step; what was done after it goes too
97
+ function undo(id, force) {
98
+ const r = cps.undo(Number(id), { force: !!force });
99
+ if (!r.done) { if (r.conflicts.length) add('undo-blocked', { checkpoint: Number(id), conflicts: r.conflicts }); return; }
100
+ for (const item of items.filter((i) => i.kind === 'tool' && r.ids.includes(i.checkpoint))) show({ ...item, undone: true });
101
+ for (const item of items.filter((i) => i.kind === 'undo-blocked' && i.checkpoint >= Number(id))) show({ ...item, settled: true });
102
+ add('undone', { files: r.restored, skipped: r.skipped });
103
+ note = `(I undid your changes to ${r.restored.join(', ')}: ${r.restored.length === 1 ? 'that file is' : 'those files are'} as before. Read ${r.restored.length === 1 ? 'it' : 'them'} again before changing ${r.restored.length === 1 ? 'it' : 'them'}.)`;
104
+ }
105
+
106
+ return {
107
+ checkpoints: cps,
108
+ /** What a file held before a step's checkpoint, as text (null: it was not there). For an editor's own diff view. */
109
+ before: (checkpoint, file) => cps.before(Number(checkpoint), file)?.toString('utf8') ?? null,
110
+ get busy() { return busy; },
111
+ state: () => ({ type: 'state', root, name: path.basename(root), items: items.map((i) => ({ ...i })), ...status() }),
112
+ /** A message from the page. Returns when what it asked for is done (a send: when the agent has finished). */
113
+ async handle(message) {
114
+ const m = message ?? {};
115
+ if (m.type === 'hello') post(this.state());
116
+ else if (m.type === 'send') await send(m.text);
117
+ else if (m.type === 'answer') waiting.get(m.id)?.(m.value === 'always' ? 'always' : m.value === true);
118
+ else if (m.type === 'stop') { stopper?.abort(); for (const answer of [...waiting.values()]) answer(false); }
119
+ else if (m.type === 'undo') { if (!busy) undo(m.id, m.force); }
120
+ else if (m.type === 'new') { if (busy) return; await drop(); items = []; usage = { input: 0, output: 0 }; problem = null; note = null; tools.clear(); post(this.state()); }
121
+ else if (m.type === 'model') { if (busy) return; want.model = m.spec ? String(m.spec) : null; await drop(true); problem = null; tell(); }
122
+ else if (m.type === 'mode') { if (busy || !['ask', 'edits', 'auto'].includes(m.mode)) return; want.mode = m.mode; await drop(true); tell(); }
123
+ },
124
+ async dispose() { stopper?.abort(); for (const answer of [...waiting.values()]) answer(false); await drop(); },
125
+ };
126
+ }
package/src/ship.js ADDED
@@ -0,0 +1,127 @@
1
+ // @clarity-js/agent — ship: put a built site, app or game where people can open it. Each target is the host's own
2
+ // command-line tool, run with the user's key from the key store (in its environment, never on the command line):
3
+ //
4
+ // const s = shipper({ root, keys })
5
+ // s.plan({ target: 'netlify', dir: 'dist' }) // → { command: 'npx …', env: ['NETLIFY_AUTH_TOKEN'], … }
6
+ // await s.ship({ target: 'netlify', dir: 'dist' })
7
+ //
8
+ // Publishing leaves the computer, so the agent's tool for it has risk 'publish': it is always asked.
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { spawn } from 'node:child_process';
13
+ import { inside } from './tools.js';
14
+
15
+ /** Where a build can go. `args(o)` is the command; `keyEnv` is what its tool reads; `need` what it must be told. */
16
+ export const TARGETS = {
17
+ netlify: { name: 'Netlify', keyEnv: 'NETLIFY_AUTH_TOKEN', docs: 'https://docs.netlify.com/cli/get-started/', args: (o) => ['npx', '--yes', 'netlify-cli', 'deploy', '--prod', `--dir=${o.dir}`, ...(o.site ? [`--site=${o.site}`] : [])] },
18
+ cloudflare: { name: 'Cloudflare Pages', keyEnv: 'CLOUDFLARE_API_TOKEN', extraEnv: ['CLOUDFLARE_ACCOUNT_ID'], need: ['project'], docs: 'https://developers.cloudflare.com/pages/', args: (o) => ['npx', '--yes', 'wrangler', 'pages', 'deploy', o.dir, `--project-name=${o.project}`, ...(o.branch ? [`--branch=${o.branch}`] : [])] },
19
+ vercel: { name: 'Vercel', docs: 'https://vercel.com/docs/cli', note: 'signed in with `npx vercel login` first', args: (o) => ['npx', '--yes', 'vercel', 'deploy', o.dir, '--prod', '--yes'] },
20
+ 'github-pages': { name: 'GitHub Pages', docs: 'https://github.com/tschaub/gh-pages', note: 'pushes the folder to the gh-pages branch of this repository\'s origin', args: (o) => ['npx', '--yes', 'gh-pages', '-d', o.dir, ...(o.branch ? ['-b', o.branch] : [])] },
21
+ surge: { name: 'Surge', keyEnv: 'SURGE_TOKEN', extraEnv: ['SURGE_LOGIN'], need: ['domain'], docs: 'https://surge.sh/help/', args: (o) => ['npx', '--yes', 'surge', o.dir, o.domain] },
22
+ itch: { name: 'itch.io (butler)', keyEnv: 'BUTLER_API_KEY', need: ['game'], docs: 'https://itch.io/docs/butler/', note: 'needs butler installed', args: (o) => ['butler', 'push', o.dir, `${o.game}:${o.channel ?? 'html5'}`] },
23
+ // your own server (and hosts that give SSH, such as Hostinger's): rsync over ssh, with the keys ssh already has
24
+ rsync: { name: 'A server over SSH (rsync)', need: ['host', 'path'], aliases: ['ssh', 'hostinger', 'server'], docs: 'https://rsync.samba.org', note: 'uses your ssh keys; --delete makes the folder match', args: (o) => ['rsync', '-az', '--delete', `${o.dir.replace(/\/$/, '')}/`, `${o.host}:${o.path}`] },
25
+ 'gitlab-pages': { name: 'GitLab Pages', docs: 'https://docs.gitlab.com/user/project/pages/', note: 'writes a pages job into .gitlab-ci.yml if there is none, then pushes the branch', prepare: 'gitlabPages', args: (o) => ['git', 'push', o.remote ?? 'origin', 'HEAD'] },
26
+ fly: { name: 'Fly.io', noDir: true, keyEnv: 'FLY_API_TOKEN', docs: 'https://fly.io/docs/flyctl/deploy/', note: 'needs flyctl and a fly.toml', args: (o) => ['flyctl', 'deploy', '--remote-only', ...(o.app ? ['--app', o.app] : [])] },
27
+ railway: { name: 'Railway', noDir: true, keyEnv: 'RAILWAY_TOKEN', docs: 'https://docs.railway.com/guides/cli', args: (o) => ['npx', '--yes', '@railway/cli', 'up', '--detach', ...(o.service ? ['--service', o.service] : [])] },
28
+ render: { name: 'Render (deploy hook)', noDir: true, keyEnv: 'RENDER_DEPLOY_HOOK', docs: 'https://render.com/docs/deploy-hooks', note: 'the key is the service\'s deploy hook address; Render builds from your repository', hook: true, args: () => ['POST', '<deploy hook>'] },
29
+ digitalocean: { name: 'DigitalOcean App Platform', noDir: true, keyEnv: 'DIGITALOCEAN_ACCESS_TOKEN', need: ['app'], docs: 'https://docs.digitalocean.com/reference/doctl/reference/apps/create-deployment/', note: 'needs doctl', args: (o) => ['doctl', 'apps', 'create-deployment', o.app, '--wait'] },
30
+ firebase: { name: 'Firebase Hosting', noDir: true, docs: 'https://firebase.google.com/docs/hosting', note: 'signed in with `npx firebase-tools login` first; needs firebase.json', args: (o) => ['npx', '--yes', 'firebase-tools', 'deploy', '--only', 'hosting', ...(o.project ? ['--project', o.project] : [])] },
31
+ poki: { name: 'Poki', docs: 'https://www.npmjs.com/package/@poki/cli', note: 'you sign in once yourself: npx @poki/cli auth login; and once: npx @poki/cli init --game <id> --build-dir dist', args: (o) => ['npx', '--yes', '@poki/cli', 'versions', 'upload', '--build-dir', o.dir, '--wait'] },
32
+ steam: { name: 'Steam (steamcmd)', noDir: true, need: ['user', 'vdf'], docs: 'https://partner.steamgames.com/doc/sdk/uploading', note: 'needs steamcmd and an app_build .vdf; Steam Guard asks you in its own window', args: (o) => ['steamcmd', '+login', o.user, '+run_app_build', o.vdf, '+quit'] },
33
+ 'google-play': { name: 'Google Play (fastlane supply)', noDir: true, need: ['aab', 'package', 'jsonKey'], docs: 'https://docs.fastlane.tools/actions/supply/', note: 'needs fastlane and a service-account JSON key', args: (o) => ['fastlane', 'supply', '--aab', o.aab, '--package_name', o.package, '--track', o.track ?? 'internal', '--json_key', o.jsonKey] },
34
+ 'app-store': { name: 'App Store Connect (TestFlight)', noDir: true, need: ['ipa', 'apiKey', 'issuer'], docs: 'https://developer.apple.com/help/app-store-connect/manage-builds/upload-builds', note: 'macOS with Xcode; the .p8 key in ~/.appstoreconnect/private_keys', args: (o) => ['xcrun', 'altool', '--upload-app', '-f', o.ipa, '-t', o.platform ?? 'ios', '--apiKey', o.apiKey, '--apiIssuer', o.issuer] },
35
+ 'meta-horizon': { name: 'Meta Horizon Store (Quest)', noDir: true, keyEnv: 'META_APP_SECRET', need: ['appId', 'apk'], docs: 'https://developers.meta.com/horizon/resources/publish-reference-platform-command-line-utility/', note: 'needs ovr-platform-util; its secret goes on its command line, as the tool requires', secretArg: '--app-secret', args: (o) => ['ovr-platform-util', 'upload-quest-build', '--app-id', o.appId, '--apk', o.apk, '--channel', o.channel ?? 'ALPHA'] },
36
+ };
37
+ const ALIASES = Object.fromEntries(Object.entries(TARGETS).flatMap(([k, t]) => (t.aliases ?? []).map((a) => [a, k])));
38
+ export const targetOf = (name) => (TARGETS[name] ? name : ALIASES[name] ?? name);
39
+
40
+ // GitLab Pages publishes what a job named "pages" leaves in public/: the job builds the project in CI
41
+ export const GITLAB_PAGES_JOB = (dir) => `pages:
42
+ stage: deploy
43
+ image: node:22
44
+ script:
45
+ - npm ci
46
+ - npm run build
47
+ - rm -rf public && cp -r ${dir} public
48
+ artifacts:
49
+ paths:
50
+ - public
51
+ rules:
52
+ - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
53
+ `;
54
+
55
+ /** The shipper for a project. keys: the key store; config: { target: { site, project, game, … } } from agent.json. */
56
+ export function shipper({ root = process.cwd(), keys, config = {}, env = process.env, spawnImpl = spawn, fetchImpl = globalThis.fetch } = {}) {
57
+ const keyFor = (target) => { const t = TARGETS[target]; return t.keyEnv ? env[t.keyEnv] ?? keys?.get(target) ?? null : null; };
58
+ return {
59
+ targets: TARGETS,
60
+ /** What would run, and what it is missing: → { target, name, dir, argv, command, env: [names], missing: [..] } */
61
+ plan({ target: asked, dir, ...more }) {
62
+ const target = targetOf(asked), t = TARGETS[target];
63
+ if (!t) throw new Error(`No target "${asked}". Targets: ${Object.keys(TARGETS).join(', ')}.`);
64
+ const o = { ...(config[target] ?? {}), ...more };
65
+ o.dir = dir ?? o.dir ?? (['dist', 'build', 'out', 'public'].find((d) => fs.existsSync(path.join(root, d))) ?? '.');
66
+ inside(root, o.dir); // the folder must be the project's
67
+ if (!t.noDir && !fs.existsSync(path.join(root, o.dir))) throw new Error(`There is no ${o.dir} folder to ship. Build first (npm run build), or say which folder.`);
68
+ const missing = (t.need ?? []).filter((k) => !o[k]).map((k) => `${k} (say it, or set ship.${target}.${k} in .clarity/agent.json)`);
69
+ const argv = t.args({ ...Object.fromEntries((t.need ?? []).map((k) => [k, `<${k}>`])), ...o }); // what is missing shows as <game>
70
+ return { target, name: t.name, dir: o.dir, argv, command: argv.join(' '), env: [t.keyEnv, ...(t.extraEnv ?? [])].filter(Boolean), keySet: !t.keyEnv || !!keyFor(target), missing, note: t.note ?? null, docs: t.docs };
71
+ },
72
+ /** Run it; → { ok, code, url, output } (the last of what it printed, and the first https address in it). */
73
+ async ship(args, { signal, onOutput } = {}) {
74
+ const p = this.plan(args);
75
+ if (p.missing.length) throw new Error(`${p.name} needs: ${p.missing.join('; ')}.`);
76
+ const t = TARGETS[p.target], key = keyFor(p.target);
77
+ if (t.hook) { // a deploy hook: one POST to the address kept as its key
78
+ if (!key) throw new Error(`${p.name} needs its deploy hook: clarity keys set ${p.target}`);
79
+ const res = await fetchImpl(key, { method: 'POST', signal });
80
+ const text = await res.text().catch(() => '');
81
+ return { ok: res.ok, code: res.status, url: null, output: text.slice(0, 2000), target: p.target, dir: p.dir };
82
+ }
83
+ if (t.prepare === 'gitlabPages') {
84
+ const ci = path.join(root, '.gitlab-ci.yml');
85
+ if (!fs.existsSync(ci)) { fs.writeFileSync(ci, GITLAB_PAGES_JOB(p.dir)); onOutput?.('Wrote .gitlab-ci.yml with a pages job. Commit it, then ship again.\n'); return { ok: false, code: null, url: null, output: 'Wrote .gitlab-ci.yml with a pages job: commit it, then ship again.', target: p.target, dir: p.dir, wrote: '.gitlab-ci.yml' }; }
86
+ if (!/^pages\s*:/m.test(fs.readFileSync(ci, 'utf8'))) throw new Error('.gitlab-ci.yml has no pages job: add one (see GITLAB_PAGES_JOB), or publish with another target.');
87
+ }
88
+ if (t.secretArg) { if (!key) throw new Error(`${p.name} needs its secret: clarity keys set ${p.target}`); p.argv.push(t.secretArg, key); }
89
+ const childEnv = { ...env, ...(key && !t.secretArg ? { [t.keyEnv]: key } : {}) };
90
+ // what is not secret (an account id) can sit in agent.json: ship.cloudflare.env.CLOUDFLARE_ACCOUNT_ID
91
+ for (const name of t.extraEnv ?? []) { const v = env[name] ?? config[p.target]?.env?.[name]; if (v) childEnv[name] = v; }
92
+ return await new Promise((resolve, reject) => {
93
+ let output = '';
94
+ const child = spawnImpl(p.argv[0], p.argv.slice(1), { cwd: root, env: childEnv, signal, stdio: ['ignore', 'pipe', 'pipe'] });
95
+ const take = (d) => { const s = String(d); output = (output + s).slice(-20000); onOutput?.(s); };
96
+ child.stdout?.on('data', take); child.stderr?.on('data', take);
97
+ child.on('error', (e) => reject(new Error(e.code === 'ENOENT' ? `${p.argv[0]} is not installed (${p.docs}).` : e.message)));
98
+ child.on('close', (code) => {
99
+ const urls = [...output.matchAll(/https:\/\/[^\s'")\]]+/g)].map((m) => m[0]).filter((u) => !/docs\.|\/help|github\.com\/tschaub/.test(u));
100
+ resolve({ ok: code === 0, code, url: urls.at(-1) ?? null, output: output.slice(-4000), target: p.target, dir: p.dir });
101
+ });
102
+ });
103
+ },
104
+ };
105
+ }
106
+
107
+ const obj = (properties, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
108
+ /** ship, for the agent: always asked, since it publishes. */
109
+ export function shipTool(s) {
110
+ return {
111
+ name: 'ship', risk: 'publish',
112
+ description: `Publish a built folder (dist by default) to a host: ${Object.entries(TARGETS).map(([k, t]) => `${k} (${t.name})`).join(', ')}. Build it first. The user is always asked.`,
113
+ inputSchema: obj({
114
+ target: { type: 'string', enum: Object.keys(TARGETS) }, dir: { type: 'string', description: 'The folder to publish, from the project\'s root.' },
115
+ host: { type: 'string', description: 'rsync: user@host.' }, path: { type: 'string', description: 'rsync: the folder on the server.' }, app: { type: 'string', description: 'Fly.io or DigitalOcean: the app.' },
116
+ user: { type: 'string', description: 'Steam: the build account.' }, vdf: { type: 'string', description: 'Steam: the app_build .vdf.' }, aab: { type: 'string' }, package: { type: 'string' }, jsonKey: { type: 'string' },
117
+ ipa: { type: 'string' }, apiKey: { type: 'string', description: 'App Store Connect: the API key id.' }, issuer: { type: 'string' }, appId: { type: 'string' }, apk: { type: 'string' }, service: { type: 'string' },
118
+ site: { type: 'string', description: 'Netlify: the site id.' }, project: { type: 'string', description: 'Cloudflare Pages: the project name.' },
119
+ domain: { type: 'string', description: 'Surge: the domain.' }, game: { type: 'string', description: 'itch.io: user/game.' }, channel: { type: 'string', description: 'itch.io: the channel (html5, windows, mac, linux).' },
120
+ }, ['target']),
121
+ summary: (a) => { try { return `publish with ${s.plan(a).command}`; } catch { return `publish to ${a.target}`; } },
122
+ async run(args, { signal }) {
123
+ const r = await s.ship(args, { signal });
124
+ return { text: r.ok ? `Published to ${TARGETS[r.target].name}${r.url ? `: ${r.url}` : ''}.` : `${TARGETS[r.target].name} stopped with code ${r.code}:\n${r.output}`, error: !r.ok, data: r };
125
+ },
126
+ };
127
+ }