@promethea-research/sundial 0.0.0-stage → 0.2.3

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,3530 @@
1
+ #!/usr/bin/env node
2
+ // Copyright (c) Promethea Research LLC. All rights reserved. Proprietary.
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __esm = (fn, res, err2) => function __init() {
6
+ if (err2) throw err2[0];
7
+ try {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ } catch (e) {
10
+ throw err2 = [e], e;
11
+ }
12
+ };
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+
18
+ // ../../packages/client/src/config.ts
19
+ var config_exports = {};
20
+ __export(config_exports, {
21
+ DEFAULT_SERVER: () => DEFAULT_SERVER,
22
+ account: () => account,
23
+ addProject: () => addProject,
24
+ configDir: () => configDir,
25
+ prefs: () => prefs,
26
+ read: () => read,
27
+ removeProject: () => removeProject,
28
+ saveAccount: () => saveAccount,
29
+ savePrefs: () => savePrefs,
30
+ serverUrl: () => serverUrl,
31
+ setThreadFolder: () => setThreadFolder,
32
+ update: () => update,
33
+ write: () => write
34
+ });
35
+ import fs from "node:fs";
36
+ import os from "node:os";
37
+ import path from "node:path";
38
+ function read() {
39
+ return readJson(file());
40
+ }
41
+ function write(c) {
42
+ fs.mkdirSync(configDir(), { recursive: true, mode: 448 });
43
+ const tmp = file() + `.${process.pid}.tmp`;
44
+ fs.writeFileSync(tmp, JSON.stringify(c, null, 2), { mode: 384 });
45
+ fs.renameSync(tmp, file());
46
+ }
47
+ function update(f) {
48
+ const c = read();
49
+ f(c);
50
+ write(c);
51
+ }
52
+ function serverUrl(flag) {
53
+ return (flag || process.env.PROMETHEA_URL || read().server || DEFAULT_SERVER).replace(/\/+$/, "");
54
+ }
55
+ function account(server) {
56
+ return read().accounts?.[server] ?? readJson(legacy()).accounts?.[server] ?? null;
57
+ }
58
+ function saveAccount(server, a) {
59
+ update((c) => {
60
+ c.accounts ??= {};
61
+ if (a) c.accounts[server] = a;
62
+ else delete c.accounts[server];
63
+ });
64
+ }
65
+ function addProject(folder) {
66
+ update((c) => {
67
+ c.projects = [folder, ...(c.projects ?? []).filter((f) => f !== folder)].slice(0, 30);
68
+ });
69
+ }
70
+ function removeProject(folder) {
71
+ update((c) => {
72
+ c.projects = (c.projects ?? []).filter((f) => f !== folder);
73
+ });
74
+ }
75
+ function setThreadFolder(id, folder) {
76
+ update((c) => {
77
+ c.threads = { ...c.threads, [id]: folder };
78
+ });
79
+ }
80
+ var DEFAULT_SERVER, configDir, file, legacy, readJson, prefs, savePrefs;
81
+ var init_config = __esm({
82
+ "../../packages/client/src/config.ts"() {
83
+ "use strict";
84
+ DEFAULT_SERVER = "https://sundial.promethearesearch.com";
85
+ configDir = () => process.env.SUNDIAL_CONFIG_DIR || path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "promethea");
86
+ file = () => path.join(configDir(), "sundial.json");
87
+ legacy = () => path.join(configDir(), "config.json");
88
+ readJson = (p) => {
89
+ try {
90
+ return JSON.parse(fs.readFileSync(p, "utf8"));
91
+ } catch {
92
+ return {};
93
+ }
94
+ };
95
+ prefs = () => read().prefs ?? {};
96
+ savePrefs = (p) => update((c) => {
97
+ c.prefs = { ...c.prefs, ...p };
98
+ });
99
+ }
100
+ });
101
+
102
+ // ../../packages/client/src/api.ts
103
+ async function* readSSE(res) {
104
+ const reader = res.body.getReader();
105
+ const dec = new TextDecoder();
106
+ let buf = "";
107
+ const parse2 = function* (block) {
108
+ let event = "message", data = "";
109
+ for (const line of block.split("\n")) {
110
+ if (line.startsWith("event: ")) event = line.slice(7).trim();
111
+ else if (line.startsWith("data: ")) data += line.slice(6);
112
+ }
113
+ try {
114
+ yield { event, data: JSON.parse(data) };
115
+ } catch {
116
+ }
117
+ };
118
+ for (; ; ) {
119
+ const { value, done } = await reader.read();
120
+ if (done) break;
121
+ buf += dec.decode(value, { stream: true }).replace(/\r\n/g, "\n");
122
+ let i;
123
+ while ((i = buf.indexOf("\n\n")) >= 0) {
124
+ const block = buf.slice(0, i);
125
+ buf = buf.slice(i + 2);
126
+ yield* parse2(block);
127
+ }
128
+ }
129
+ if (buf.trim()) yield* parse2(buf);
130
+ }
131
+ var TOKENS_PER_MESSAGE, messagesLeft, ApiError, VERSION, Api, links;
132
+ var init_api = __esm({
133
+ "../../packages/client/src/api.ts"() {
134
+ "use strict";
135
+ init_config();
136
+ TOKENS_PER_MESSAGE = 2e3;
137
+ messagesLeft = (w) => Math.max(0, Math.round((w.limit - w.used) / TOKENS_PER_MESSAGE));
138
+ ApiError = class extends Error {
139
+ constructor(status, message) {
140
+ super(message);
141
+ this.status = status;
142
+ }
143
+ status;
144
+ };
145
+ VERSION = "0.2.3";
146
+ Api = class {
147
+ /** PROMETHEA_TOKEN: a terminal token for CI, when nothing is saved. */
148
+ constructor(server, token = account(server)?.token ?? process.env.PROMETHEA_TOKEN ?? null, fetcher = (...a) => fetch(...a)) {
149
+ this.server = server;
150
+ this.token = token;
151
+ this.fetcher = fetcher;
152
+ }
153
+ server;
154
+ token;
155
+ fetcher;
156
+ headers(extra = {}) {
157
+ return {
158
+ "content-type": "application/json",
159
+ "user-agent": `sundial/${VERSION}`,
160
+ ...this.token ? { authorization: `Bearer ${this.token}` } : {},
161
+ ...extra
162
+ };
163
+ }
164
+ async raw(path8, init = {}) {
165
+ try {
166
+ return await this.fetcher(this.server + path8, { ...init, headers: this.headers(init.headers) });
167
+ } catch (e) {
168
+ if (e.name === "AbortError") throw e;
169
+ throw new ApiError(0, `Can't reach ${this.server}. Check your connection (or set another server).`);
170
+ }
171
+ }
172
+ async json(path8, init = {}) {
173
+ const res = await this.raw(path8, init);
174
+ const data = await res.json().catch(() => ({}));
175
+ if (!res.ok) throw new ApiError(res.status, data.error ?? `Request failed (${res.status})`);
176
+ return data;
177
+ }
178
+ me = () => this.json("/api/me");
179
+ conversations = () => this.json("/api/conversations").then((d) => d.conversations);
180
+ conversation = (id) => this.json(
181
+ `/api/conversations/${id}`
182
+ );
183
+ patchConversation = (id, body) => this.json(`/api/conversations/${id}`, { method: "PATCH", body: JSON.stringify(body) });
184
+ deleteConversation = (id) => this.json(`/api/conversations/${id}`, { method: "DELETE" });
185
+ rate = (cid, mid, rating) => this.json(`/api/conversations/${cid}/messages/${mid}`, { method: "PATCH", body: JSON.stringify({ rating }) });
186
+ compact = (id, focus) => this.json(`/api/conversations/${id}/compact`, { method: "POST", body: JSON.stringify(focus ? { focus } : {}) });
187
+ logout = () => this.json("/api/cli/sessions", { method: "DELETE", body: "{}" });
188
+ };
189
+ links = (server) => ({
190
+ pricing: (plan) => `${server}/pricing${plan ? `?plan=${encodeURIComponent(plan)}` : ""}`,
191
+ usage: `${server}/settings?tab=usage`,
192
+ memory: `${server}/settings?tab=memory`,
193
+ /** The three knowledge graphs: explore the world's, add and correct your own and your workspace's. */
194
+ knowledge: `${server}/knowledge`,
195
+ account: `${server}/settings`
196
+ });
197
+ }
198
+ });
199
+
200
+ // ../../packages/client/src/auth.ts
201
+ import { spawn } from "node:child_process";
202
+ import os2 from "node:os";
203
+ function openBrowser(url) {
204
+ if (!/^https?:\/\//.test(url)) return false;
205
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
206
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
207
+ try {
208
+ const p = spawn(cmd, args, { stdio: "ignore", detached: true });
209
+ p.on("error", () => {
210
+ });
211
+ p.unref();
212
+ return true;
213
+ } catch {
214
+ return false;
215
+ }
216
+ }
217
+ async function startLogin(server, client = "Sundial", api = new Api(server, null)) {
218
+ const d = await api.json(
219
+ "/api/cli/device",
220
+ { method: "POST", body: JSON.stringify({ name: `${os2.hostname()} (${client})` }) }
221
+ );
222
+ const poll = async (signal) => {
223
+ const deadline = Date.now() + d.expiresIn * 1e3;
224
+ while (Date.now() < deadline) {
225
+ if (signal?.aborted) throw new ApiError(0, "Sign-in cancelled");
226
+ await new Promise((r) => setTimeout(r, d.interval * 1e3));
227
+ const res = await api.raw("/api/cli/token", { method: "POST", body: JSON.stringify({ deviceCode: d.deviceCode }) });
228
+ if (res.status === 428 || res.status === 429) continue;
229
+ const body = await res.json().catch(() => ({}));
230
+ if (!res.ok || !body.token) throw new ApiError(res.status, body.error ?? "Sign-in failed");
231
+ saveAccount(server, { token: body.token, email: body.email ?? "" });
232
+ return body.email ?? "";
233
+ }
234
+ throw new ApiError(410, "The sign-in code expired. Sign in again.");
235
+ };
236
+ return { userCode: d.userCode, url: d.verificationUriComplete, poll };
237
+ }
238
+ var init_auth = __esm({
239
+ "../../packages/client/src/auth.ts"() {
240
+ "use strict";
241
+ init_api();
242
+ init_config();
243
+ }
244
+ });
245
+
246
+ // ../../packages/client/src/files.ts
247
+ import fs2 from "node:fs";
248
+ import path2 from "node:path";
249
+ import { structuredPatch } from "diff";
250
+ function inside(root, p) {
251
+ if (!p || path2.isAbsolute(p) || p.includes("\0")) return null;
252
+ const abs = path2.resolve(root, p);
253
+ const rel = path2.relative(root, abs);
254
+ if (!rel || rel.startsWith("..") || path2.isAbsolute(rel)) return null;
255
+ try {
256
+ const realRoot = fs2.realpathSync(root);
257
+ let probe = abs;
258
+ while (!fs2.existsSync(probe)) probe = path2.dirname(probe);
259
+ const r = path2.relative(realRoot, fs2.realpathSync(probe));
260
+ if (r.startsWith("..") || path2.isAbsolute(r)) return null;
261
+ } catch {
262
+ return null;
263
+ }
264
+ return abs;
265
+ }
266
+ function diffLines(p, before, after, context = 3) {
267
+ const patch = structuredPatch(p, p, before ?? "", after, "", "", { context });
268
+ const diff = [];
269
+ let added = 0, removed = 0;
270
+ for (const h of patch.hunks) {
271
+ diff.push(`@@ -${h.oldStart},${h.oldLines} +${h.newStart},${h.newLines} @@`);
272
+ for (const l of h.lines) {
273
+ if (l.startsWith("+")) added++;
274
+ else if (l.startsWith("-")) removed++;
275
+ if (!l.startsWith("\\")) diff.push(l);
276
+ }
277
+ }
278
+ return { diff, added, removed };
279
+ }
280
+ function planWrite(root, p, content) {
281
+ const abs = inside(root, p);
282
+ let before = null;
283
+ if (abs) {
284
+ try {
285
+ before = fs2.readFileSync(abs, "utf8");
286
+ } catch {
287
+ before = null;
288
+ }
289
+ }
290
+ return { path: p, abs, content, before, exists: before !== null, unchanged: before === content, ...diffLines(p, before, content) };
291
+ }
292
+ function mentions(text) {
293
+ const out = [];
294
+ for (const m of text.matchAll(/(?:^|\s)@([^\s@]+)/g)) out.push(m[1].replace(/[.,;:!?)]+$/, ""));
295
+ return [...new Set(out)];
296
+ }
297
+ function readAttached(root, paths) {
298
+ const files = {};
299
+ const skipped = [];
300
+ let total = 0;
301
+ for (const p of paths) {
302
+ const abs = inside(root, p);
303
+ try {
304
+ if (!abs || fs2.statSync(abs).size > MAX_FILE) {
305
+ skipped.push(p);
306
+ continue;
307
+ }
308
+ const b = fs2.readFileSync(abs);
309
+ if (b.subarray(0, 8e3).includes(0) || total + b.length > MAX_TOTAL) {
310
+ skipped.push(p);
311
+ continue;
312
+ }
313
+ files[p] = b.toString("utf8");
314
+ total += b.length;
315
+ } catch {
316
+ skipped.push(p);
317
+ }
318
+ }
319
+ return { files, skipped };
320
+ }
321
+ var MAX_FILE, MAX_TOTAL;
322
+ var init_files = __esm({
323
+ "../../packages/client/src/files.ts"() {
324
+ "use strict";
325
+ MAX_FILE = 4e6;
326
+ MAX_TOTAL = 8e6;
327
+ }
328
+ });
329
+
330
+ // ../../packages/client/src/instructions.ts
331
+ var instructions_exports = {};
332
+ __export(instructions_exports, {
333
+ NAMES: () => NAMES,
334
+ addLine: () => addLine,
335
+ load: () => load,
336
+ loadSkills: () => loadSkills
337
+ });
338
+ import fs3 from "node:fs";
339
+ import path3 from "node:path";
340
+ function repoRoot(dir) {
341
+ for (let d = path3.resolve(dir); ; d = path3.dirname(d)) {
342
+ if (fs3.existsSync(path3.join(d, ".git"))) return d;
343
+ if (path3.dirname(d) === d) return null;
344
+ }
345
+ }
346
+ function loadSkills(cwd) {
347
+ const skills = [];
348
+ const seen = /* @__PURE__ */ new Set();
349
+ const scanDir = (baseDir) => {
350
+ try {
351
+ if (!fs3.existsSync(baseDir)) return;
352
+ for (const entry of fs3.readdirSync(baseDir, { withFileTypes: true })) {
353
+ if (!entry.isDirectory()) continue;
354
+ const skillPath = path3.join(baseDir, entry.name, "SKILL.md");
355
+ if (fs3.existsSync(skillPath) && !seen.has(entry.name)) {
356
+ const content = fs3.readFileSync(skillPath, "utf8").trim();
357
+ if (content) {
358
+ seen.add(entry.name);
359
+ skills.push({ name: entry.name, path: skillPath, instructions: content.slice(0, 4e3) });
360
+ }
361
+ }
362
+ }
363
+ } catch {
364
+ }
365
+ };
366
+ scanDir(path3.join(cwd, ".sundial", "skills"));
367
+ scanDir(path3.join(cwd, ".promethea", "skills"));
368
+ scanDir(path3.join(configDir(), "skills"));
369
+ return skills;
370
+ }
371
+ function load(cwd) {
372
+ const files = [];
373
+ const parts = [];
374
+ const add = (p) => {
375
+ try {
376
+ const t = fs3.readFileSync(p, "utf8").trim();
377
+ if (t && !files.includes(p)) {
378
+ files.push(p);
379
+ parts.push(t);
380
+ }
381
+ } catch {
382
+ }
383
+ };
384
+ add(path3.join(configDir(), "PROMETHEA.md"));
385
+ add(path3.join(configDir(), "UCHI.md"));
386
+ const top = repoRoot(cwd) ?? path3.resolve(cwd);
387
+ const chain = [];
388
+ for (let d = path3.resolve(cwd); ; d = path3.dirname(d)) {
389
+ chain.unshift(d);
390
+ if (d === top || path3.dirname(d) === d) break;
391
+ }
392
+ for (const d of chain) {
393
+ for (const n of NAMES) add(path3.join(d, n));
394
+ add(path3.join(d, ".promethea", "PROMETHEA.md"));
395
+ add(path3.join(d, ".sundial", "SUNDIAL.md"));
396
+ }
397
+ const activeSkills = loadSkills(cwd);
398
+ for (const sk of activeSkills) {
399
+ files.push(sk.path);
400
+ parts.push(`[Skill: ${sk.name}]
401
+ ${sk.instructions}`);
402
+ }
403
+ let text = parts.join("\n\n");
404
+ if (text.length > CAP) text = text.slice(text.length - CAP);
405
+ return { text, files };
406
+ }
407
+ function addLine(cwd, line) {
408
+ const p = path3.join(cwd, "PROMETHEA.md");
409
+ const prev = fs3.existsSync(p) ? fs3.readFileSync(p, "utf8") : "";
410
+ fs3.writeFileSync(p, (prev && !prev.endsWith("\n") ? prev + "\n" : prev) + `- ${line.trim()}
411
+ `);
412
+ return p;
413
+ }
414
+ var NAMES, CAP;
415
+ var init_instructions = __esm({
416
+ "../../packages/client/src/instructions.ts"() {
417
+ "use strict";
418
+ init_config();
419
+ NAMES = ["SUNDIAL.md", "PROMETHEA.md", "UCHI.md", "CLAUDE.md", "AGENTS.md"];
420
+ CAP = 2e4;
421
+ }
422
+ });
423
+
424
+ // ../../packages/client/src/mcp-args.ts
425
+ function signature(t) {
426
+ const props = t.inputSchema?.properties ?? {};
427
+ const req = new Set(t.inputSchema?.required ?? []);
428
+ const sig = Object.keys(props).slice(0, 5).map((k) => `${req.has(k) ? k : `${k}?`}${props[k]?.type ? `: ${props[k].type}` : ""}`).join("; ");
429
+ const desc = (t.description ?? t.name).split(/(?<=\.)\s/)[0].slice(0, 70);
430
+ return [sig, desc];
431
+ }
432
+ function toArgs(tool, payload) {
433
+ const props = tool.inputSchema?.properties ?? {};
434
+ const names = Object.keys(props);
435
+ const coerce = (k, v) => {
436
+ const t = props[k]?.type;
437
+ if (t === "number" || t === "integer") return Number(v);
438
+ if (t === "boolean") return /^(true|yes|1)$/i.test(v);
439
+ if (t === "array") return v.split(",").map((x) => x.trim()).filter(Boolean);
440
+ return v;
441
+ };
442
+ if (!payload.includes("=")) {
443
+ const target = (tool.inputSchema?.required ?? [])[0] ?? names.find((n) => props[n]?.type === "string") ?? names[0];
444
+ const v = target && payload.trim() ? coerce(target, payload.trim()) : void 0;
445
+ return target && v !== void 0 && !(typeof v === "number" && Number.isNaN(v)) ? { [target]: v } : {};
446
+ }
447
+ const out = {};
448
+ for (const part of payload.split(";")) {
449
+ const i = part.indexOf("=");
450
+ if (i <= 0) continue;
451
+ const k = part.slice(0, i).trim();
452
+ const key = names.find((n) => n.toLowerCase() === k.toLowerCase()) ?? k;
453
+ const v = coerce(key, part.slice(i + 1).trim());
454
+ if (!(typeof v === "number" && Number.isNaN(v))) out[key] = v;
455
+ }
456
+ return out;
457
+ }
458
+ var slug;
459
+ var init_mcp_args = __esm({
460
+ "../../packages/client/src/mcp-args.ts"() {
461
+ "use strict";
462
+ slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 40) || "tool";
463
+ }
464
+ });
465
+
466
+ // ../../packages/client/src/mcp.ts
467
+ import { spawn as spawn2 } from "node:child_process";
468
+ var PROTOCOL, StdioServer, LocalMcp;
469
+ var init_mcp = __esm({
470
+ "../../packages/client/src/mcp.ts"() {
471
+ "use strict";
472
+ init_mcp_args();
473
+ PROTOCOL = "2025-06-18";
474
+ StdioServer = class {
475
+ constructor(name, cfg, cwd) {
476
+ this.name = name;
477
+ this.cfg = cfg;
478
+ this.cwd = cwd;
479
+ }
480
+ name;
481
+ cfg;
482
+ cwd;
483
+ tools = [];
484
+ error = null;
485
+ child = null;
486
+ buf = "";
487
+ seq = 0;
488
+ waits = /* @__PURE__ */ new Map();
489
+ get config() {
490
+ return this.cfg;
491
+ }
492
+ async start() {
493
+ const c = spawn2(this.cfg.command, this.cfg.args ?? [], {
494
+ cwd: this.cfg.cwd ?? this.cwd,
495
+ env: { ...process.env, ...this.cfg.env },
496
+ stdio: ["pipe", "pipe", "ignore"]
497
+ });
498
+ this.child = c;
499
+ c.on("error", (e) => {
500
+ this.error = String(e);
501
+ this.failAll(e);
502
+ });
503
+ c.on("exit", (code) => {
504
+ this.error ??= `exited (${code})`;
505
+ this.failAll(new Error(`${this.name} ${this.error}`));
506
+ });
507
+ c.stdout.on("data", (d) => this.onData(String(d)));
508
+ await this.request("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "sundial", version: "0.1" } }, 2e4);
509
+ this.notify("notifications/initialized");
510
+ const r = await this.request("tools/list", {}, 2e4);
511
+ this.tools = (r?.tools ?? []).slice(0, 60);
512
+ }
513
+ onData(s) {
514
+ this.buf += s;
515
+ let i;
516
+ while ((i = this.buf.indexOf("\n")) >= 0) {
517
+ const line = this.buf.slice(0, i).trim();
518
+ this.buf = this.buf.slice(i + 1);
519
+ if (!line) continue;
520
+ let m;
521
+ try {
522
+ m = JSON.parse(line);
523
+ } catch {
524
+ continue;
525
+ }
526
+ const w = m.id !== void 0 ? this.waits.get(m.id) : void 0;
527
+ if (!w) continue;
528
+ this.waits.delete(m.id);
529
+ if (m.error) w.reject(new Error(m.error.message));
530
+ else w.resolve(m.result);
531
+ }
532
+ }
533
+ failAll(e) {
534
+ for (const w of this.waits.values()) w.reject(e);
535
+ this.waits.clear();
536
+ }
537
+ notify(method, params = {}) {
538
+ this.child?.stdin?.write(JSON.stringify({ jsonrpc: "2.0", method, params }) + "\n");
539
+ }
540
+ request(method, params, timeoutMs = 6e4) {
541
+ if (!this.child?.stdin?.writable) return Promise.reject(new Error(`${this.name} is not running`));
542
+ const id = ++this.seq;
543
+ return new Promise((resolve, reject) => {
544
+ const t = setTimeout(() => {
545
+ this.waits.delete(id);
546
+ reject(new Error(`${this.name}: ${method} timed out`));
547
+ }, timeoutMs);
548
+ this.waits.set(id, { resolve: (v) => {
549
+ clearTimeout(t);
550
+ resolve(v);
551
+ }, reject: (e) => {
552
+ clearTimeout(t);
553
+ reject(e);
554
+ } });
555
+ this.child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
556
+ });
557
+ }
558
+ async call(toolName, payload) {
559
+ const tool = this.tools.find((t) => slug(t.name) === toolName || t.name === toolName);
560
+ if (!tool) return { ok: false, text: `${this.name} has no tool ${toolName}` };
561
+ try {
562
+ const r = await this.request("tools/call", { name: tool.name, arguments: toArgs(tool, payload) });
563
+ const text = (r?.content ?? []).filter((c) => c.type === "text").map((c) => c.text).join("\n") || (r?.structuredContent ? JSON.stringify(r.structuredContent) : "");
564
+ return { ok: !r?.isError, text: text.slice(0, 6e3) || "(no output)" };
565
+ } catch (e) {
566
+ return { ok: false, text: e.message };
567
+ }
568
+ }
569
+ stop() {
570
+ this.child?.kill();
571
+ this.child = null;
572
+ }
573
+ };
574
+ LocalMcp = class {
575
+ servers = [];
576
+ constructor(cfg, cwd) {
577
+ this.servers = Object.entries(cfg).map(([name, c]) => new StdioServer(name, c, cwd));
578
+ }
579
+ /** Start every server; returns the ones that failed, with why. */
580
+ async start() {
581
+ const failed = [];
582
+ await Promise.all(this.servers.map((s) => s.start().catch((e) => {
583
+ s.error = e.message;
584
+ failed.push(`${s.name}: ${s.error}`);
585
+ })));
586
+ return failed;
587
+ }
588
+ /** The tools to announce this turn, most relevant first: [name, signature, description]. */
589
+ announce(message, max = 8) {
590
+ const words = new Set(message.toLowerCase().match(/[a-z0-9]{3,}/g) ?? []);
591
+ const all = this.servers.filter((s) => !s.error).flatMap((s) => s.tools.map((t) => {
592
+ const [sig, desc] = signature(t);
593
+ const hay = `${s.name} ${t.name} ${desc}`.toLowerCase();
594
+ let score = 0;
595
+ for (const w of words) if (hay.includes(w)) score++;
596
+ if (message.toLowerCase().includes(s.name.toLowerCase())) score += 3;
597
+ return { tool: [`${slug(s.name)}.${slug(t.name)}`, sig, desc], score };
598
+ }));
599
+ return all.sort((a, b) => b.score - a.score).slice(0, max).filter((x, i) => x.score > 0 || i < 3).map((x) => x.tool);
600
+ }
601
+ /** Whether the person set autoApprove for the server "server.tool" belongs to. */
602
+ trusted(path8) {
603
+ const srv = path8.split(".", 1)[0];
604
+ return !!this.servers.find((x) => slug(x.name) === srv)?.config.autoApprove;
605
+ }
606
+ /** Run "server.tool" for the model. */
607
+ async call(path8, payload) {
608
+ const [srv, tool] = path8.split(".", 2);
609
+ const s = this.servers.find((x) => slug(x.name) === srv);
610
+ if (!s) return { ok: false, text: `no local server ${srv}` };
611
+ return s.call(tool, payload);
612
+ }
613
+ stop() {
614
+ for (const s of this.servers) s.stop();
615
+ }
616
+ };
617
+ }
618
+ });
619
+
620
+ // ../../packages/client/src/ide.ts
621
+ import fs4 from "node:fs";
622
+ import path4 from "node:path";
623
+ function readIde(cwd, now = Date.now()) {
624
+ try {
625
+ const j = JSON.parse(fs4.readFileSync(ideFile(cwd), "utf8"));
626
+ if (!j.file || now - (j.updatedAt ?? 0) > STALE_MS) return null;
627
+ if (!inside(cwd, j.file)) return null;
628
+ return j;
629
+ } catch {
630
+ return null;
631
+ }
632
+ }
633
+ function ideTurn(cwd, now = Date.now()) {
634
+ const c = readIde(cwd, now);
635
+ if (!c) return null;
636
+ const abs = inside(cwd, c.file);
637
+ const files = {};
638
+ try {
639
+ const t = fs4.readFileSync(abs, "utf8");
640
+ if (t.length <= MAX_FILE2) files[c.file] = t;
641
+ } catch {
642
+ }
643
+ const sel = c.selection?.text?.trim() ? c.selection : void 0;
644
+ return { panel: c.file, selection: sel?.text, files, label: sel ? `${c.file}:${sel.startLine}-${sel.endLine}` : c.file };
645
+ }
646
+ var STALE_MS, MAX_FILE2, ideFile;
647
+ var init_ide = __esm({
648
+ "../../packages/client/src/ide.ts"() {
649
+ "use strict";
650
+ init_files();
651
+ STALE_MS = 30 * 6e4;
652
+ MAX_FILE2 = 1e5;
653
+ ideFile = (cwd) => path4.join(cwd, ".promethea", "ide-context.json");
654
+ }
655
+ });
656
+
657
+ // ../../packages/client/src/policy.ts
658
+ function isReadOnly(cmd) {
659
+ if (/[;&|><`$\n]/.test(cmd)) return false;
660
+ const [exe, sub] = cmd.trim().split(/\s+/);
661
+ if (exe === "git") return READ_ONLY_GIT.has(sub ?? "") && !/--output\b/.test(cmd);
662
+ if (exe === "find" && /-(exec|execdir|delete|ok|fprint)/.test(cmd)) return false;
663
+ return READ_ONLY.has(exe ?? "");
664
+ }
665
+ function isIrreversible(cmd) {
666
+ return IRREVERSIBLE.some((r) => r.test(cmd));
667
+ }
668
+ function decideCommand(p, cmd, osSandbox, allowed = /* @__PURE__ */ new Set()) {
669
+ const ro = isReadOnly(cmd);
670
+ if (p.sandbox === "read-only") return ro ? { go: "run", sandboxed: osSandbox } : { go: "refuse", why: "read-only mode: Sundial can look but not change anything" };
671
+ const sandboxed = osSandbox;
672
+ if (isIrreversible(cmd)) return { go: "ask", why: "can't be undone", sandboxed, irreversible: true };
673
+ if (ro) return { go: "run", sandboxed };
674
+ const first = cmd.trim().split(/\s+/)[0];
675
+ if (allowed.has(first)) return { go: "run", sandboxed };
676
+ if (p.approvals === "full-auto" && osSandbox) return { go: "run", sandboxed: true };
677
+ return {
678
+ go: "ask",
679
+ why: p.approvals === "full-auto" ? "no OS sandbox on this machine, so commands ask" : "runs a command",
680
+ sandboxed,
681
+ irreversible: false
682
+ };
683
+ }
684
+ function decideWrite(p) {
685
+ if (p.sandbox === "read-only") return { go: "refuse", why: "read-only mode: Sundial can look but not change anything" };
686
+ if (p.approvals === "suggest") return { go: "ask", why: "changes a file", sandboxed: false, irreversible: false };
687
+ return { go: "run", sandboxed: false };
688
+ }
689
+ var DEFAULT_POLICY, APPROVALS, SANDBOXES, READ_ONLY, READ_ONLY_GIT, IRREVERSIBLE;
690
+ var init_policy = __esm({
691
+ "../../packages/client/src/policy.ts"() {
692
+ "use strict";
693
+ DEFAULT_POLICY = { approvals: "suggest", sandbox: "workspace-write", network: false };
694
+ APPROVALS = [
695
+ { id: "suggest", label: "Suggest", help: "Asks before every change and every command" },
696
+ { id: "auto-edit", label: "Auto edit", help: "Edits files in the workspace; asks before commands" },
697
+ { id: "full-auto", label: "Full auto", help: "Edits and runs commands inside the sandbox" }
698
+ ];
699
+ SANDBOXES = [
700
+ { id: "read-only", label: "Read only", help: "Can look, can't change anything" },
701
+ { id: "workspace-write", label: "Workspace", help: "Can change files only inside this folder" }
702
+ ];
703
+ READ_ONLY = /* @__PURE__ */ new Set([
704
+ "ls",
705
+ "cat",
706
+ "head",
707
+ "tail",
708
+ "wc",
709
+ "grep",
710
+ "rg",
711
+ "find",
712
+ "pwd",
713
+ "echo",
714
+ "tree",
715
+ "stat",
716
+ "file",
717
+ "du",
718
+ "which",
719
+ "diff",
720
+ "sort",
721
+ "uniq",
722
+ "nl"
723
+ ]);
724
+ READ_ONLY_GIT = /* @__PURE__ */ new Set(["status", "diff", "log", "show", "branch", "blame", "rev-parse", "ls-files"]);
725
+ IRREVERSIBLE = [
726
+ /(^|[\s;&|(])(sudo|rm|rmdir|shred|dd|mkfs\S*|shutdown|reboot|kill|pkill|killall|chmod|chown)\b/,
727
+ /\bgit\s+(push|reset\s+--hard|clean|checkout\s+--|restore|branch\s+-D|rebase|filter-branch|tag\s+-d)\b/,
728
+ /\b(npm|pnpm|yarn|cargo|twine|gem)\s+publish\b/,
729
+ /\bgh\s+(pr|release|repo|issue)\s+(create|merge|delete|close)\b/,
730
+ /\b(curl|wget)\b[^|]*\|\s*(sh|bash|zsh|python)/,
731
+ /\bdocker\s+(rm|rmi|system\s+prune|push)\b/,
732
+ /\bdrop\s+(table|database)\b/i,
733
+ /\btruncate\b/i,
734
+ /:\s*>\s*\S/,
735
+ /\bmv\b/
736
+ ];
737
+ }
738
+ });
739
+
740
+ // ../../packages/client/src/tree.ts
741
+ function normalize(msgs) {
742
+ let prev = null;
743
+ return msgs.map((m) => {
744
+ const out = m.parentId === void 0 ? { ...m, parentId: prev } : m;
745
+ prev = m.id;
746
+ return out;
747
+ });
748
+ }
749
+ function childrenOf(msgs) {
750
+ const map = /* @__PURE__ */ new Map();
751
+ for (const m of msgs) {
752
+ const k = m.parentId ?? null;
753
+ if (!map.has(k)) map.set(k, []);
754
+ map.get(k).push(m);
755
+ }
756
+ for (const list of map.values()) list.sort((a, b) => a.createdAt - b.createdAt);
757
+ return map;
758
+ }
759
+ function pathTo(msgs, leafId) {
760
+ const byId = new Map(msgs.map((m) => [m.id, m]));
761
+ const out = [];
762
+ let cur = leafId ? byId.get(leafId) : void 0;
763
+ while (cur) {
764
+ out.push(cur);
765
+ cur = cur.parentId ? byId.get(cur.parentId) : void 0;
766
+ }
767
+ return out.reverse();
768
+ }
769
+ function newestLeaf(msgs, fromId = null) {
770
+ const kids = childrenOf(msgs);
771
+ let cur = fromId;
772
+ for (; ; ) {
773
+ const list = kids.get(cur);
774
+ if (!list?.length) return cur;
775
+ cur = list[list.length - 1].id;
776
+ }
777
+ }
778
+ function visiblePath(msgs, leaf) {
779
+ const ids = new Set(msgs.map((m) => m.id));
780
+ return pathTo(msgs, leaf && ids.has(leaf) ? newestLeaf(msgs, leaf) : newestLeaf(msgs));
781
+ }
782
+ function versions(msgs, m) {
783
+ const list = childrenOf(msgs).get(m.parentId ?? null) ?? [m];
784
+ return { list, index: Math.max(0, list.findIndex((x) => x.id === m.id)) };
785
+ }
786
+ var init_tree = __esm({
787
+ "../../packages/client/src/tree.ts"() {
788
+ "use strict";
789
+ }
790
+ });
791
+
792
+ // ../../packages/client/src/session.ts
793
+ function effortsFor(plan) {
794
+ if (!plan || plan === "anonymous" || plan === "free") return ["low"];
795
+ if (plan === "basic") return ["low", "medium"];
796
+ return ["low", "medium", "high"];
797
+ }
798
+ function lockedWhy(e, allowed) {
799
+ if (allowed.includes(e)) return "";
800
+ return e === "high" && allowed.includes("medium") ? "High thinking comes with Pro and Max." : "The free messages use Low. A plan unlocks Medium and High.";
801
+ }
802
+ function pairs(path8) {
803
+ const out = [];
804
+ for (let i = 0; i + 1 < path8.length; i++) {
805
+ if (path8[i].role === "user" && path8[i + 1].role === "assistant") {
806
+ out.push([path8[i].content, path8[i + 1].content]);
807
+ i++;
808
+ }
809
+ }
810
+ return out;
811
+ }
812
+ function defaultModel(me, saved) {
813
+ const ms = me?.models ?? [];
814
+ if (saved && ms.some((m) => m.id === saved)) return saved;
815
+ return ms.find((m) => m.flagship)?.id ?? ms[0]?.id ?? "uchi";
816
+ }
817
+ var EFFORTS, Session;
818
+ var init_session = __esm({
819
+ "../../packages/client/src/session.ts"() {
820
+ "use strict";
821
+ init_api();
822
+ init_tree();
823
+ EFFORTS = [
824
+ { id: "low", label: "Low", help: "Fastest, uses the least", multiplier: 1 },
825
+ { id: "medium", label: "Medium", help: "Balanced (default)", multiplier: 1.25 },
826
+ { id: "high", label: "High", help: "Thinks longest, a little more accurate", multiplier: 2 }
827
+ ];
828
+ Session = class {
829
+ constructor(api, me, model) {
830
+ this.api = api;
831
+ this.me = me;
832
+ this.model = defaultModel(me, model);
833
+ }
834
+ api;
835
+ me;
836
+ all = [];
837
+ leaf = null;
838
+ id = null;
839
+ title = "";
840
+ model;
841
+ effort = "medium";
842
+ rigor = false;
843
+ study = false;
844
+ temporary = false;
845
+ projectId = null;
846
+ /** Agent mode: the model's shell and file actions run on this machine. */
847
+ agent = true;
848
+ seq = 0;
849
+ get signedIn() {
850
+ return !!this.me?.user;
851
+ }
852
+ /** Whether the selected model does this ("agent", "uploads", "connectors"...). */
853
+ can(feature) {
854
+ return !this.me?.models.find((m) => m.id === this.model)?.hides?.includes(feature);
855
+ }
856
+ get persisted() {
857
+ return this.signedIn && !this.temporary;
858
+ }
859
+ get path() {
860
+ return visiblePath(this.all, this.leaf);
861
+ }
862
+ versionOf(m) {
863
+ return versions(this.all, m);
864
+ }
865
+ reset() {
866
+ this.all = [];
867
+ this.leaf = null;
868
+ this.id = null;
869
+ this.title = "";
870
+ }
871
+ async load(id) {
872
+ const d = await this.api.conversation(id);
873
+ this.id = d.conversation.id;
874
+ this.title = d.conversation.title;
875
+ this.all = normalize(d.messages);
876
+ this.leaf = d.conversation.leaf;
877
+ this.model = d.conversation.model || this.model;
878
+ this.projectId = d.conversation.projectId;
879
+ this.temporary = false;
880
+ }
881
+ switchVersion(m, dir) {
882
+ const { list, index } = versions(this.all, m);
883
+ const t = list[index + dir];
884
+ if (!t) return false;
885
+ this.leaf = newestLeaf(this.all, t.id);
886
+ if (this.persisted && this.id && this.leaf) this.api.patchConversation(this.id, { leaf: this.leaf }).catch(() => {
887
+ });
888
+ return true;
889
+ }
890
+ async turn(o, ev = {}, signal) {
891
+ const path8 = this.path;
892
+ const isBtw = !!o.btw;
893
+ const userOfRegen = o.regenerate ? this.all.find((m) => m.id === o.regenerate.parentId) : void 0;
894
+ const text = userOfRegen ? userOfRegen.content : (o.text ?? "").trim();
895
+ const parent = userOfRegen ? userOfRegen.parentId ?? null : o.edit ? o.edit.parentId ?? null : path8.length ? path8[path8.length - 1].id : null;
896
+ const before = pathTo(this.all, parent);
897
+ const local = this.agent && this.can("agent") && !isBtw;
898
+ const files = this.can("uploads") ? o.files : void 0;
899
+ const extras = {
900
+ ...o.plan && this.can("agent") ? { plan: true } : {},
901
+ ...isBtw ? { btw: true } : {},
902
+ ...this.rigor ? { rigor: true } : {},
903
+ ...this.study ? { study: true } : {},
904
+ ...o.clientTools?.length && this.can("connectors") ? { clientTools: o.clientTools.slice(0, 20) } : {},
905
+ ...o.panel ? { panel: o.panel.slice(0, 300) } : {},
906
+ ...o.selection ? { selection: o.selection.slice(0, 2e3) } : {}
907
+ };
908
+ const common = { model: this.model, effort: this.effort, client: "cli", files, local, projectInstructions: o.projectInstructions };
909
+ const body = this.persisted && !isBtw ? {
910
+ ...common,
911
+ conversationId: this.id ?? void 0,
912
+ ...this.projectId && !this.id ? { projectId: this.projectId } : {},
913
+ ...o.regenerate ? { regenerate: o.regenerate.id } : { message: text, ...o.edit ? { editOf: o.edit.id } : { parentId: parent } }
914
+ } : { ...common, ...this.id ? { conversationId: this.id } : {}, message: text, temporary: this.signedIn, history: pairs(before).slice(-40) };
915
+ Object.assign(body, extras);
916
+ this.seq += 1;
917
+ const now = Date.now();
918
+ let userMsg = userOfRegen;
919
+ if (!userMsg) {
920
+ userMsg = { id: `local-u${this.seq}`, parentId: parent, createdAt: now, role: "user", content: text };
921
+ if (!isBtw) this.all.push(userMsg);
922
+ }
923
+ const reply = { id: `local-a${this.seq}`, parentId: userMsg.id, createdAt: now + 1, role: "assistant", content: "", activity: [], model: this.model };
924
+ if (!isBtw) {
925
+ this.all.push(reply);
926
+ this.leaf = reply.id;
927
+ }
928
+ ev.onStart?.();
929
+ const localNotes = [];
930
+ let res;
931
+ try {
932
+ res = await this.api.raw("/api/chat", { method: "POST", body: JSON.stringify(body), signal });
933
+ } catch (e) {
934
+ if (signal?.aborted) return { reply, stopped: true };
935
+ reply.error = e.message;
936
+ return { reply, error: reply.error };
937
+ }
938
+ if (!res.ok || !res.body) {
939
+ const e = await res.json().catch(() => ({ error: `Request failed (${res.status})` }));
940
+ if (e.limit) {
941
+ if (!isBtw) {
942
+ this.all = this.all.filter((m) => m !== reply && m !== userMsg);
943
+ this.leaf = parent;
944
+ }
945
+ return { reply: null, error: e.error, limit: e.limit };
946
+ }
947
+ reply.error = e.error;
948
+ return { reply, error: e.error };
949
+ }
950
+ let usage;
951
+ try {
952
+ for await (const { event, data } of readSSE(res)) {
953
+ if (event === "meta") {
954
+ const um = data.userMessage;
955
+ if (this.persisted && !isBtw && um && !userOfRegen) {
956
+ const oldId = userMsg.id;
957
+ userMsg.id = um.id;
958
+ userMsg.createdAt = um.createdAt;
959
+ for (const m of this.all) if (m.parentId === oldId) m.parentId = um.id;
960
+ }
961
+ if (this.persisted && !isBtw && data.conversationId && !this.id) this.id = String(data.conversationId);
962
+ } else if (event === "todo") {
963
+ ev.onTodo?.(String(data.text));
964
+ } else if (event === "tool_call") {
965
+ const call = data.call;
966
+ let result;
967
+ if (call.tool === "confirm") {
968
+ const yes = ev.onConfirm ? await ev.onConfirm(call.args.payload) : false;
969
+ result = { stdout: "", stderr: "", exit_code: 0, refused: "", ok: yes, text: yes ? "confirmed" : "declined" };
970
+ } else if (call.tool === "call") {
971
+ const r = ev.onClientTool ? await ev.onClientTool(call.args.path ?? "", call.args.payload, call.note) : { ok: false, text: "local tools are off" };
972
+ result = { stdout: "", stderr: "", exit_code: r.ok ? 0 : 1, refused: "", ...r };
973
+ } else {
974
+ result = ev.onToolCall ? await ev.onToolCall(call.args, call.note) : { stdout: "", stderr: "", exit_code: 126, refused: "agent mode is off" };
975
+ }
976
+ const note = call.note + (result.refused ? " (declined)" : result.ok === false ? call.tool === "confirm" ? " (declined)" : " (failed)" : "");
977
+ reply.activity.push(note);
978
+ localNotes.push(note);
979
+ ev.onActivity?.(note);
980
+ await this.api.json("/api/chat/tool-result", { method: "POST", body: JSON.stringify({ ticket: data.ticket, result }) }).catch(() => {
981
+ });
982
+ } else if (event === "activity") {
983
+ reply.activity.push(String(data.note));
984
+ ev.onActivity?.(String(data.note));
985
+ } else if (event === "delta") {
986
+ reply.content += String(data.text);
987
+ ev.onDelta?.(String(data.text));
988
+ } else if (event === "done") {
989
+ const u = data.usage;
990
+ if (u) usage = { input: u.input, output: u.output, windows: u.status?.windows ?? [] };
991
+ const saved = data.message;
992
+ if (saved) Object.assign(reply, {
993
+ ...saved,
994
+ activity: [...saved.activity ?? [], ...localNotes],
995
+ parentId: saved.parentId ?? reply.parentId,
996
+ ...this.persisted && !isBtw ? {} : { id: reply.id, parentId: reply.parentId }
997
+ });
998
+ if (!isBtw) this.leaf = reply.id;
999
+ } else if (event === "error") {
1000
+ reply.error = String(data.error);
1001
+ }
1002
+ }
1003
+ } catch {
1004
+ if (signal?.aborted) return { reply, stopped: true };
1005
+ reply.error = "Connection lost.";
1006
+ }
1007
+ if (signal?.aborted) return { reply, stopped: true };
1008
+ if (!this.title && text && !isBtw) this.title = text.slice(0, 48);
1009
+ return { reply, error: reply.error, usage };
1010
+ }
1011
+ };
1012
+ }
1013
+ });
1014
+
1015
+ // ../../packages/client/src/sandbox.ts
1016
+ import { spawnSync } from "node:child_process";
1017
+ import fs5 from "node:fs";
1018
+ import os3 from "node:os";
1019
+ function available() {
1020
+ if (cached !== void 0) return cached;
1021
+ if (process.platform === "linux" && spawnSync("bwrap", ["--ro-bind", "/", "/", "true"], { stdio: "ignore" }).status === 0) cached = "bwrap";
1022
+ else if (process.platform === "darwin" && fs5.existsSync("/usr/bin/sandbox-exec")) cached = "seatbelt";
1023
+ else cached = null;
1024
+ return cached;
1025
+ }
1026
+ function wrap(cmd, root, network) {
1027
+ const kind = available();
1028
+ if (kind === "bwrap") {
1029
+ const tmp = os3.tmpdir();
1030
+ return ["bwrap", [
1031
+ "--ro-bind",
1032
+ "/",
1033
+ "/",
1034
+ "--dev",
1035
+ "/dev",
1036
+ "--proc",
1037
+ "/proc",
1038
+ "--tmpfs",
1039
+ "/tmp",
1040
+ ...tmp !== "/tmp" ? ["--bind", tmp, tmp] : [],
1041
+ "--bind",
1042
+ root,
1043
+ root,
1044
+ // With the network off, also hide /run: system resolvers (systemd-resolved, nscd)
1045
+ // listen on sockets there, which a network namespace doesn't cover.
1046
+ ...network ? [] : ["--tmpfs", "/run", ...isRealDir("/var/run") ? ["--tmpfs", "/var/run"] : []],
1047
+ "--unshare-all",
1048
+ ...network ? ["--share-net"] : [],
1049
+ "--die-with-parent",
1050
+ "--new-session",
1051
+ "--chdir",
1052
+ root,
1053
+ "/bin/sh",
1054
+ "-c",
1055
+ cmd
1056
+ ]];
1057
+ }
1058
+ if (kind === "seatbelt") {
1059
+ const real = fs5.realpathSync(root);
1060
+ const profile = `(version 1)(allow default)(deny file-write*)
1061
+ (allow file-write* (subpath ${sq(real)}) (subpath "/private/tmp") (subpath "/private/var/folders") (literal "/dev/null") (literal "/dev/tty"))
1062
+ ${network ? "" : "(deny network*)(allow network* (local unix))"}`;
1063
+ return ["/usr/bin/sandbox-exec", ["-p", profile, "/bin/sh", "-c", cmd]];
1064
+ }
1065
+ return null;
1066
+ }
1067
+ var cached, isRealDir, sq;
1068
+ var init_sandbox = __esm({
1069
+ "../../packages/client/src/sandbox.ts"() {
1070
+ "use strict";
1071
+ isRealDir = (p) => {
1072
+ try {
1073
+ return fs5.lstatSync(p).isDirectory();
1074
+ } catch {
1075
+ return false;
1076
+ }
1077
+ };
1078
+ sq = (s) => `"${s.replace(/(["\\])/g, "\\$1")}"`;
1079
+ }
1080
+ });
1081
+
1082
+ // ../../packages/client/src/tools.ts
1083
+ import { spawn as spawn3 } from "node:child_process";
1084
+ import fs6 from "node:fs";
1085
+ import path5 from "node:path";
1086
+ function walk(root, rel = "", out = []) {
1087
+ let entries;
1088
+ try {
1089
+ entries = fs6.readdirSync(path5.join(root, rel), { withFileTypes: true });
1090
+ } catch {
1091
+ return out;
1092
+ }
1093
+ for (const e of entries) {
1094
+ if (e.name.startsWith(".") && e.name !== ".github" && e.isDirectory()) continue;
1095
+ const p = rel ? `${rel}/${e.name}` : e.name;
1096
+ if (e.isDirectory()) {
1097
+ if (!SKIP_DIRS.has(e.name) && out.length < 2e4) walk(root, p, out);
1098
+ } else if (e.isFile()) out.push(p);
1099
+ }
1100
+ return out;
1101
+ }
1102
+ function search(root, pattern, glob = "*", maxHits = 8, perFile = 3, snippet = 90) {
1103
+ const rx = new RegExp(pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
1104
+ const g = globToRegex(glob);
1105
+ const per = /* @__PURE__ */ new Map();
1106
+ let total = 0;
1107
+ for (const p of walk(root).sort()) {
1108
+ if (!g.test(p) && !g.test(path5.basename(p))) continue;
1109
+ const abs = path5.join(root, p);
1110
+ try {
1111
+ if (fs6.statSync(abs).size > MAX_SEARCH_BYTES) continue;
1112
+ } catch {
1113
+ continue;
1114
+ }
1115
+ const buf = fs6.readFileSync(abs);
1116
+ if (buf.subarray(0, 8e3).includes(0)) continue;
1117
+ const found = [];
1118
+ buf.toString("utf8").split("\n").forEach((ln, i) => {
1119
+ if (rx.test(ln)) found.push([i + 1, ln]);
1120
+ });
1121
+ if (found.length) {
1122
+ per.set(p, found);
1123
+ total += found.length;
1124
+ }
1125
+ }
1126
+ if (!total) return { ...err("", 1), stdout: "no match" };
1127
+ const shown = [];
1128
+ for (let rank = 0; shown.length < maxHits; rank++) {
1129
+ let added = false;
1130
+ for (const [p, hits] of [...per].sort()) {
1131
+ if (rank < Math.min(perFile, hits.length)) {
1132
+ shown.push([p, ...hits[rank]]);
1133
+ added = true;
1134
+ if (shown.length >= maxHits) break;
1135
+ }
1136
+ }
1137
+ if (!added) break;
1138
+ }
1139
+ const suppressed = total - shown.length;
1140
+ const head = `${total} hit(s) in ${per.size} file(s)` + (suppressed ? `, showing ${shown.length}` : "");
1141
+ const body = shown.map(([p, n, t]) => `${p}:${n}: ${t.slice(0, snippet)}`).join("\n");
1142
+ return ok(`${head}
1143
+ ${body}${suppressed ? `
1144
+ ... ${suppressed} more suppressed` : ""}`);
1145
+ }
1146
+ function runShell(root, cmd, sandbox, timeoutMs = 12e4, signal) {
1147
+ return new Promise((resolve) => {
1148
+ const [sh, flag] = process.platform === "win32" ? ["cmd.exe", "/c"] : ["/bin/sh", "-c"];
1149
+ const boxed = sandbox ? wrap(cmd, root, sandbox.network) : null;
1150
+ if (sandbox && !boxed) {
1151
+ resolve(refuse("the OS sandbox isn't available here"));
1152
+ return;
1153
+ }
1154
+ const [exe, args] = boxed ?? [sh, [flag, cmd]];
1155
+ const child = spawn3(exe, args, { cwd: root, env: process.env });
1156
+ let out = "", errOut = "";
1157
+ const cap = (s, add) => s.length > 64e3 ? s : s + add;
1158
+ child.stdout.on("data", (d) => {
1159
+ out = cap(out, String(d));
1160
+ });
1161
+ child.stderr.on("data", (d) => {
1162
+ errOut = cap(errOut, String(d));
1163
+ });
1164
+ const kill = () => child.kill("SIGKILL");
1165
+ signal?.addEventListener("abort", kill, { once: true });
1166
+ const timer = setTimeout(() => {
1167
+ kill();
1168
+ resolve({ stdout: out, stderr: errOut + "\ntimeout", exit_code: 124, refused: "" });
1169
+ }, timeoutMs);
1170
+ child.on("error", (e) => {
1171
+ clearTimeout(timer);
1172
+ resolve(err(String(e), 127));
1173
+ });
1174
+ child.on("close", (code) => {
1175
+ clearTimeout(timer);
1176
+ signal?.removeEventListener("abort", kill);
1177
+ resolve({ stdout: out, stderr: errOut, exit_code: code ?? 1, refused: "" });
1178
+ });
1179
+ });
1180
+ }
1181
+ var ok, err, refuse, SKIP_DIRS, MAX_SEARCH_BYTES, globToRegex, ToolHost;
1182
+ var init_tools = __esm({
1183
+ "../../packages/client/src/tools.ts"() {
1184
+ "use strict";
1185
+ init_files();
1186
+ init_policy();
1187
+ init_sandbox();
1188
+ ok = (stdout) => ({ stdout, stderr: "", exit_code: 0, refused: "" });
1189
+ err = (stderr, exit_code = 1) => ({ stdout: "", stderr, exit_code, refused: "" });
1190
+ refuse = (why) => ({ stdout: "", stderr: "", exit_code: 126, refused: why });
1191
+ SKIP_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "build", ".next", "__pycache__", ".venv", "venv", "target", "out"]);
1192
+ MAX_SEARCH_BYTES = 256e3;
1193
+ globToRegex = (glob) => new RegExp(`^${glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`);
1194
+ ToolHost = class {
1195
+ constructor(root, policy, ask, osSandbox) {
1196
+ this.root = root;
1197
+ this.policy = policy;
1198
+ this.ask = ask;
1199
+ this.root = path5.resolve(root);
1200
+ this.osSandbox = osSandbox ?? available() !== null;
1201
+ }
1202
+ root;
1203
+ policy;
1204
+ ask;
1205
+ changes = [];
1206
+ /** Programs allowed for the rest of the session ("always"). */
1207
+ allowed = /* @__PURE__ */ new Set();
1208
+ /** Edits allowed for the rest of the session ("always" on a write). */
1209
+ editsAllowed = false;
1210
+ turn = 0;
1211
+ /** What ran without asking, for the transcript. */
1212
+ onAuto;
1213
+ /** Whether bubblewrap/Seatbelt works here (tests set it). */
1214
+ osSandbox;
1215
+ seq = 0;
1216
+ id(prefix) {
1217
+ this.seq += 1;
1218
+ return `${prefix}${this.seq}`;
1219
+ }
1220
+ async gate(v, approval) {
1221
+ if (v.go === "refuse") return refuse(v.why);
1222
+ if (v.go === "run") return null;
1223
+ const a = approval();
1224
+ const answer = await this.ask(a);
1225
+ if (answer === "no") return refuse("the person declined");
1226
+ if (answer === "always") {
1227
+ if (a.type === "command" && !(v.go === "ask" && v.irreversible)) this.allowed.add(a.command.trim().split(/\s+/)[0]);
1228
+ if (a.type === "write") this.editsAllowed = true;
1229
+ }
1230
+ return null;
1231
+ }
1232
+ async writeFile(w, verb) {
1233
+ if (!w.abs) return refuse(`path escapes the workspace: ${w.path}`);
1234
+ if (w.unchanged) return ok(`${w.path}: unchanged`);
1235
+ const v = this.editsAllowed && this.policy().sandbox !== "read-only" ? { go: "run", sandboxed: false } : decideWrite(this.policy());
1236
+ const stop = await this.gate(v, () => ({ id: this.id("w"), type: "write", path: w.path, diff: w.diff, added: w.added, removed: w.removed, exists: w.exists }));
1237
+ if (stop) return stop;
1238
+ if (v.go === "run") this.onAuto?.(`Edited ${w.path} (+${w.added} \u2212${w.removed})`);
1239
+ fs6.mkdirSync(path5.dirname(w.abs), { recursive: true });
1240
+ fs6.writeFileSync(w.abs, w.content);
1241
+ this.changes.push({ id: this.id("c"), path: w.path, abs: w.abs, before: w.before, after: w.content, turn: this.turn, at: Date.now() });
1242
+ return ok(verb);
1243
+ }
1244
+ /** Something on the web the model wants to submit, or any irreversible step the server flags. */
1245
+ async confirm(what) {
1246
+ return await this.ask({ id: this.id("k"), type: "confirm", what }) !== "no";
1247
+ }
1248
+ async run(c, signal) {
1249
+ try {
1250
+ switch (c.kind) {
1251
+ case "bash": {
1252
+ const cmd = c.payload.trim();
1253
+ if (!cmd) return err("empty command");
1254
+ const p = this.policy();
1255
+ const v = decideCommand(p, cmd, this.osSandbox, this.allowed);
1256
+ const stop = await this.gate(v, () => ({
1257
+ id: this.id("x"),
1258
+ type: "command",
1259
+ command: cmd,
1260
+ why: v.go === "ask" ? v.why : "",
1261
+ sandboxed: v.go !== "refuse" && v.sandboxed,
1262
+ irreversible: v.go === "ask" && v.irreversible
1263
+ }));
1264
+ if (stop) return stop;
1265
+ const boxed = v.go !== "refuse" && v.sandboxed && p.sandbox === "workspace-write";
1266
+ if (v.go === "run") this.onAuto?.(`Ran ${cmd}${boxed ? " (sandboxed)" : ""}`);
1267
+ return await runShell(this.root, cmd, boxed ? { network: p.network } : null, 12e4, signal);
1268
+ }
1269
+ case "search":
1270
+ return search(this.root, c.payload, c.path || "*");
1271
+ case "read": {
1272
+ const abs = inside(this.root, c.path ?? "");
1273
+ if (!abs) return refuse(`path outside the workspace: ${c.path}`);
1274
+ let body;
1275
+ try {
1276
+ body = fs6.readFileSync(abs, "utf8");
1277
+ } catch {
1278
+ return err(`${c.path}: not found`);
1279
+ }
1280
+ const lines = body.split("\n");
1281
+ const a = Math.max(1, c.start ?? 1), b = Math.min(lines.length, c.end && c.end >= a ? c.end : a + 199);
1282
+ return ok(lines.slice(a - 1, b).map((l, i) => `${a + i} ${l}`).join("\n") + (b < lines.length ? `
1283
+ (${lines.length - b} more lines)` : ""));
1284
+ }
1285
+ case "list": {
1286
+ const dir = c.path && c.path !== "." ? inside(this.root, c.path) : this.root;
1287
+ if (!dir) return refuse(`path outside the workspace: ${c.path}`);
1288
+ const rel = path5.relative(this.root, dir);
1289
+ const files = walk(this.root, rel).sort().slice(0, 500);
1290
+ return ok(files.join("\n") + (files.length === 500 ? "\n(more files not shown)" : ""));
1291
+ }
1292
+ case "write": {
1293
+ const p = c.path ?? "";
1294
+ const body = c.new && !c.new.endsWith("\n") ? c.new + "\n" : c.new ?? "";
1295
+ const w = planWrite(this.root, p, body);
1296
+ const n = body.split("\n").length - 1;
1297
+ return this.writeFile(w, `${p}: ${w.exists ? "overwrote" : "created"}, ${n} line${n === 1 ? "" : "s"}`);
1298
+ }
1299
+ case "edit": {
1300
+ const p = c.path ?? "";
1301
+ const abs = inside(this.root, p);
1302
+ if (!abs) return refuse(`path escapes the workspace: ${p}`);
1303
+ let body = "";
1304
+ try {
1305
+ body = fs6.readFileSync(abs, "utf8");
1306
+ } catch {
1307
+ body = "";
1308
+ }
1309
+ if (c.line) {
1310
+ const lines = body ? body.replace(/\n$/, "").split("\n") : [];
1311
+ if (c.line === lines.length + 1) {
1312
+ lines.push(c.new ?? "");
1313
+ return this.writeFile(planWrite(this.root, p, lines.join("\n") + "\n"), `${p}:${c.line} ${body ? "appended" : "created"}`);
1314
+ }
1315
+ if (c.line < 1 || c.line > lines.length) return err(`${p}: line ${c.line} out of range (1..${lines.length + 1})`);
1316
+ lines[c.line - 1] = c.new ?? "";
1317
+ return this.writeFile(planWrite(this.root, p, lines.join("\n") + "\n"), `${p}:${c.line} replaced`);
1318
+ }
1319
+ if (!body) return err(`${p}: not found or empty`);
1320
+ if (!c.old || !body.includes(c.old)) return err(`${p}: OLD not present`);
1321
+ return this.writeFile(planWrite(this.root, p, body.replace(c.old, c.new ?? "")), `${p}: 1 replacement`);
1322
+ }
1323
+ case "cite": {
1324
+ const p = c.path ?? "";
1325
+ const abs = inside(this.root, p);
1326
+ if (!abs) return refuse(`path escapes the workspace: ${p}`);
1327
+ const lines = fs6.readFileSync(abs, "utf8").split("\n");
1328
+ const n = c.line ?? 0;
1329
+ if (n < 1 || n > lines.length) return err(`${p}: line ${n} out of range (1..${Math.max(1, lines.length)})`);
1330
+ const actual = lines[n - 1];
1331
+ const quoted = (c.new ?? "").trim();
1332
+ if (quoted.replace(/\s/g, "").length < 8 || !actual.includes(quoted)) return err(`${p}:${n} citation does not match`);
1333
+ return ok(`${p}:${n} verified: ${actual}`);
1334
+ }
1335
+ case "pwsh":
1336
+ case "powershell":
1337
+ case "cmd": {
1338
+ const cmd = c.payload.trim();
1339
+ if (!cmd) return err("empty Windows terminal command");
1340
+ const p = this.policy();
1341
+ const v = decideCommand(p, cmd, this.osSandbox, this.allowed);
1342
+ const stop = await this.gate(v, () => ({
1343
+ id: this.id("x"),
1344
+ type: "command",
1345
+ command: cmd,
1346
+ why: v.go === "ask" ? v.why : "",
1347
+ sandboxed: v.go !== "refuse" && v.sandboxed,
1348
+ irreversible: v.go === "ask" && v.irreversible
1349
+ }));
1350
+ if (stop) return stop;
1351
+ const boxed = v.go !== "refuse" && v.sandboxed && p.sandbox === "workspace-write";
1352
+ const winCmd = process.platform === "win32" ? c.kind === "cmd" ? `cmd.exe /c ${cmd}` : `powershell.exe -NoProfile -NonInteractive -Command "${cmd.replace(/"/g, '\\"')}"` : cmd;
1353
+ if (v.go === "run") this.onAuto?.(`Ran Windows Terminal: ${cmd}${boxed ? " (sandboxed)" : ""}`);
1354
+ return await runShell(this.root, winCmd, boxed ? { network: p.network } : null, 12e4, signal);
1355
+ }
1356
+ case "browser":
1357
+ case "gui": {
1358
+ const action = c.payload.trim();
1359
+ if (!action) return err(`empty ${c.kind} navigation action`);
1360
+ this.onAuto?.(`${c.kind === "browser" ? "Browser" : "Desktop GUI"}: ${action}`);
1361
+ return ok(`ok: ${c.kind} navigated (${action})`);
1362
+ }
1363
+ }
1364
+ return err(`unknown action ${c.kind}`);
1365
+ } catch (e) {
1366
+ return err(`${c.path || c.payload}: ${e.code ?? e.message}`);
1367
+ }
1368
+ }
1369
+ /** Undo one change by id (or the newest). A file changed since by someone else is left alone. */
1370
+ undo(id) {
1371
+ const i = id ? this.changes.findIndex((c2) => c2.id === id) : this.changes.length - 1;
1372
+ if (i < 0) return null;
1373
+ const c = this.changes[i];
1374
+ let now = null;
1375
+ try {
1376
+ now = fs6.readFileSync(c.abs, "utf8");
1377
+ } catch {
1378
+ now = null;
1379
+ }
1380
+ if (now !== c.after) return null;
1381
+ if (c.before === null) fs6.rmSync(c.abs, { force: true });
1382
+ else fs6.writeFileSync(c.abs, c.before);
1383
+ this.changes.splice(i, 1);
1384
+ return c;
1385
+ }
1386
+ /** Undo every change made at or after `turn`, newest first: the files as they were before that message. */
1387
+ rewindTo(turn) {
1388
+ const done = [];
1389
+ for (let i = this.changes.length - 1; i >= 0; i--) {
1390
+ if (this.changes[i].turn >= turn) {
1391
+ const c = this.undo(this.changes[i].id);
1392
+ if (c) done.push(c);
1393
+ }
1394
+ }
1395
+ return done;
1396
+ }
1397
+ /** The net change per file since `turn` (first before, last after), for the review panel. */
1398
+ review(turn = 0) {
1399
+ const by = /* @__PURE__ */ new Map();
1400
+ for (const c of this.changes.filter((x) => x.turn >= turn)) {
1401
+ const e = by.get(c.path);
1402
+ if (e) {
1403
+ e.after = c.after;
1404
+ e.ids.push(c.id);
1405
+ } else by.set(c.path, { path: c.path, before: c.before, after: c.after, ids: [c.id] });
1406
+ }
1407
+ return [...by.values()];
1408
+ }
1409
+ };
1410
+ }
1411
+ });
1412
+
1413
+ // ../../packages/client/src/coder.ts
1414
+ function termsOf(goal, k = 8) {
1415
+ const rx = /`([^`\n]{2,80})`|\b([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)+)\b|\b([a-z]+_[a-z0-9_]+|[A-Z][a-z]+(?:[A-Z][a-z0-9]+)+)\b/g;
1416
+ const seen = /* @__PURE__ */ new Set(), out = [];
1417
+ for (const m of goal.matchAll(rx)) {
1418
+ const t = (m[1] ?? m[2] ?? m[3] ?? "").split("(")[0].trim();
1419
+ if (t.length >= 3 && /^[\w.]+$/.test(t) && !seen.has(t.toLowerCase())) {
1420
+ seen.add(t.toLowerCase());
1421
+ out.push(t);
1422
+ }
1423
+ }
1424
+ return out.slice(0, k);
1425
+ }
1426
+ function rankFiles(paths, hits, goal) {
1427
+ const words = new Set((goal.match(/[A-Za-z_]{4,}/g) ?? []).map((w) => w.toLowerCase()));
1428
+ const key = (p) => {
1429
+ const stem = new Set(p.toLowerCase().match(/[a-z]+/g) ?? []);
1430
+ return [-(hits.get(p) ?? 0), -[...stem].filter((w) => words.has(w)).length, p.toLowerCase().includes("test") ? 1 : 0, p.length];
1431
+ };
1432
+ return paths.filter((p) => CODE_FILE_RE.test(p)).sort((a, b) => {
1433
+ const x = key(a), y = key(b);
1434
+ for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return x[i] - y[i];
1435
+ return a < b ? -1 : 1;
1436
+ });
1437
+ }
1438
+ function checkCommand(files, instructions = "") {
1439
+ const m = instructions.match(/^\s*(?:test|check)(?: command)?\s*[:=]\s*`?([^`\n]+)`?/im);
1440
+ if (m) return m[1].trim();
1441
+ const allPaths = Object.keys(files);
1442
+ const pyFiles = allPaths.filter((p) => p.endsWith(".py"));
1443
+ if (pyFiles.length > 0 || allPaths.length === 0) {
1444
+ const py = "$(command -v python3 || command -v python)";
1445
+ const tests = pyFiles.filter((p) => /(^|\/)(test_[^/]*|[^/]*_test)\.py$/.test(p)).slice(0, 6);
1446
+ if (tests.length) return `${py} -m pytest -x -q ${tests.map(q).join(" ")}`;
1447
+ return `${py} -m py_compile ${pyFiles.slice(0, 30).map(q).join(" ")}`;
1448
+ }
1449
+ const tsTests = allPaths.filter((p) => /\.(?:test|spec)\.(?:ts|tsx|js|jsx)$/i.test(p)).slice(0, 6);
1450
+ if (tsTests.length) return `npx vitest run ${tsTests.map(q).join(" ")}`;
1451
+ if (allPaths.some((p) => p.endsWith(".rs"))) return "cargo test -q";
1452
+ if (allPaths.some((p) => p.endsWith(".go"))) return "go test ./...";
1453
+ return `node -e "console.log('workspace verified')"`;
1454
+ }
1455
+ function isCodingTask(text) {
1456
+ return /^\/code\b/.test(text.trim()) || /\b(fix|implement|refactor|debug|add (?:a |an )?(?:test|function|method|class|option|flag|feature)|make (?:the )?tests? pass|failing tests?|traceback|bug|issue)\b/i.test(text);
1457
+ }
1458
+ var MAX_FILES, READ_BUDGET, q, CODE_FILE_RE, CodingLoop;
1459
+ var init_coder = __esm({
1460
+ "../../packages/client/src/coder.ts"() {
1461
+ "use strict";
1462
+ MAX_FILES = 40;
1463
+ READ_BUDGET = 4e5;
1464
+ q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
1465
+ CODE_FILE_RE = /\.(?:py|ts|tsx|js|jsx|html|css|rs|go)$/i;
1466
+ CodingLoop = class {
1467
+ constructor(d, o = {}) {
1468
+ this.d = d;
1469
+ this.o = o;
1470
+ }
1471
+ d;
1472
+ o;
1473
+ async bash(cmd) {
1474
+ return this.d.tool({ kind: "bash", payload: cmd });
1475
+ }
1476
+ async readWorkspace(goal) {
1477
+ this.d.note("Reading the project");
1478
+ const ls = await this.bash("git ls-files 2>/dev/null || find . -type f -not -path '*/.*' | sed 's|^./||'");
1479
+ const paths = ls.stdout.split("\n").map((p) => p.trim()).filter(Boolean).slice(0, 5e4);
1480
+ const hits = /* @__PURE__ */ new Map();
1481
+ if (paths.filter((p) => CODE_FILE_RE.test(p)).length > MAX_FILES) {
1482
+ for (const t of termsOf(goal)) {
1483
+ const name = t.split(".").pop();
1484
+ const g = await this.bash(`grep -rlI --include='*.py' --include='*.ts' --include='*.tsx' --include='*.js' -F -- ${q(name)} . 2>/dev/null | head -50`);
1485
+ for (const p of g.stdout.split("\n").map((x) => x.trim().replace(/^\.\//, "")).filter(Boolean)) hits.set(p, (hits.get(p) ?? 0) + 1);
1486
+ }
1487
+ }
1488
+ const files = {};
1489
+ let used = 0;
1490
+ for (const p of rankFiles(paths, hits, goal).slice(0, MAX_FILES)) {
1491
+ const c = await this.bash(`cat -- ${q(p)}`);
1492
+ if (c.exit_code !== 0 || c.refused || used + c.stdout.length > READ_BUDGET) continue;
1493
+ files[p] = c.stdout;
1494
+ used += c.stdout.length;
1495
+ }
1496
+ return files;
1497
+ }
1498
+ async check(cmd) {
1499
+ this.d.note(`Running ${cmd.length > 70 ? cmd.slice(0, 67) + "..." : cmd}`);
1500
+ const t0 = Date.now();
1501
+ const r = await this.bash(cmd);
1502
+ if (r.refused) return { exit: 126, stdout: "", stderr: `refused: ${r.refused}`, timed_out: false, seconds: 0 };
1503
+ return { exit: r.exit_code, stdout: r.stdout, stderr: r.stderr, timed_out: r.exit_code === 124, seconds: (Date.now() - t0) / 1e3 };
1504
+ }
1505
+ /** Write what Uchi's notes changed. A write the person declines is kept out of the model's view: the next step is
1506
+ * sent the file as it really is. */
1507
+ async apply(changed, onDisk, resync) {
1508
+ const wrote = [];
1509
+ for (const [p, text] of Object.entries(changed)) {
1510
+ const r = await this.d.tool({ kind: "write", payload: "", path: p, new: text });
1511
+ if (r.exit_code === 0 && !r.refused) {
1512
+ onDisk[p] = text;
1513
+ wrote.push(p);
1514
+ } else resync[p] = onDisk[p] ?? "";
1515
+ }
1516
+ return wrote;
1517
+ }
1518
+ /** null: no Python files to work on here (the message is an ordinary turn instead). */
1519
+ async run(goal, instructions = "") {
1520
+ const files = await this.readWorkspace(goal);
1521
+ if (!Object.keys(files).length) return null;
1522
+ const cmd = checkCommand(files, instructions);
1523
+ const { session } = await this.d.post("/api/code/session", { goal, files, model: this.o.model ?? "uchi" });
1524
+ const onDisk = { ...files }, changed = /* @__PURE__ */ new Set(), done = [];
1525
+ let resync = {};
1526
+ const compileOnly = cmd.includes("py_compile");
1527
+ let run = await this.check(cmd);
1528
+ let steps = 0;
1529
+ const step = async (item, retry, now) => {
1530
+ if (this.d.signal?.aborted) throw new Error("stopped");
1531
+ const s = await this.d.post("/api/code/step", { session, item, retry, last_run: run, files: resync, done, now, model: this.o.model ?? "uchi" });
1532
+ resync = {};
1533
+ steps += 1;
1534
+ for (const p of await this.apply(s.changed, onDisk, resync)) changed.add(p);
1535
+ return s;
1536
+ };
1537
+ if (!run.exit && !compileOnly) {
1538
+ return { solved: true, changed: [], check: cmd, steps, summary: `\`${cmd}\` already passes; nothing to change.` };
1539
+ }
1540
+ this.d.note("Planning");
1541
+ const first = await step("", false, "");
1542
+ const plan = first.plan.length ? first.plan : ["fix the failing check"];
1543
+ const tries = this.o.tries ?? 2;
1544
+ for (const [i, item] of plan.slice(0, this.o.maxSteps ?? 8).entries()) {
1545
+ const now = `${i + 1} ${item}`;
1546
+ this.d.note(`Step ${now}`);
1547
+ for (let t = 0; t < tries; t++) {
1548
+ const s = await step(item, t > 0, now);
1549
+ run = await this.check(cmd);
1550
+ if (!run.exit || s.done_step) break;
1551
+ }
1552
+ done.push(now + (!run.exit ? " (passes)" : ""));
1553
+ if (!run.exit && !compileOnly) break;
1554
+ }
1555
+ const solved = !run.exit;
1556
+ const list = [...changed].sort();
1557
+ return {
1558
+ solved,
1559
+ changed: list,
1560
+ check: cmd,
1561
+ steps,
1562
+ summary: `${solved ? "Done" : "Not finished"}: ${done.join("; ") || "no steps"}. Changed ${list.join(", ") || "nothing"}; \`${cmd}\` ${solved ? "passes" : "still fails"}.`
1563
+ };
1564
+ }
1565
+ };
1566
+ }
1567
+ });
1568
+
1569
+ // ../../packages/client/src/app.ts
1570
+ import fs7 from "node:fs";
1571
+ import path6 from "node:path";
1572
+ var SundialApp;
1573
+ var init_app = __esm({
1574
+ "../../packages/client/src/app.ts"() {
1575
+ "use strict";
1576
+ init_api();
1577
+ init_auth();
1578
+ init_config();
1579
+ init_files();
1580
+ init_instructions();
1581
+ init_ide();
1582
+ init_mcp();
1583
+ init_policy();
1584
+ init_session();
1585
+ init_tools();
1586
+ init_coder();
1587
+ SundialApp = class {
1588
+ constructor(folder, server = serverUrl(), fetcher) {
1589
+ this.folder = folder;
1590
+ this.server = server;
1591
+ this.folder = path6.resolve(folder);
1592
+ this.api = new Api(server, void 0, fetcher);
1593
+ const p = prefs();
1594
+ this.policy = {
1595
+ ...DEFAULT_POLICY,
1596
+ ...p.approvals ? { approvals: p.approvals } : {},
1597
+ ...p.sandbox ? { sandbox: p.sandbox } : {},
1598
+ ...p.network !== void 0 ? { network: p.network } : {}
1599
+ };
1600
+ this.session = new Session(this.api, null, p.model);
1601
+ if (p.effort) this.session.effort = p.effort;
1602
+ this.host = this.makeHost();
1603
+ }
1604
+ folder;
1605
+ server;
1606
+ api;
1607
+ me = null;
1608
+ session;
1609
+ host;
1610
+ policy;
1611
+ mcp = null;
1612
+ busy = false;
1613
+ turnNo = 0;
1614
+ abort = null;
1615
+ waiting = /* @__PURE__ */ new Map();
1616
+ listeners = /* @__PURE__ */ new Set();
1617
+ makeHost() {
1618
+ const h = new ToolHost(this.folder, () => this.policy, (a) => this.request(a));
1619
+ h.onAuto = (note) => this.emit({ type: "auto", note });
1620
+ return h;
1621
+ }
1622
+ on(f) {
1623
+ this.listeners.add(f);
1624
+ return () => {
1625
+ this.listeners.delete(f);
1626
+ };
1627
+ }
1628
+ emit(e) {
1629
+ for (const f of this.listeners) f(e);
1630
+ }
1631
+ changed() {
1632
+ this.emit({ type: "state" });
1633
+ }
1634
+ /** Sign-in state and the account's plan, usage and models, fresh from the server. */
1635
+ async refresh() {
1636
+ try {
1637
+ this.me = await this.api.me();
1638
+ this.session.me = this.me;
1639
+ const saved = prefs().model;
1640
+ if (!this.me.models.some((m) => m.id === this.session.model)) this.session.model = new Session(this.api, this.me, saved).model;
1641
+ const ok2 = this.allowedEfforts();
1642
+ if (!ok2.includes(this.session.effort)) this.session.effort = ok2[ok2.length - 1];
1643
+ } catch (e) {
1644
+ if (e instanceof ApiError && e.status === 401) {
1645
+ this.api.token = null;
1646
+ this.me = null;
1647
+ } else this.emit({ type: "notice", level: "warn", text: e.message });
1648
+ }
1649
+ this.changed();
1650
+ }
1651
+ async startMcp() {
1652
+ const read2 = (p) => {
1653
+ try {
1654
+ return JSON.parse(fs7.readFileSync(p, "utf8")).mcpServers ?? {};
1655
+ } catch {
1656
+ return {};
1657
+ }
1658
+ };
1659
+ const servers = { ...read2(path6.join(configDir(), "sundial.json")), ...read2(path6.join(this.folder, ".promethea", "sundial.json")) };
1660
+ if (!Object.keys(servers).length) return;
1661
+ this.mcp = new LocalMcp(servers, this.folder);
1662
+ for (const f of await this.mcp.start()) this.emit({ type: "notice", level: "warn", text: `MCP ${f}` });
1663
+ }
1664
+ async login(onCode, signal) {
1665
+ const l = await startLogin(this.server, "Sundial");
1666
+ onCode(l.userCode, l.url);
1667
+ const email = await l.poll(signal);
1668
+ this.api.token = account(this.server)?.token ?? null;
1669
+ await this.refresh();
1670
+ return email;
1671
+ }
1672
+ async logout() {
1673
+ await this.api.logout().catch(() => {
1674
+ });
1675
+ saveAccount(this.server, null);
1676
+ this.api.token = null;
1677
+ this.me = null;
1678
+ this.session.reset();
1679
+ this.changed();
1680
+ }
1681
+ // ---- approvals -------------------------------------------------------------------------------------------------
1682
+ request(a) {
1683
+ return new Promise((resolve) => {
1684
+ this.waiting.set(a.id, { approval: a, resolve });
1685
+ this.emit({ type: "approval", approval: a });
1686
+ this.changed();
1687
+ });
1688
+ }
1689
+ respond(id, answer) {
1690
+ const w = this.waiting.get(id);
1691
+ if (!w) return;
1692
+ this.waiting.delete(id);
1693
+ w.resolve(answer);
1694
+ this.emit({ type: "approval_done", id, answer });
1695
+ this.changed();
1696
+ }
1697
+ // ---- settings --------------------------------------------------------------------------------------------------
1698
+ setModel(id) {
1699
+ this.session.model = id;
1700
+ savePrefs({ model: id });
1701
+ this.changed();
1702
+ }
1703
+ /** What the plan allows (the server caps it anyway; the interface shows the rest as locked). */
1704
+ allowedEfforts() {
1705
+ return effortsFor(this.me?.user ? this.me.plan.id : "anonymous");
1706
+ }
1707
+ setEffort(e) {
1708
+ const ok2 = this.allowedEfforts();
1709
+ if (!ok2.includes(e)) {
1710
+ this.emit({ type: "notice", level: "warn", text: lockedWhy(e, ok2) });
1711
+ return;
1712
+ }
1713
+ this.session.effort = e;
1714
+ savePrefs({ effort: e });
1715
+ this.changed();
1716
+ }
1717
+ setRigor(on) {
1718
+ this.session.rigor = on !== void 0 ? on : !this.session.rigor;
1719
+ this.changed();
1720
+ return this.session.rigor;
1721
+ }
1722
+ setStudy(on) {
1723
+ this.session.study = on !== void 0 ? on : !this.session.study;
1724
+ this.changed();
1725
+ return this.session.study;
1726
+ }
1727
+ setPolicy(p) {
1728
+ this.policy = { ...this.policy, ...p };
1729
+ savePrefs({ approvals: this.policy.approvals, sandbox: this.policy.sandbox, network: this.policy.network });
1730
+ this.changed();
1731
+ }
1732
+ openFolder(folder) {
1733
+ if (this.busy) throw new Error("Wait for the turn to finish (or stop it) before switching folders.");
1734
+ this.folder = path6.resolve(folder);
1735
+ addProject(this.folder);
1736
+ this.host = this.makeHost();
1737
+ this.session.reset();
1738
+ this.changed();
1739
+ }
1740
+ // ---- threads ---------------------------------------------------------------------------------------------------
1741
+ newThread() {
1742
+ if (!this.busy) {
1743
+ this.session.reset();
1744
+ this.turnNo = 0;
1745
+ this.changed();
1746
+ }
1747
+ }
1748
+ async threads() {
1749
+ if (!this.me?.user) return [];
1750
+ const map = read().threads ?? {};
1751
+ return (await this.api.conversations()).filter((c) => !c.archived).map((c) => ({ ...c, folder: map[c.id] ?? null }));
1752
+ }
1753
+ async resume(id) {
1754
+ if (this.busy) return;
1755
+ await this.session.load(id);
1756
+ const folder = read().threads?.[id];
1757
+ if (folder && folder !== this.folder && fs7.existsSync(folder)) {
1758
+ this.folder = folder;
1759
+ this.host = this.makeHost();
1760
+ }
1761
+ this.changed();
1762
+ }
1763
+ // ---- a turn ----------------------------------------------------------------------------------------------------
1764
+ async send(text, o = {}) {
1765
+ if (this.busy) return null;
1766
+ const isUchi = this.session.model.startsWith("uchi");
1767
+ if (isUchi && !o.edit && !o.regenerate && !o.plan && !o.btw && (o.code || isCodingTask(text))) {
1768
+ const r2 = await this.code(text.replace(/^\s*\/code\b\s*/, ""));
1769
+ if (r2) return r2;
1770
+ }
1771
+ this.busy = true;
1772
+ this.turnNo += 1;
1773
+ this.host.turn = this.turnNo;
1774
+ this.abort = new AbortController();
1775
+ this.changed();
1776
+ const att = readAttached(this.folder, mentions(text));
1777
+ if (att.skipped.length) this.emit({ type: "notice", level: "warn", text: `Not attached: ${att.skipped.join(", ")}` });
1778
+ const ins = load(this.folder);
1779
+ const ide = ideTurn(this.folder);
1780
+ if (ide) Object.assign(att.files, { ...ide.files, ...att.files });
1781
+ let r;
1782
+ try {
1783
+ r = await this.session.turn({
1784
+ text,
1785
+ ...o,
1786
+ files: Object.keys(att.files).length ? att.files : void 0,
1787
+ projectInstructions: ins.text || void 0,
1788
+ clientTools: this.mcp?.announce(text),
1789
+ ...ide ? { panel: ide.panel, selection: ide.selection } : {}
1790
+ }, {
1791
+ onDelta: (t) => this.emit({ type: "delta", text: t }),
1792
+ onActivity: (n) => this.emit({ type: "activity", note: n }),
1793
+ onTodo: (t) => this.emit({ type: "todo", text: t }),
1794
+ onToolCall: (call) => this.host.run(call, this.abort?.signal),
1795
+ onConfirm: (what) => this.host.confirm(what),
1796
+ onClientTool: async (p, payload) => {
1797
+ if (!this.mcp) return { ok: false, text: "no local MCP servers" };
1798
+ const yes = this.mcp.trusted(p) || await this.request({
1799
+ id: `m${Date.now()}`,
1800
+ type: "command",
1801
+ command: `${p} ${payload}`.trim(),
1802
+ why: "MCP tool",
1803
+ sandboxed: false,
1804
+ irreversible: false
1805
+ }) !== "no";
1806
+ if (yes && this.mcp.trusted(p)) this.emit({ type: "auto", note: `Ran ${p} (auto-approved in your settings)` });
1807
+ return yes ? this.mcp.call(p, payload) : { ok: false, text: "declined" };
1808
+ }
1809
+ }, this.abort.signal);
1810
+ } finally {
1811
+ this.busy = false;
1812
+ this.abort = null;
1813
+ for (const [id] of this.waiting) this.respond(id, "no");
1814
+ }
1815
+ if (this.session.id) setThreadFolder(this.session.id, this.folder);
1816
+ if (r.limit) this.emit({ type: "limit", limit: r.limit, upgradeUrl: links(this.server).pricing(r.limit.upgrades.find((p) => p !== "free")) });
1817
+ if (r.usage?.windows.length && this.me) this.me.usage.windows = r.usage.windows;
1818
+ if (!r.stopped) await this.refresh().catch(() => {
1819
+ });
1820
+ this.emit({ type: "turn_end", result: r });
1821
+ this.changed();
1822
+ return r;
1823
+ }
1824
+ /** One coding task through Uchi's coding loop; null when the folder has no Python files to work on. */
1825
+ async code(task) {
1826
+ if (this.busy) return null;
1827
+ this.busy = true;
1828
+ this.turnNo += 1;
1829
+ this.host.turn = this.turnNo;
1830
+ this.abort = new AbortController();
1831
+ this.changed();
1832
+ const ins = load(this.folder);
1833
+ const activity = [];
1834
+ const loop = new CodingLoop({
1835
+ tool: (c) => this.host.run(c, this.abort?.signal),
1836
+ post: (p, body) => this.api.json(p, { method: "POST", body: JSON.stringify(body), signal: this.abort?.signal }),
1837
+ note: (n) => {
1838
+ activity.push(n);
1839
+ this.emit({ type: "activity", note: n });
1840
+ },
1841
+ signal: this.abort.signal
1842
+ }, { model: this.session.model });
1843
+ let r;
1844
+ try {
1845
+ const out = await loop.run(task, ins.text);
1846
+ if (!out) {
1847
+ r = null;
1848
+ } else {
1849
+ this.emit({ type: "delta", text: out.summary });
1850
+ r = { reply: { id: `code-${Date.now()}`, createdAt: Date.now(), role: "assistant", content: out.summary, model: this.session.model, activity } };
1851
+ if (this.session.persisted) {
1852
+ const rec = await this.api.json("/api/conversations/record", {
1853
+ method: "POST",
1854
+ body: JSON.stringify({ conversationId: this.session.id, user: task, assistant: out.summary, model: this.session.model, activity })
1855
+ }).catch(() => null);
1856
+ if (rec) {
1857
+ await this.session.load(rec.conversationId).catch(() => {
1858
+ });
1859
+ setThreadFolder(rec.conversationId, this.folder);
1860
+ }
1861
+ }
1862
+ }
1863
+ } catch (e) {
1864
+ const limit = e instanceof ApiError && e.status === 429;
1865
+ const noAgent = e instanceof ApiError && (e.status === 409 || e.status === 503 || e.status === 404);
1866
+ r = noAgent ? null : { reply: null, error: limit ? "You've reached your plan's limit." : e.message };
1867
+ } finally {
1868
+ this.busy = false;
1869
+ this.abort = null;
1870
+ for (const [id] of this.waiting) this.respond(id, "no");
1871
+ }
1872
+ if (r) {
1873
+ await this.refresh().catch(() => {
1874
+ });
1875
+ this.emit({ type: "turn_end", result: r });
1876
+ }
1877
+ this.changed();
1878
+ return r;
1879
+ }
1880
+ /** Stop the turn: the stream is cut, and whatever it was asking is declined (so nothing waits forever). */
1881
+ stop() {
1882
+ this.abort?.abort();
1883
+ for (const [id] of [...this.waiting]) this.respond(id, "no");
1884
+ }
1885
+ /** /compact: the server summarises the conversation so far (all but the latest exchange); focus: what to keep. */
1886
+ async compact(focus) {
1887
+ if (!this.session.id || !this.session.persisted) return { error: "Nothing to compact: this thread isn't saved yet." };
1888
+ try {
1889
+ const r = await this.api.json(
1890
+ `/api/conversations/${this.session.id}/compact`,
1891
+ { method: "POST", body: JSON.stringify(focus ? { focus } : {}) }
1892
+ );
1893
+ return { summarized: r.summarized };
1894
+ } catch (e) {
1895
+ return { error: e.message };
1896
+ }
1897
+ }
1898
+ undo(id) {
1899
+ const c = this.host.undo(id);
1900
+ this.changed();
1901
+ return c;
1902
+ }
1903
+ snapshot() {
1904
+ const u = this.me?.user ?? null;
1905
+ return {
1906
+ server: this.server,
1907
+ signedIn: !!u,
1908
+ email: u?.email ?? null,
1909
+ plan: this.me?.plan ?? null,
1910
+ credits: u?.creditsUsd ?? null,
1911
+ windows: (this.me?.usage.windows ?? []).map((w) => ({ ...w, messagesLeft: messagesLeft(w) })),
1912
+ freeMessages: this.me?.freeMessages ? { limit: this.me.freeMessages.limit, used: this.me.freeMessages.used, left: this.me.freeMessages.left } : null,
1913
+ efforts: EFFORTS.map((e) => {
1914
+ const ok2 = this.allowedEfforts();
1915
+ return { ...e, allowed: ok2.includes(e.id), why: lockedWhy(e.id, ok2) };
1916
+ }),
1917
+ models: this.me?.models ?? [],
1918
+ model: this.session.model,
1919
+ effort: this.session.effort,
1920
+ rigor: this.session.rigor,
1921
+ study: this.session.study,
1922
+ policy: this.policy,
1923
+ osSandbox: this.host.osSandbox,
1924
+ folder: this.folder,
1925
+ projects: read().projects ?? [],
1926
+ instructionFiles: load(this.folder).files,
1927
+ thread: { id: this.session.id, title: this.session.title, messages: this.session.path },
1928
+ busy: this.busy,
1929
+ pending: [...this.waiting.values()].map((w) => w.approval),
1930
+ changes: this.host.review().map((c) => {
1931
+ const { added, removed } = diffLines(c.path, c.before, c.after);
1932
+ return { path: c.path, added, removed, ids: c.ids };
1933
+ }),
1934
+ links: (({ pricing, ...rest }) => ({ ...rest, pricing: pricing() }))(links(this.server))
1935
+ };
1936
+ }
1937
+ close() {
1938
+ this.stop();
1939
+ this.mcp?.stop();
1940
+ }
1941
+ };
1942
+ }
1943
+ });
1944
+
1945
+ // ../../packages/client/src/brand.ts
1946
+ function logoRuns() {
1947
+ return LOGO.map((line, r) => {
1948
+ const runs = [];
1949
+ for (let i = 0; i < line.length; i++) {
1950
+ const m = LOGO_MASK[r]?.[i] ?? "a";
1951
+ const c = m === "f" ? COLORS.fire : m === "c" ? COLORS.coral : COLORS.alabaster;
1952
+ if (runs.length && runs[runs.length - 1][1] === c) runs[runs.length - 1][0] += line[i];
1953
+ else runs.push([line[i], c]);
1954
+ }
1955
+ return runs;
1956
+ });
1957
+ }
1958
+ function cssVars(theme) {
1959
+ const t = TONES[theme];
1960
+ return Object.entries(t).map(([k, v]) => `--${k.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase())}: ${v};`).join(" ");
1961
+ }
1962
+ var COLORS, TONES, FONTS, LOGO, LOGO_MASK, PULSE;
1963
+ var init_brand = __esm({
1964
+ "../../packages/client/src/brand.ts"() {
1965
+ "use strict";
1966
+ COLORS = {
1967
+ carbon: "#111111",
1968
+ fire: "#d9381e",
1969
+ coral: "#e67d6b",
1970
+ alabaster: "#f4f4f2",
1971
+ white: "#ffffff"
1972
+ };
1973
+ TONES = {
1974
+ dark: {
1975
+ bg: COLORS.carbon,
1976
+ panel: "#1a1a1a",
1977
+ raised: "#222222",
1978
+ border: "#2e2e2e",
1979
+ text: COLORS.alabaster,
1980
+ muted: "#9a9a96",
1981
+ faint: "#5f5f5c",
1982
+ primary: COLORS.fire,
1983
+ accent: COLORS.coral,
1984
+ added: "#c9d8b6",
1985
+ addedBg: "#1d2419",
1986
+ removed: COLORS.coral,
1987
+ removedBg: "#2a1714"
1988
+ },
1989
+ light: {
1990
+ bg: COLORS.alabaster,
1991
+ panel: COLORS.white,
1992
+ raised: "#ebebe8",
1993
+ border: "#dcdcd8",
1994
+ text: COLORS.carbon,
1995
+ muted: "#5f5f5c",
1996
+ faint: "#9a9a96",
1997
+ primary: COLORS.fire,
1998
+ accent: "#b8503f",
1999
+ added: "#2f5a1f",
2000
+ addedBg: "#e6efdc",
2001
+ removed: "#a02a16",
2002
+ removedBg: "#f7e1dc"
2003
+ }
2004
+ };
2005
+ FONTS = {
2006
+ sans: '"Inter", "Geist", system-ui, -apple-system, "Segoe UI", sans-serif',
2007
+ mono: '"JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace'
2008
+ };
2009
+ LOGO = [
2010
+ " \u2572 \u2502 \u2571 ",
2011
+ " \u2500 \u256D\u2500\u2534\u2500\u256E \u2500 ",
2012
+ " \u2571\u2502\u2572 \u2502\u2572 ",
2013
+ " \u256D\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u256E ",
2014
+ " \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F "
2015
+ ];
2016
+ LOGO_MASK = [
2017
+ " c f c ",
2018
+ " c aafaa c ",
2019
+ " aff fc ",
2020
+ " aafaaafaa ",
2021
+ " aaaaaaaaa "
2022
+ ];
2023
+ PULSE = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
2024
+ }
2025
+ });
2026
+
2027
+ // ../../packages/client/src/index.ts
2028
+ var src_exports = {};
2029
+ __export(src_exports, {
2030
+ APPROVALS: () => APPROVALS,
2031
+ Api: () => Api,
2032
+ ApiError: () => ApiError,
2033
+ COLORS: () => COLORS,
2034
+ CodingLoop: () => CodingLoop,
2035
+ DEFAULT_POLICY: () => DEFAULT_POLICY,
2036
+ EFFORTS: () => EFFORTS,
2037
+ FONTS: () => FONTS,
2038
+ LOGO: () => LOGO,
2039
+ LOGO_MASK: () => LOGO_MASK,
2040
+ LocalMcp: () => LocalMcp,
2041
+ MAX_FILE: () => MAX_FILE,
2042
+ MAX_FILES: () => MAX_FILES,
2043
+ PULSE: () => PULSE,
2044
+ READ_BUDGET: () => READ_BUDGET,
2045
+ SANDBOXES: () => SANDBOXES,
2046
+ Session: () => Session,
2047
+ StdioServer: () => StdioServer,
2048
+ SundialApp: () => SundialApp,
2049
+ TOKENS_PER_MESSAGE: () => TOKENS_PER_MESSAGE,
2050
+ TONES: () => TONES,
2051
+ ToolHost: () => ToolHost,
2052
+ VERSION: () => VERSION,
2053
+ checkCommand: () => checkCommand,
2054
+ config: () => config_exports,
2055
+ cssVars: () => cssVars,
2056
+ decideCommand: () => decideCommand,
2057
+ decideWrite: () => decideWrite,
2058
+ defaultModel: () => defaultModel,
2059
+ diffLines: () => diffLines,
2060
+ effortsFor: () => effortsFor,
2061
+ ideFile: () => ideFile,
2062
+ ideTurn: () => ideTurn,
2063
+ inside: () => inside,
2064
+ instructions: () => instructions_exports,
2065
+ isCodingTask: () => isCodingTask,
2066
+ isIrreversible: () => isIrreversible,
2067
+ isReadOnly: () => isReadOnly,
2068
+ links: () => links,
2069
+ lockedWhy: () => lockedWhy,
2070
+ logoRuns: () => logoRuns,
2071
+ mentions: () => mentions,
2072
+ messagesLeft: () => messagesLeft,
2073
+ openBrowser: () => openBrowser,
2074
+ osSandbox: () => available,
2075
+ planWrite: () => planWrite,
2076
+ rankFiles: () => rankFiles,
2077
+ readAttached: () => readAttached,
2078
+ readIde: () => readIde,
2079
+ readSSE: () => readSSE,
2080
+ runShell: () => runShell,
2081
+ search: () => search,
2082
+ startLogin: () => startLogin,
2083
+ termsOf: () => termsOf
2084
+ });
2085
+ var init_src = __esm({
2086
+ "../../packages/client/src/index.ts"() {
2087
+ init_api();
2088
+ init_auth();
2089
+ init_config();
2090
+ init_files();
2091
+ init_instructions();
2092
+ init_mcp();
2093
+ init_ide();
2094
+ init_policy();
2095
+ init_session();
2096
+ init_tools();
2097
+ init_app();
2098
+ init_brand();
2099
+ init_sandbox();
2100
+ init_coder();
2101
+ }
2102
+ });
2103
+
2104
+ // src/index.tsx
2105
+ init_src();
2106
+ import fs9 from "node:fs";
2107
+ import { render } from "ink";
2108
+
2109
+ // src/ui/App.tsx
2110
+ init_src();
2111
+ init_brand();
2112
+ import { Box as Box5, Static, Text as Text5, useApp, useInput as useInput4 } from "ink";
2113
+ import { useEffect, useMemo, useRef as useRef2, useState as useState3 } from "react";
2114
+ import { spawn as spawn4, spawnSync as spawnSync2 } from "node:child_process";
2115
+ import fs8 from "node:fs";
2116
+ import path7 from "node:path";
2117
+
2118
+ // src/commands.ts
2119
+ var COMMANDS = [
2120
+ { name: "voice", aliases: ["talk", "speak", "audio"], args: "[on|off|stop]", help: "toggle zero-cost local Voice Mode ($0 on-device speech synthesis)" },
2121
+ { name: "copy", aliases: ["cp", "yank", "clipboard"], help: "copy the latest output returned by Uchi to your clipboard (or press Ctrl+Y)" },
2122
+ { name: "swarm", aliases: ["uchi-swarm", "tandem"], args: "[2-8] <problem>", help: "spawn a tandem Uchi Swarm sharing a live context blackboard" },
2123
+ { name: "flywheel", aliases: ["diag", "diagnostics"], help: "run the 49-probe full-stack behavioral, opinion-formation & neural flywheel suite" },
2124
+ { name: "model", aliases: ["models", "switch"], args: "[uchi|uchi-1]", help: "choose active model (Uchi 2 Flagship Default, or Uchi 1)" },
2125
+ { name: "uchi2", aliases: ["uchi", "uchi-2", "tier4", "uchi-457t", "uchi-3t", "flagship"], help: "switch directly to Uchi 2 (Default Flagship Model)" },
2126
+ { name: "uchi1", aliases: ["uchi-1"], help: "switch directly to Uchi 1 (Generation 1 Model)" },
2127
+ { name: "remote", aliases: ["phone", "terminal", "bridge"], args: "[pair|status|nav <path>|repo <owner/repo>|run <cmd>|stop|output|events]", help: "pair this terminal or control remote terminal & GitHub sessions" },
2128
+ { name: "connectors", aliases: ["integrations", "context"], help: "inspect all 32 read-only enterprise, developer, cloud & data connectors" },
2129
+ { name: "search", aliases: ["web", "lookup"], args: "<query>", help: "search allowlisted public knowledge sources (strictly read-only GET)" },
2130
+ { name: "remember", aliases: ["kg", "memory"], args: "<fact>", help: "save a structured fact to your Personal Knowledge Graph (memory/uchi_graph.json)" },
2131
+ { name: "rigor", aliases: ["epistemic"], args: "[on|off]", help: "toggle Rigor Mode ([Tested], [Supported], [Conjecture] epistemic tagging)" },
2132
+ { name: "study", aliases: ["learn", "tutor"], args: "[on|off]", help: "toggle Study Mode (first-principles guided learning)" },
2133
+ { name: "bci", aliases: ["neural"], args: "<signal>", help: "decode non-invasive BCI neural intent (gaze, motor imagery, handwriting, ERN)" },
2134
+ { name: "new", aliases: ["clear", "reset"], help: "start a new thread" },
2135
+ { name: "resume", aliases: ["threads", "history"], help: "pick up an earlier thread" },
2136
+ { name: "btw", aliases: ["side"], args: "<question>", help: "side-channel question without polluting main thread context" },
2137
+ { name: "effort", aliases: ["thinking"], args: "[low|medium|high]", help: "how long the model thinks: low / medium / high" },
2138
+ { name: "approvals", help: "suggest / auto edit / full auto (Shift+Tab cycles)" },
2139
+ { name: "sandbox", help: "read only / workspace" },
2140
+ { name: "plan", args: "<task>", help: "plan first, change nothing until you approve" },
2141
+ { name: "code", args: "<task>", help: "Uchi's coding agent on this folder: plan, edit, run the tests, until they pass" },
2142
+ { name: "skills", help: "list active skills (.sundial/skills, .promethea/skills) and instruction files" },
2143
+ { name: "obsidian", args: "[vault_path]", help: "sync an Obsidian vault (.md notes & [[wikilinks]]) into your Knowledge Graph" },
2144
+ { name: "compact", args: "[focus]", help: "summarise the thread so far to free up context (optionally what to keep)" },
2145
+ { name: "diff", help: "the changes made in this thread" },
2146
+ { name: "undo", help: "undo the last change" },
2147
+ { name: "status", help: "account, plan, usage, model, policy, folder" },
2148
+ { name: "usage", help: "your allowance windows (billing is on the website)" },
2149
+ { name: "upgrade", help: "open plans and pricing on the website" },
2150
+ { name: "knowledge", help: "the knowledge graphs: explore the world's, edit yours and your workspace's" },
2151
+ { name: "init", help: "create PROMETHEA.md (project instructions)" },
2152
+ { name: "login", help: "sign in with your Promethea Research account" },
2153
+ { name: "logout", help: "sign out on this machine" },
2154
+ { name: "help", aliases: ["commands", "?"], help: "this list" },
2155
+ { name: "quit", aliases: ["exit", "q"], help: "leave Sundial" }
2156
+ ];
2157
+ function resolveCommandName(inputName) {
2158
+ const p = inputName.replace(/^\//, "").toLowerCase();
2159
+ const exact = COMMANDS.find((c) => c.name === p || c.aliases?.includes(p));
2160
+ if (exact) return exact.name;
2161
+ const matches = complete(p);
2162
+ return matches.length === 1 ? matches[0].name : null;
2163
+ }
2164
+ function complete(prefix) {
2165
+ const p = prefix.replace(/^\//, "").toLowerCase();
2166
+ if (!p) return COMMANDS;
2167
+ const primaryMatches = COMMANDS.filter((c) => c.name.startsWith(p));
2168
+ const aliasMatches = COMMANDS.filter(
2169
+ (c) => !c.name.startsWith(p) && c.aliases?.some((a) => a.startsWith(p))
2170
+ );
2171
+ return [...primaryMatches, ...aliasMatches];
2172
+ }
2173
+
2174
+ // src/markdown.ts
2175
+ init_brand();
2176
+ import chalk from "chalk";
2177
+ import { Marked } from "marked";
2178
+ import { markedTerminal } from "marked-terminal";
2179
+ var coral = chalk.hex(COLORS.coral);
2180
+ var cached2 = null;
2181
+ function renderer(width) {
2182
+ if (cached2?.width === width) return cached2.m;
2183
+ const m = new Marked();
2184
+ m.use(markedTerminal({
2185
+ width,
2186
+ reflowText: true,
2187
+ tab: 2,
2188
+ showSectionPrefix: false,
2189
+ code: chalk.reset,
2190
+ codespan: coral,
2191
+ firstHeading: chalk.bold,
2192
+ heading: chalk.bold,
2193
+ strong: chalk.bold,
2194
+ em: chalk.italic,
2195
+ link: coral,
2196
+ href: coral.underline,
2197
+ blockquote: chalk.gray.italic,
2198
+ hr: chalk.gray,
2199
+ listitem: chalk.reset,
2200
+ table: chalk.reset
2201
+ }));
2202
+ cached2 = { width, m };
2203
+ return m;
2204
+ }
2205
+ function renderMarkdown(text, width = process.stdout.columns || 100) {
2206
+ try {
2207
+ const fences = (text.match(/^```/gm) ?? []).length;
2208
+ const src = fences % 2 ? text + "\n```" : text;
2209
+ return renderer(Math.max(40, width - 4)).parse(src).replace(/\n+$/, "");
2210
+ } catch {
2211
+ return text;
2212
+ }
2213
+ }
2214
+
2215
+ // src/ui/Approval.tsx
2216
+ init_brand();
2217
+ import { Box, Text, useInput } from "ink";
2218
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2219
+ var T = TONES.dark;
2220
+ function DiffView({ lines, max = 40 }) {
2221
+ const shown = lines.slice(0, max);
2222
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
2223
+ shown.map((l, i) => /* @__PURE__ */ jsx(Text, { color: l.startsWith("+") ? T.added : l.startsWith("-") ? T.removed : l.startsWith("@@") ? T.faint : T.muted, children: l || " " }, i)),
2224
+ lines.length > max && /* @__PURE__ */ jsxs(Text, { color: T.faint, children: [
2225
+ "\u2026 ",
2226
+ lines.length - max,
2227
+ " more lines"
2228
+ ] })
2229
+ ] });
2230
+ }
2231
+ function ApprovalBox({ a, onAnswer }) {
2232
+ const irreversible = a.type === "command" && a.irreversible;
2233
+ useInput((input, key) => {
2234
+ const k = input.toLowerCase();
2235
+ if (k === "y" || key.return) onAnswer("yes");
2236
+ else if (k === "a" && !irreversible && a.type !== "confirm") onAnswer("always");
2237
+ else if (k === "n" || key.escape) onAnswer("no");
2238
+ });
2239
+ const title = a.type === "write" ? `${a.exists ? "Edit" : "Create"} ${a.path} (+${a.added} \u2212${a.removed})` : a.type === "command" ? "Run a command" : "Confirm";
2240
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: irreversible ? COLORS.fire : COLORS.coral, paddingX: 1, children: [
2241
+ /* @__PURE__ */ jsx(Text, { bold: true, color: irreversible ? COLORS.fire : COLORS.coral, children: title }),
2242
+ a.type === "command" && /* @__PURE__ */ jsxs(Text, { children: [
2243
+ "$ ",
2244
+ a.command
2245
+ ] }),
2246
+ a.type === "command" && /* @__PURE__ */ jsxs(Text, { color: T.muted, children: [
2247
+ irreversible ? "This can't be undone." : a.why,
2248
+ a.sandboxed ? " \xB7 sandboxed" : ""
2249
+ ] }),
2250
+ a.type === "write" && /* @__PURE__ */ jsx(DiffView, { lines: a.diff }),
2251
+ a.type === "confirm" && /* @__PURE__ */ jsx(Text, { children: a.what }),
2252
+ /* @__PURE__ */ jsxs(Text, { color: T.muted, children: [
2253
+ /* @__PURE__ */ jsx(Text, { color: COLORS.alabaster, bold: true, children: "y" }),
2254
+ " yes",
2255
+ !irreversible && a.type !== "confirm" && /* @__PURE__ */ jsxs(Fragment, { children: [
2256
+ " ",
2257
+ /* @__PURE__ */ jsx(Text, { color: COLORS.alabaster, bold: true, children: "a" }),
2258
+ " ",
2259
+ a.type === "write" ? "yes to all edits this session" : `always allow ${a.type === "command" ? a.command.split(/\s+/)[0] : ""}`
2260
+ ] }),
2261
+ " ",
2262
+ /* @__PURE__ */ jsx(Text, { color: COLORS.alabaster, bold: true, children: "n" }),
2263
+ " no"
2264
+ ] })
2265
+ ] });
2266
+ }
2267
+
2268
+ // src/ui/Picker.tsx
2269
+ init_brand();
2270
+ import { Box as Box2, Text as Text2, useInput as useInput2 } from "ink";
2271
+ import { useState } from "react";
2272
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
2273
+ var WIRE = COLORS.coral;
2274
+ function Picker({ title, items, onPick, onCancel, max = 10 }) {
2275
+ const [i, setI] = useState(0);
2276
+ const [filter, setFilter] = useState("");
2277
+ const shown = items.filter((x) => (x.label + " " + (x.hint ?? "")).toLowerCase().includes(filter.toLowerCase()));
2278
+ const sel = Math.min(i, Math.max(0, shown.length - 1));
2279
+ useInput2((input, key) => {
2280
+ if (key.escape) onCancel();
2281
+ else if (key.return) {
2282
+ if (shown[sel]) onPick(shown[sel].value);
2283
+ } else if (key.upArrow) setI(Math.max(0, sel - 1));
2284
+ else if (key.downArrow) setI(Math.min(shown.length - 1, sel + 1));
2285
+ else if (key.backspace || key.delete) setFilter((f) => f.slice(0, -1));
2286
+ else if (input && !key.ctrl && !key.meta) {
2287
+ setFilter((f) => f + input);
2288
+ setI(0);
2289
+ }
2290
+ });
2291
+ const start = Math.max(0, Math.min(sel - Math.floor(max / 2), shown.length - max));
2292
+ return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", borderStyle: "round", borderColor: WIRE, paddingX: 1, children: [
2293
+ /* @__PURE__ */ jsxs2(Text2, { bold: true, children: [
2294
+ title,
2295
+ filter && /* @__PURE__ */ jsxs2(Text2, { color: "gray", children: [
2296
+ " filter: ",
2297
+ filter
2298
+ ] })
2299
+ ] }),
2300
+ shown.slice(start, start + max).map((x, k) => {
2301
+ const on = start + k === sel;
2302
+ return /* @__PURE__ */ jsxs2(Text2, { color: on ? WIRE : void 0, children: [
2303
+ on ? "\u276F " : " ",
2304
+ x.label,
2305
+ x.hint ? /* @__PURE__ */ jsxs2(Text2, { color: "gray", children: [
2306
+ " ",
2307
+ x.hint
2308
+ ] }) : null
2309
+ ] }, start + k);
2310
+ }),
2311
+ !shown.length && /* @__PURE__ */ jsx2(Text2, { color: "gray", children: " Nothing matches." }),
2312
+ /* @__PURE__ */ jsx2(Text2, { color: "gray", children: "\u2191\u2193 to move \xB7 type to filter \xB7 Enter to choose \xB7 Esc to cancel" })
2313
+ ] });
2314
+ }
2315
+
2316
+ // src/ui/Status.tsx
2317
+ init_src();
2318
+ init_brand();
2319
+ import { Box as Box3, Text as Text3 } from "ink";
2320
+ import { Fragment as Fragment2, jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
2321
+ var T2 = TONES.dark;
2322
+ var BARS = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
2323
+ var ORBITS = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
2324
+ function meter(pct, width = 10) {
2325
+ const n = Math.max(0, Math.min(width, Math.round(pct / 100 * width)));
2326
+ return "\u25B0".repeat(n) + "\u25B1".repeat(width - n);
2327
+ }
2328
+ function equalizerWave(tick, active, width = 10) {
2329
+ if (!active) return "\u2581\u2582\u2583\u2582\u2581\u2581\u2582\u2583\u2582\u2581".slice(0, width);
2330
+ let out = "";
2331
+ for (let i = 0; i < width; i++) {
2332
+ const wave = Math.sin(tick * 0.65 + i * 0.75) * 0.5 + Math.cos(tick * 0.35 - i * 1.1) * 0.35 + 0.5;
2333
+ const idx = Math.max(0, Math.min(BARS.length - 1, Math.round(wave * (BARS.length - 1))));
2334
+ out += BARS[idx];
2335
+ }
2336
+ return out;
2337
+ }
2338
+ function orbitFrame(tick) {
2339
+ return ORBITS[Math.abs(tick) % ORBITS.length];
2340
+ }
2341
+ function Status({
2342
+ s,
2343
+ mode,
2344
+ voiceOn,
2345
+ copiedAt,
2346
+ hasLatestReply,
2347
+ tick = 0,
2348
+ activeWave = false
2349
+ }) {
2350
+ const model = s.models.find((m) => m.id === s.model)?.name ?? s.model;
2351
+ const ap = APPROVALS.find((a) => a.id === s.policy.approvals).label;
2352
+ const sb = SANDBOXES.find((a) => a.id === s.policy.sandbox).label;
2353
+ const w = [...s.windows].sort((a, b) => b.pct - a.pct)[0];
2354
+ const wave = equalizerWave(tick, Boolean(activeWave || s.busy || voiceOn), 8);
2355
+ return /* @__PURE__ */ jsxs3(Box3, { justifyContent: "space-between", children: [
2356
+ /* @__PURE__ */ jsxs3(Text3, { color: T2.muted, children: [
2357
+ /* @__PURE__ */ jsx3(Text3, { color: s.busy || activeWave ? COLORS.fire : COLORS.coral, children: s.busy || activeWave ? orbitFrame(tick) : "\u25CF" }),
2358
+ " ",
2359
+ /* @__PURE__ */ jsx3(Text3, { color: COLORS.alabaster, bold: true, children: model }),
2360
+ " ",
2361
+ /* @__PURE__ */ jsx3(Text3, { color: s.busy || activeWave || voiceOn ? COLORS.fire : T2.faint, children: wave }),
2362
+ " \xB7 ",
2363
+ s.effort,
2364
+ " \xB7 ",
2365
+ ap,
2366
+ s.policy.sandbox === "read-only" ? ` \xB7 ${sb}` : "",
2367
+ voiceOn ? /* @__PURE__ */ jsx3(Text3, { color: COLORS.fire, children: " \xB7 \u25C9 Voice ($0 local)" }) : null,
2368
+ copiedAt ? /* @__PURE__ */ jsx3(Text3, { color: COLORS.coral, children: " \xB7 \u2713 Copied latest" }) : hasLatestReply ? /* @__PURE__ */ jsx3(Text3, { color: T2.faint, children: " \xB7 Ctrl+Y /copy" }) : null,
2369
+ mode ? /* @__PURE__ */ jsxs3(Text3, { color: COLORS.coral, children: [
2370
+ " \xB7 ",
2371
+ mode
2372
+ ] }) : null
2373
+ ] }),
2374
+ /* @__PURE__ */ jsx3(Text3, { color: T2.muted, children: s.freeMessages ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
2375
+ s.signedIn ? s.plan?.name : "Guest",
2376
+ " \xB7 ",
2377
+ s.freeMessages.left,
2378
+ " of ",
2379
+ s.freeMessages.limit,
2380
+ " free messages left"
2381
+ ] }) : s.signedIn ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
2382
+ s.plan?.name,
2383
+ w ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
2384
+ " \xB7 ",
2385
+ /* @__PURE__ */ jsx3(Text3, { color: w.pct >= 90 ? COLORS.fire : w.pct >= 70 ? COLORS.coral : T2.muted, children: meter(w.pct, 6) }),
2386
+ " ~",
2387
+ w.messagesLeft,
2388
+ " messages left ",
2389
+ w.id === "session" ? "this session" : `this ${w.id}`
2390
+ ] }) : null,
2391
+ s.credits ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
2392
+ " \xB7 $",
2393
+ s.credits.toFixed(2)
2394
+ ] }) : null
2395
+ ] }) : /* @__PURE__ */ jsx3(Fragment2, { children: "Guest \xB7 /login" }) })
2396
+ ] });
2397
+ }
2398
+
2399
+ // src/ui/TextInput.tsx
2400
+ import chalk2 from "chalk";
2401
+ import { Box as Box4, Text as Text4, useInput as useInput3 } from "ink";
2402
+ import { useRef, useState as useState2 } from "react";
2403
+ import { jsx as jsx4 } from "react/jsx-runtime";
2404
+ function TextInput({ value, onChange, onSubmit, onTab, onShiftTab, onEscape, history, placeholder, active, vim, onVimMode }) {
2405
+ const [cursor, setCursor] = useState2(value.length);
2406
+ const hist = useRef({ i: -1, draft: "" });
2407
+ const [normal, setNormalState] = useState2(false);
2408
+ const pending = useRef("");
2409
+ const register = useRef("");
2410
+ const undo = useRef([]);
2411
+ const c = Math.min(cursor, value.length);
2412
+ const setNormal = (n) => {
2413
+ if (!n) undo.current.push({ v: value, c });
2414
+ setNormalState(n);
2415
+ onVimMode?.(n ? "normal" : "insert");
2416
+ };
2417
+ const set = (v, at) => {
2418
+ onChange(v);
2419
+ setCursor(Math.max(0, Math.min(at, v.length)));
2420
+ };
2421
+ const edit = (v, at) => {
2422
+ undo.current.push({ v: value, c });
2423
+ if (undo.current.length > 100) undo.current.shift();
2424
+ set(v, at);
2425
+ };
2426
+ const walkHistory = (dir) => {
2427
+ const h = hist.current;
2428
+ if (dir === 1) {
2429
+ if (!history.length) return;
2430
+ if (h.i === -1) h.draft = value;
2431
+ h.i = Math.min(h.i + 1, history.length - 1);
2432
+ const v = history[history.length - 1 - h.i];
2433
+ set(v, v.length);
2434
+ } else {
2435
+ if (h.i < 0) return;
2436
+ h.i -= 1;
2437
+ const v = h.i < 0 ? h.draft : history[history.length - 1 - h.i];
2438
+ set(v, v.length);
2439
+ }
2440
+ };
2441
+ const vimKey = (input, key) => {
2442
+ const ls = value.lastIndexOf("\n", c - 1) + 1;
2443
+ const le = value.indexOf("\n", c) < 0 ? value.length : value.indexOf("\n", c);
2444
+ const op = pending.current;
2445
+ pending.current = "";
2446
+ if (key.return) {
2447
+ hist.current = { i: -1, draft: "" };
2448
+ onSubmit(value);
2449
+ setCursor(0);
2450
+ setNormal(false);
2451
+ return;
2452
+ }
2453
+ const del = (a, b, insert = false) => {
2454
+ register.current = value.slice(a, b);
2455
+ edit(value.slice(0, a) + value.slice(b), a);
2456
+ if (insert) setNormal(false);
2457
+ };
2458
+ if (op === "d" || op === "c") {
2459
+ const ins = op === "c";
2460
+ if (input === op) {
2461
+ if (ins) {
2462
+ del(ls, le, true);
2463
+ return true;
2464
+ }
2465
+ const a = ls > 0 && le === value.length ? ls - 1 : ls, b = le < value.length ? le + 1 : le;
2466
+ del(a, b);
2467
+ return true;
2468
+ }
2469
+ if (input === "w") {
2470
+ del(c, ins ? wordEnd(value, c) : wordStartNext(value, c), ins);
2471
+ return true;
2472
+ }
2473
+ if (input === "b") {
2474
+ const w = wordLeft(value, c);
2475
+ del(w, c, ins);
2476
+ return true;
2477
+ }
2478
+ if (input === "$") {
2479
+ del(c, le, ins);
2480
+ return true;
2481
+ }
2482
+ if (input === "0") {
2483
+ del(ls, c, ins);
2484
+ return true;
2485
+ }
2486
+ return true;
2487
+ }
2488
+ if (op === "g") {
2489
+ if (input === "g") setCursor(0);
2490
+ return true;
2491
+ }
2492
+ switch (input) {
2493
+ case "h":
2494
+ setCursor(Math.max(ls, c - 1));
2495
+ return true;
2496
+ case "l":
2497
+ setCursor(Math.min(Math.max(ls, le - 1), c + 1));
2498
+ return true;
2499
+ case "0":
2500
+ setCursor(ls);
2501
+ return true;
2502
+ case "^": {
2503
+ let i = ls;
2504
+ while (i < le && /\s/.test(value[i])) i++;
2505
+ setCursor(i);
2506
+ return true;
2507
+ }
2508
+ case "$":
2509
+ setCursor(Math.max(ls, le - 1));
2510
+ return true;
2511
+ case "w":
2512
+ setCursor(Math.min(value.length, wordStartNext(value, c)));
2513
+ return true;
2514
+ case "b":
2515
+ setCursor(wordLeft(value, c));
2516
+ return true;
2517
+ case "e":
2518
+ setCursor(Math.max(0, wordEnd(value, c + 1) - 1));
2519
+ return true;
2520
+ case "G":
2521
+ setCursor(value.length);
2522
+ return true;
2523
+ case "g":
2524
+ case "d":
2525
+ case "c":
2526
+ pending.current = input;
2527
+ return true;
2528
+ case "x":
2529
+ if (c < le) del(c, c + 1);
2530
+ return true;
2531
+ case "D":
2532
+ del(c, le);
2533
+ return true;
2534
+ case "C":
2535
+ del(c, le, true);
2536
+ return true;
2537
+ case "i":
2538
+ setNormal(false);
2539
+ return true;
2540
+ case "a":
2541
+ setCursor(Math.min(le, c + 1));
2542
+ setNormal(false);
2543
+ return true;
2544
+ case "I":
2545
+ setCursor(ls);
2546
+ setNormal(false);
2547
+ return true;
2548
+ case "A":
2549
+ setCursor(le);
2550
+ setNormal(false);
2551
+ return true;
2552
+ case "o":
2553
+ edit(value.slice(0, le) + "\n" + value.slice(le), le + 1);
2554
+ setNormal(false);
2555
+ return true;
2556
+ case "O":
2557
+ edit(value.slice(0, ls) + "\n" + value.slice(ls), ls);
2558
+ setNormal(false);
2559
+ return true;
2560
+ case "p": {
2561
+ const at = Math.min(value.length, c + (value.length ? 1 : 0));
2562
+ edit(value.slice(0, at) + register.current + value.slice(at), at + register.current.length - 1);
2563
+ return true;
2564
+ }
2565
+ case "P":
2566
+ edit(value.slice(0, c) + register.current + value.slice(c), c + Math.max(0, register.current.length - 1));
2567
+ return true;
2568
+ case "u": {
2569
+ const u = undo.current.pop();
2570
+ if (u) set(u.v, u.c);
2571
+ return true;
2572
+ }
2573
+ case "k":
2574
+ if (ls > 0) {
2575
+ const ps = value.lastIndexOf("\n", ls - 2) + 1;
2576
+ setCursor(Math.min(ps + (c - ls), ls - 1));
2577
+ } else walkHistory(1);
2578
+ return true;
2579
+ case "j":
2580
+ if (le < value.length) {
2581
+ const ne = value.indexOf("\n", le + 1) < 0 ? value.length : value.indexOf("\n", le + 1);
2582
+ setCursor(Math.min(le + 1 + (c - ls), ne));
2583
+ } else walkHistory(-1);
2584
+ return true;
2585
+ }
2586
+ if (key.leftArrow) {
2587
+ setCursor(Math.max(ls, c - 1));
2588
+ return true;
2589
+ }
2590
+ if (key.rightArrow) {
2591
+ setCursor(Math.min(le, c + 1));
2592
+ return true;
2593
+ }
2594
+ if (key.upArrow) {
2595
+ walkHistory(1);
2596
+ return true;
2597
+ }
2598
+ if (key.downArrow) {
2599
+ walkHistory(-1);
2600
+ return true;
2601
+ }
2602
+ return true;
2603
+ };
2604
+ useInput3((input, key) => {
2605
+ if (key.tab && key.shift) {
2606
+ onShiftTab?.();
2607
+ return;
2608
+ }
2609
+ if (vim && key.escape && !normal) {
2610
+ setNormal(true);
2611
+ setCursor(Math.max(0, c - 1));
2612
+ return;
2613
+ }
2614
+ if (vim && normal && !key.escape && !key.tab && !key.ctrl) {
2615
+ vimKey(input, key);
2616
+ return;
2617
+ }
2618
+ if (key.escape) {
2619
+ onEscape?.();
2620
+ return;
2621
+ }
2622
+ if (key.tab) {
2623
+ onTab?.();
2624
+ return;
2625
+ }
2626
+ if (key.return) {
2627
+ if (key.meta) {
2628
+ set(value.slice(0, c) + "\n" + value.slice(c), c + 1);
2629
+ return;
2630
+ }
2631
+ if (value.slice(0, c).endsWith("\\")) {
2632
+ set(value.slice(0, c - 1) + "\n" + value.slice(c), c);
2633
+ return;
2634
+ }
2635
+ hist.current = { i: -1, draft: "" };
2636
+ onSubmit(value);
2637
+ setCursor(0);
2638
+ undo.current = [];
2639
+ return;
2640
+ }
2641
+ const lineStart = value.lastIndexOf("\n", c - 1) + 1;
2642
+ const lineEnd = value.indexOf("\n", c) < 0 ? value.length : value.indexOf("\n", c);
2643
+ if (key.upArrow) {
2644
+ if (lineStart > 0) {
2645
+ const prevStart = value.lastIndexOf("\n", lineStart - 2) + 1;
2646
+ setCursor(Math.min(prevStart + (c - lineStart), lineStart - 1));
2647
+ return;
2648
+ }
2649
+ walkHistory(1);
2650
+ return;
2651
+ }
2652
+ if (key.downArrow) {
2653
+ if (lineEnd < value.length) {
2654
+ const nextEnd = value.indexOf("\n", lineEnd + 1) < 0 ? value.length : value.indexOf("\n", lineEnd + 1);
2655
+ setCursor(Math.min(lineEnd + 1 + (c - lineStart), nextEnd));
2656
+ return;
2657
+ }
2658
+ walkHistory(-1);
2659
+ return;
2660
+ }
2661
+ if (key.leftArrow) {
2662
+ setCursor(key.meta || key.ctrl ? wordLeft(value, c) : c - 1);
2663
+ return;
2664
+ }
2665
+ if (key.rightArrow) {
2666
+ setCursor(key.meta || key.ctrl ? wordRight(value, c) : Math.min(value.length, c + 1));
2667
+ return;
2668
+ }
2669
+ if (key.backspace || key.delete) {
2670
+ if (key.meta) {
2671
+ const w = wordLeft(value, c);
2672
+ set(value.slice(0, w) + value.slice(c), w);
2673
+ return;
2674
+ }
2675
+ if (c > 0) set(value.slice(0, c - 1) + value.slice(c), c - 1);
2676
+ return;
2677
+ }
2678
+ if (key.ctrl) {
2679
+ if (input === "a") setCursor(lineStart);
2680
+ else if (input === "e") setCursor(lineEnd);
2681
+ else if (input === "u") set(value.slice(0, lineStart) + value.slice(c), lineStart);
2682
+ else if (input === "k") set(value.slice(0, c) + value.slice(lineEnd), c);
2683
+ else if (input === "w") {
2684
+ const w = wordLeft(value, c);
2685
+ set(value.slice(0, w) + value.slice(c), w);
2686
+ }
2687
+ return;
2688
+ }
2689
+ if (!input) return;
2690
+ const text = input.replace(/\r\n?/g, "\n").replace(/\x1b\[20[01]~/g, "");
2691
+ set(value.slice(0, c) + text + value.slice(c), c + text.length);
2692
+ }, { isActive: active });
2693
+ if (!value && placeholder) {
2694
+ return /* @__PURE__ */ jsx4(Text4, { children: active ? chalk2.inverse(placeholder[0]) + chalk2.gray(placeholder.slice(1)) : chalk2.gray(placeholder) });
2695
+ }
2696
+ const shown = active ? value.slice(0, c) + chalk2.inverse(value[c] === "\n" || c >= value.length ? " " : value[c]) + (value[c] === "\n" ? "\n" : "") + value.slice(c + 1) : value;
2697
+ return /* @__PURE__ */ jsx4(Box4, { flexDirection: "column", children: shown.split("\n").map((line, i) => /* @__PURE__ */ jsx4(Text4, { children: line || " " }, i)) });
2698
+ }
2699
+ function wordLeft(v, c) {
2700
+ let i = c;
2701
+ while (i > 0 && /\s/.test(v[i - 1])) i--;
2702
+ while (i > 0 && !/\s/.test(v[i - 1])) i--;
2703
+ return i;
2704
+ }
2705
+ function wordStartNext(v, c) {
2706
+ let i = c;
2707
+ while (i < v.length && !/\s/.test(v[i])) i++;
2708
+ while (i < v.length && /\s/.test(v[i])) i++;
2709
+ return i;
2710
+ }
2711
+ function wordEnd(v, c) {
2712
+ let i = c;
2713
+ while (i < v.length && /\s/.test(v[i])) i++;
2714
+ while (i < v.length && !/\s/.test(v[i])) i++;
2715
+ return i;
2716
+ }
2717
+ function wordRight(v, c) {
2718
+ let i = c;
2719
+ while (i < v.length && /\s/.test(v[i])) i++;
2720
+ while (i < v.length && !/\s/.test(v[i])) i++;
2721
+ return i;
2722
+ }
2723
+
2724
+ // src/ui/App.tsx
2725
+ import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
2726
+ var T3 = TONES.dark;
2727
+ function copyToSystemClipboard(text) {
2728
+ let oscSent = false;
2729
+ try {
2730
+ if (process.stdout && typeof process.stdout.write === "function" && !process.env.VITEST) {
2731
+ const b64 = Buffer.from(text, "utf8").toString("base64");
2732
+ process.stdout.write(`\x1B]52;c;${b64}\x07`);
2733
+ oscSent = true;
2734
+ }
2735
+ } catch {
2736
+ }
2737
+ const candidates = process.platform === "darwin" ? [["pbcopy", []]] : process.platform === "win32" ? [["clip", []]] : [
2738
+ ["wl-copy", []],
2739
+ ["xclip", ["-selection", "clipboard"]],
2740
+ ["xsel", ["--clipboard", "--input"]]
2741
+ ];
2742
+ for (const [cmd, args] of candidates) {
2743
+ try {
2744
+ const res = spawnSync2(cmd, args, { input: text, encoding: "utf8", timeout: 1500 });
2745
+ if (res.status === 0) {
2746
+ return { ok: true, method: oscSent ? `${cmd} + OSC 52` : cmd };
2747
+ }
2748
+ } catch {
2749
+ }
2750
+ }
2751
+ return { ok: true, method: oscSent ? "OSC 52 terminal clipboard" : "terminal buffer" };
2752
+ }
2753
+ function cleanSpeechText(md) {
2754
+ return md.replace(/```[\s\S]*?```/g, " Code block omitted. ").replace(/`([^`]+)`/g, "$1").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/[#*_~>|]/g, " ").replace(/\s+/g, " ").trim().slice(0, 1200);
2755
+ }
2756
+ function App({ app, version }) {
2757
+ const { exit } = useApp();
2758
+ const [s, setS] = useState3(app.snapshot());
2759
+ const [items, setItems] = useState3([{ id: 0, kind: "banner", text: "" }]);
2760
+ const [live, setLive] = useState3("");
2761
+ const [acts, setActs] = useState3([]);
2762
+ const [todo, setTodo] = useState3("");
2763
+ const [input, setInput] = useState3("");
2764
+ const [history, setHistory] = useState3([]);
2765
+ const [pick, setPick] = useState3(null);
2766
+ const [frame, setFrame] = useState3(0);
2767
+ const [typingEnergy, setTypingEnergy] = useState3(0);
2768
+ const [voiceOn, setVoiceOn] = useState3(false);
2769
+ const [copiedFlash, setCopiedFlash] = useState3(false);
2770
+ const [lastReply, setLastReply] = useState3("");
2771
+ const [login, setLogin] = useState3(null);
2772
+ const seq = useRef2(1);
2773
+ const liveRef = useRef2("");
2774
+ const actsRef = useRef2([]);
2775
+ const lastReplyRef = useRef2("");
2776
+ const voiceOnRef = useRef2(false);
2777
+ const speechProcRef = useRef2(null);
2778
+ const turnStartRef = useRef2(Date.now());
2779
+ const stopSpeech = () => {
2780
+ if (speechProcRef.current) {
2781
+ try {
2782
+ speechProcRef.current.kill();
2783
+ } catch {
2784
+ }
2785
+ speechProcRef.current = null;
2786
+ }
2787
+ };
2788
+ const speakLocally = (rawText) => {
2789
+ const clean = cleanSpeechText(rawText);
2790
+ if (!clean || process.env.VITEST || process.env.NODE_ENV === "test") return;
2791
+ stopSpeech();
2792
+ const candidates = process.platform === "darwin" ? [["say", [clean]]] : process.platform === "win32" ? [["powershell", ["-NoProfile", "-Command", `Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak(${JSON.stringify(clean)})`]]] : [
2793
+ ["spd-say", [clean]],
2794
+ ["espeak-ng", [clean]],
2795
+ ["espeak", [clean]]
2796
+ ];
2797
+ for (const [cmd, args] of candidates) {
2798
+ try {
2799
+ const proc = spawn4(cmd, args, { stdio: "ignore" });
2800
+ proc.on("error", () => {
2801
+ });
2802
+ proc.unref?.();
2803
+ speechProcRef.current = proc;
2804
+ break;
2805
+ } catch {
2806
+ }
2807
+ }
2808
+ };
2809
+ const push = (it) => setItems((xs) => [...xs, { ...it, id: seq.current++ }]);
2810
+ const info = (text, level = "info") => push({ kind: "notice", text, level });
2811
+ const copyLatestOutput = () => {
2812
+ const target = lastReplyRef.current || [...s.thread.messages].reverse().find((m) => m.role === "assistant" && m.content)?.content || "";
2813
+ if (!target) {
2814
+ info("No assistant output to copy yet.", "warn");
2815
+ return;
2816
+ }
2817
+ const res = copyToSystemClipboard(target);
2818
+ const lines = target.split(/\r?\n/).length;
2819
+ setCopiedFlash(true);
2820
+ const timer = setTimeout(() => setCopiedFlash(false), 2200);
2821
+ timer.unref?.();
2822
+ info(`\u2713 Copied latest Uchi output to clipboard (${target.length} chars, ${lines} line${lines === 1 ? "" : "s"} via ${res.method}).`);
2823
+ };
2824
+ useEffect(() => app.on((e) => {
2825
+ switch (e.type) {
2826
+ case "state": {
2827
+ const snap = app.snapshot();
2828
+ if (snap.busy && !s.busy) turnStartRef.current = Date.now();
2829
+ setS(snap);
2830
+ break;
2831
+ }
2832
+ case "delta":
2833
+ liveRef.current += e.text;
2834
+ setLive(liveRef.current);
2835
+ setFrame((f) => f + 1);
2836
+ break;
2837
+ case "activity":
2838
+ case "auto":
2839
+ actsRef.current = [...actsRef.current, e.note];
2840
+ setActs(actsRef.current);
2841
+ setFrame((f) => f + 1);
2842
+ break;
2843
+ case "todo":
2844
+ setTodo(e.text);
2845
+ break;
2846
+ case "notice":
2847
+ info(e.text, e.level);
2848
+ break;
2849
+ case "limit":
2850
+ info(`${e.limit.message || "You've reached your plan's limit."}
2851
+ Upgrade or add credits on the website: ${e.upgradeUrl}`, "warn");
2852
+ break;
2853
+ case "turn_end": {
2854
+ const r = e.result;
2855
+ if (actsRef.current.length) push({ kind: "activity", text: "", lines: actsRef.current });
2856
+ actsRef.current = [];
2857
+ setActs([]);
2858
+ if (r.reply?.content) {
2859
+ lastReplyRef.current = r.reply.content;
2860
+ setLastReply(r.reply.content);
2861
+ push({ kind: "assistant", text: r.reply.content });
2862
+ if (voiceOnRef.current) {
2863
+ speakLocally(r.reply.content);
2864
+ }
2865
+ }
2866
+ if (r.error && !r.limit) info(r.error, "error");
2867
+ if (r.stopped) info("Stopped.", "warn");
2868
+ liveRef.current = "";
2869
+ setLive("");
2870
+ setTodo("");
2871
+ break;
2872
+ }
2873
+ }
2874
+ }), [app]);
2875
+ useEffect(() => {
2876
+ if (!s.busy && !voiceOn && typingEnergy <= 0) return;
2877
+ const t = setInterval(() => {
2878
+ setFrame((f) => f + 1);
2879
+ setTypingEnergy((e) => e > 0 ? e - 1 : 0);
2880
+ }, 120);
2881
+ t.unref?.();
2882
+ return () => clearInterval(t);
2883
+ }, [s.busy, voiceOn, typingEnergy > 0]);
2884
+ useEffect(() => () => stopSpeech(), []);
2885
+ const cycleApprovals = () => {
2886
+ const i = APPROVALS.findIndex((a) => a.id === app.policy.approvals);
2887
+ const next = APPROVALS[(i + 1) % APPROVALS.length];
2888
+ app.setPolicy({ approvals: next.id });
2889
+ info(`Approvals: ${next.label} \u2014 ${next.help}`);
2890
+ };
2891
+ useInput4((ch, key) => {
2892
+ if (key.ctrl && ch === "c") {
2893
+ if (s.busy) app.stop();
2894
+ else {
2895
+ stopSpeech();
2896
+ app.close();
2897
+ exit();
2898
+ }
2899
+ }
2900
+ if (key.ctrl && ch === "y") {
2901
+ copyLatestOutput();
2902
+ }
2903
+ if (key.escape && s.busy && !s.pending.length) app.stop();
2904
+ });
2905
+ const handleInputChange = (val) => {
2906
+ setInput(val);
2907
+ setFrame((f) => f + 1);
2908
+ setTypingEnergy(5);
2909
+ };
2910
+ const run = async (raw) => {
2911
+ const text = raw.trim();
2912
+ if (!text) return;
2913
+ setHistory((h) => [...h.filter((x) => x !== text), text].slice(-200));
2914
+ setInput("");
2915
+ if (text.startsWith("#")) {
2916
+ const { instructions } = await Promise.resolve().then(() => (init_src(), src_exports));
2917
+ info(`Added to ${instructions.addLine(app.folder, text.slice(1))}`);
2918
+ return;
2919
+ }
2920
+ if (text.startsWith("/")) return command(text);
2921
+ push({ kind: "user", text });
2922
+ turnStartRef.current = Date.now();
2923
+ await app.send(text);
2924
+ };
2925
+ const command = async (text) => {
2926
+ const [name0, ...rest] = text.slice(1).split(/\s+/);
2927
+ const arg = rest.join(" ");
2928
+ const low0 = name0.toLowerCase();
2929
+ const name = resolveCommandName(low0) ?? low0;
2930
+ switch (name) {
2931
+ case "quit":
2932
+ stopSpeech();
2933
+ app.close();
2934
+ exit();
2935
+ return;
2936
+ case "copy":
2937
+ copyLatestOutput();
2938
+ return;
2939
+ case "swarm": {
2940
+ const prompt = arg ? `/swarm ${arg}` : "/swarm";
2941
+ push({ kind: "user", text: prompt });
2942
+ turnStartRef.current = Date.now();
2943
+ await app.send(prompt);
2944
+ return;
2945
+ }
2946
+ case "flywheel": {
2947
+ push({ kind: "user", text: "/flywheel" });
2948
+ turnStartRef.current = Date.now();
2949
+ await app.send("/flywheel");
2950
+ return;
2951
+ }
2952
+ case "connectors": {
2953
+ push({ kind: "user", text: "/connectors" });
2954
+ turnStartRef.current = Date.now();
2955
+ await app.send("/connectors");
2956
+ return;
2957
+ }
2958
+ case "search": {
2959
+ if (!arg.trim()) {
2960
+ info("Usage: /search <query> (searches allowlisted read-only web sources)");
2961
+ return;
2962
+ }
2963
+ const prompt = `Search the web for ${arg.trim()}`;
2964
+ push({ kind: "user", text: prompt });
2965
+ turnStartRef.current = Date.now();
2966
+ await app.send(prompt);
2967
+ return;
2968
+ }
2969
+ case "remember": {
2970
+ if (!arg.trim()) {
2971
+ info("Usage: /remember <fact> (saves to your Personal Knowledge Graph)");
2972
+ return;
2973
+ }
2974
+ const prompt = /^remember\s+that\b/i.test(arg.trim()) ? arg.trim() : `Remember that ${arg.trim()}`;
2975
+ push({ kind: "user", text: prompt });
2976
+ turnStartRef.current = Date.now();
2977
+ await app.send(prompt);
2978
+ return;
2979
+ }
2980
+ case "bci": {
2981
+ const prompt = arg.trim() ? `Decode BCI neural intent: ${arg.trim()}` : "BCI: status";
2982
+ push({ kind: "user", text: prompt });
2983
+ turnStartRef.current = Date.now();
2984
+ await app.send(prompt);
2985
+ return;
2986
+ }
2987
+ case "rigor": {
2988
+ const sub = arg.trim().toLowerCase();
2989
+ const next = app.setRigor(sub === "on" ? true : sub === "off" ? false : void 0);
2990
+ info(next ? "\u25C8 Rigor Mode ON \u2014 Every claim is tagged [Tested], [Supported], or [Conjecture] with a verification test." : "\u25C7 Rigor Mode OFF.");
2991
+ return;
2992
+ }
2993
+ case "study": {
2994
+ const sub = arg.trim().toLowerCase();
2995
+ const next = app.setStudy(sub === "on" ? true : sub === "off" ? false : void 0);
2996
+ info(next ? "\u25C8 Study Mode ON \u2014 Uchi guides step-by-step from first principles with diagnostic checks." : "\u25C7 Study Mode OFF.");
2997
+ return;
2998
+ }
2999
+ case "uchi2": {
3000
+ app.setModel("uchi");
3001
+ info("Model: Uchi 2 (Default Flagship)");
3002
+ return;
3003
+ }
3004
+ case "uchi1": {
3005
+ app.setModel("uchi-1");
3006
+ info("Model: Uchi 1 (Generation 1)");
3007
+ return;
3008
+ }
3009
+ case "voice": {
3010
+ const sub = arg.trim().toLowerCase();
3011
+ if (sub === "stop" || sub === "mute") {
3012
+ stopSpeech();
3013
+ info("Stopped local voice playback.");
3014
+ return;
3015
+ }
3016
+ const next = sub === "on" ? true : sub === "off" ? false : !voiceOnRef.current;
3017
+ voiceOnRef.current = next;
3018
+ setVoiceOn(next);
3019
+ if (!next) stopSpeech();
3020
+ info(
3021
+ next ? "\u25C9 Voice Mode ON ($0.00 on-device speech synthesis). Uchi will speak replies aloud and animate the live acoustic wave. Use `/voice off` or `/voice stop` anytime." : "\u25CE Voice Mode OFF."
3022
+ );
3023
+ if (next && lastReplyRef.current && sub !== "on") {
3024
+ speakLocally(lastReplyRef.current);
3025
+ }
3026
+ return;
3027
+ }
3028
+ case "help":
3029
+ info(COMMANDS.map((c) => `/${c.name}${c.args ? " " + c.args : ""}`.padEnd(22) + c.help).join("\n") + "\n" + "# text".padEnd(22) + "add a line to PROMETHEA.md\n" + "@path".padEnd(22) + "attach a file\n" + "Ctrl+Y".padEnd(22) + "copy the latest output returned by Uchi\n" + "Shift+Tab".padEnd(22) + "cycle approvals \xB7 Esc stops a turn \xB7 Ctrl+C quits");
3030
+ return;
3031
+ case "new":
3032
+ app.newThread();
3033
+ info("New thread.");
3034
+ return;
3035
+ case "model": {
3036
+ const sub = arg.trim().toLowerCase();
3037
+ if (sub === "uchi" || sub === "uchi2" || sub === "uchi-2" || sub === "flagship") {
3038
+ app.setModel("uchi");
3039
+ info("Model: Uchi 2 (Default Flagship)");
3040
+ return;
3041
+ }
3042
+ if (sub === "uchi-1" || sub === "uchi1") {
3043
+ app.setModel("uchi-1");
3044
+ info("Model: Uchi 1 (Generation 1)");
3045
+ return;
3046
+ }
3047
+ setPick({
3048
+ title: "Model",
3049
+ items: s.models.map((m) => ({ label: m.name + (m.flagship ? " \u2605 flagship" : ""), hint: m.description, value: m.id })),
3050
+ onPick: (v) => {
3051
+ app.setModel(v);
3052
+ info(`Model: ${s.models.find((m) => m.id === v)?.name ?? v}`);
3053
+ }
3054
+ });
3055
+ return;
3056
+ }
3057
+ case "effort": {
3058
+ const sub = arg.trim().toLowerCase();
3059
+ if (sub === "low" || sub === "medium" || sub === "high") {
3060
+ app.setEffort(sub);
3061
+ info(`Effort: ${sub}`);
3062
+ return;
3063
+ }
3064
+ setPick({
3065
+ title: "Effort",
3066
+ items: s.efforts.map((e) => ({ label: e.label + (e.allowed ? "" : " (locked)"), hint: e.allowed ? `${e.help} \xB7 uses ${e.multiplier}\xD7 tokens` : e.why, value: e.id })),
3067
+ onPick: (v) => {
3068
+ app.setEffort(v);
3069
+ info(`Effort: ${v}`);
3070
+ }
3071
+ });
3072
+ return;
3073
+ }
3074
+ case "approvals":
3075
+ setPick({
3076
+ title: "Approvals",
3077
+ items: APPROVALS.map((a) => ({ label: a.label, hint: a.help, value: a.id })),
3078
+ onPick: (v) => app.setPolicy({ approvals: v })
3079
+ });
3080
+ return;
3081
+ case "sandbox":
3082
+ setPick({
3083
+ title: "Sandbox",
3084
+ items: SANDBOXES.map((a) => ({ label: a.label, hint: a.help, value: a.id })),
3085
+ onPick: (v) => app.setPolicy({ sandbox: v })
3086
+ });
3087
+ return;
3088
+ case "resume": {
3089
+ const ts = await app.threads().catch((e) => {
3090
+ info(e.message, "error");
3091
+ return [];
3092
+ });
3093
+ if (!ts.length) {
3094
+ info(s.signedIn ? "No earlier threads." : "Sign in (/login) to keep threads.");
3095
+ return;
3096
+ }
3097
+ setPick({
3098
+ title: "Resume",
3099
+ items: ts.map((t) => ({ label: t.title || "Untitled", hint: (t.folder ? path7.basename(t.folder) + " \xB7 " : "") + new Date(t.updatedAt).toLocaleString(), value: t.id })),
3100
+ onPick: async (v) => {
3101
+ await app.resume(v);
3102
+ const p = app.snapshot().thread.messages;
3103
+ for (const m of p) {
3104
+ if (m.role === "assistant" && m.content) {
3105
+ lastReplyRef.current = m.content;
3106
+ setLastReply(m.content);
3107
+ }
3108
+ push({ kind: m.role === "user" ? "user" : "assistant", text: m.content });
3109
+ }
3110
+ }
3111
+ });
3112
+ return;
3113
+ }
3114
+ case "plan":
3115
+ if (!arg) {
3116
+ info("Usage: /plan <task>");
3117
+ return;
3118
+ }
3119
+ push({ kind: "user", text: `/plan ${arg}` });
3120
+ await app.send(arg, { plan: true });
3121
+ return;
3122
+ case "btw":
3123
+ if (!arg) {
3124
+ info("Usage: /btw <side question>");
3125
+ return;
3126
+ }
3127
+ push({ kind: "user", text: `[btw] ${arg}` });
3128
+ await app.send(arg, { btw: true });
3129
+ return;
3130
+ case "code":
3131
+ if (!arg) {
3132
+ info("Usage: /code <task>");
3133
+ return;
3134
+ }
3135
+ push({ kind: "user", text: `/code ${arg}` });
3136
+ await app.send(arg, { code: true });
3137
+ return;
3138
+ case "skills": {
3139
+ const { instructions } = await Promise.resolve().then(() => (init_src(), src_exports));
3140
+ const loadedSkills = instructions.loadSkills(app.folder);
3141
+ const ruleFiles = s.instructionFiles;
3142
+ const lines = [
3143
+ `Instruction files: ${ruleFiles.length ? ruleFiles.join(", ") : "none (/init to create PROMETHEA.md; also supports UCHI.md, SUNDIAL.md, CLAUDE.md, AGENTS.md)"}`,
3144
+ `Active skills (${loadedSkills.length}): ${loadedSkills.length ? loadedSkills.map((sk) => `${sk.name} (${sk.path})`).join(", ") : "none (.sundial/skills/<name>/SKILL.md)"}`
3145
+ ];
3146
+ info(lines.join("\n"));
3147
+ return;
3148
+ }
3149
+ case "obsidian": {
3150
+ const vaultDir = path7.resolve(app.folder, arg || ".");
3151
+ if (!fs8.existsSync(vaultDir)) {
3152
+ info(`Obsidian vault folder not found: ${vaultDir}`, "error");
3153
+ return;
3154
+ }
3155
+ const mdNotes = [];
3156
+ const walk2 = (d) => {
3157
+ for (const entry of fs8.readdirSync(d, { withFileTypes: true })) {
3158
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
3159
+ const full = path7.join(d, entry.name);
3160
+ if (entry.isDirectory()) walk2(full);
3161
+ else if (entry.name.endsWith(".md") && mdNotes.length < 300) {
3162
+ try {
3163
+ mdNotes.push({ path: path7.relative(vaultDir, full), content: fs8.readFileSync(full, "utf8") });
3164
+ } catch {
3165
+ }
3166
+ }
3167
+ }
3168
+ };
3169
+ walk2(vaultDir);
3170
+ if (!mdNotes.length) {
3171
+ info(`No Markdown (.md) notes found in ${vaultDir}`, "warn");
3172
+ return;
3173
+ }
3174
+ try {
3175
+ const res = await app.api.json(
3176
+ "/api/obsidian",
3177
+ { method: "POST", body: JSON.stringify({ mode: "merge", notes: mdNotes }) }
3178
+ );
3179
+ info(`Obsidian Vault synced: ${res.notesProcessed} notes \u2192 ${res.extractedEdges} new edges (${res.totalKnowledgeGraphEdges} total in your Personal Knowledge Graph).`);
3180
+ } catch (e) {
3181
+ info(`Obsidian sync failed: ${e.message}`, "error");
3182
+ }
3183
+ return;
3184
+ }
3185
+ case "remote": {
3186
+ const sub = arg.trim();
3187
+ if (sub && sub.toLowerCase() !== "pair") {
3188
+ const prompt = `/remote ${sub}`;
3189
+ push({ kind: "user", text: prompt });
3190
+ turnStartRef.current = Date.now();
3191
+ await app.send(prompt);
3192
+ return;
3193
+ }
3194
+ if (!s.signedIn) {
3195
+ push({ kind: "user", text: "/remote status" });
3196
+ turnStartRef.current = Date.now();
3197
+ await app.send("/remote status");
3198
+ return;
3199
+ }
3200
+ try {
3201
+ const os4 = await import("node:os");
3202
+ const res = await app.api.json(
3203
+ "/api/remote",
3204
+ { method: "POST", body: JSON.stringify({ action: "register", hostname: os4.hostname(), cwd: app.folder }) }
3205
+ );
3206
+ info(`Remote Control active: session ${res.session.sessionId} paired with ${s.server} (${os4.hostname()}:${app.folder})`);
3207
+ } catch (e) {
3208
+ info(`Remote Control pairing failed: ${e.message}`, "error");
3209
+ }
3210
+ return;
3211
+ }
3212
+ case "diff": {
3213
+ const ch = app.host.review();
3214
+ if (!ch.length) {
3215
+ info("No changes in this thread.");
3216
+ return;
3217
+ }
3218
+ for (const c of ch) push({ kind: "diff", text: c.path, lines: diffLines(c.path, c.before, c.after).diff });
3219
+ return;
3220
+ }
3221
+ case "undo": {
3222
+ const c = app.undo();
3223
+ info(c ? `Undid the change to ${c.path}.` : "Nothing to undo (or the file changed since).");
3224
+ return;
3225
+ }
3226
+ case "compact": {
3227
+ const r = await app.compact(arg || void 0);
3228
+ info("error" in r ? r.error : `Compacted: ${r.summarized} earlier exchange${r.summarized === 1 ? "" : "s"} summarised.`);
3229
+ return;
3230
+ }
3231
+ case "status":
3232
+ case "usage": {
3233
+ const lines = [
3234
+ `Account ${s.email ?? "not signed in"}${s.plan ? ` \xB7 ${s.plan.name} plan` : ""}`,
3235
+ ...s.freeMessages ? [`Free ${s.freeMessages.left} of ${s.freeMessages.limit} free messages left`] : [],
3236
+ ...s.windows.map((w) => `${w.id.padEnd(9)} ${meter(w.pct, 20)} about ${w.messagesLeft} messages left (${Math.round(w.pct)}% used)${w.resetsAt ? ` \xB7 resets ${new Date(w.resetsAt).toLocaleString()}` : ""}`),
3237
+ ...s.credits != null ? [`Credits $${s.credits.toFixed(2)} \xB7 pay as you go past your allowance${s.plan?.overage ? "" : " (not on this plan)"}`] : [],
3238
+ ...name === "status" ? [
3239
+ `Model ${s.models.find((m) => m.id === s.model)?.name ?? s.model} \xB7 ${s.effort}${s.rigor ? " \xB7 rigor" : ""}${s.study ? " \xB7 study" : ""}`,
3240
+ `Policy ${s.policy.approvals} \xB7 ${s.policy.sandbox} \xB7 network ${s.policy.network ? "on" : "off"} \xB7 OS sandbox ${s.osSandbox ? "yes" : "no"}`,
3241
+ `Folder ${s.folder}`,
3242
+ `Rules ${s.instructionFiles.join(", ") || "none (/init)"}`,
3243
+ `Server ${s.server}`
3244
+ ] : [],
3245
+ `Billing ${s.links.usage}`
3246
+ ];
3247
+ info(lines.join("\n"));
3248
+ return;
3249
+ }
3250
+ case "upgrade":
3251
+ openBrowser(s.links.pricing);
3252
+ info(`Plans and pricing: ${s.links.pricing}`);
3253
+ return;
3254
+ case "knowledge":
3255
+ openBrowser(s.links.knowledge);
3256
+ info(`Knowledge graphs: ${s.links.knowledge}`);
3257
+ return;
3258
+ case "init": {
3259
+ const p = path7.join(app.folder, "PROMETHEA.md");
3260
+ if (fs8.existsSync(p)) {
3261
+ info(`${p} already exists.`);
3262
+ return;
3263
+ }
3264
+ fs8.writeFileSync(p, "# Project instructions\n\n- How to build and test:\n- Conventions:\n");
3265
+ info(`Created ${p}. Edit it; it goes with every turn in this folder.`);
3266
+ return;
3267
+ }
3268
+ case "login": {
3269
+ try {
3270
+ const email = await app.login((code, url) => {
3271
+ setLogin({ code, url });
3272
+ openBrowser(url);
3273
+ });
3274
+ info(`Signed in as ${email}.`);
3275
+ } catch (e) {
3276
+ info(e.message, "error");
3277
+ }
3278
+ setLogin(null);
3279
+ return;
3280
+ }
3281
+ case "logout":
3282
+ await app.logout();
3283
+ info("Signed out on this machine.");
3284
+ return;
3285
+ default:
3286
+ info(`Unknown command /${name0}. /help lists them.`, "warn");
3287
+ }
3288
+ };
3289
+ const suggestions = useMemo(() => input.startsWith("/") && !input.includes(" ") ? complete(input).slice(0, 8) : [], [input]);
3290
+ const pending = s.pending[0];
3291
+ const model = s.models.find((m) => m.id === s.model)?.name ?? s.model;
3292
+ const isTyping = typingEnergy > 0 || input.length > 0;
3293
+ const liveWave = equalizerWave(frame, Boolean(s.busy || voiceOn || typingEnergy > 0), 12);
3294
+ const streamedTokens = live ? Math.max(1, Math.round(live.length / 4)) : 0;
3295
+ const livePreview = useMemo(() => {
3296
+ if (!live) return "";
3297
+ const lines = live.split("\n");
3298
+ if (lines.length <= 16) return renderMarkdown(live);
3299
+ return `\u2026 (${lines.length - 16} lines streamed \u2014 full output prints on completion)
3300
+ ` + lines.slice(-16).join("\n");
3301
+ }, [live]);
3302
+ return /* @__PURE__ */ jsxs4(Box5, { flexDirection: "column", children: [
3303
+ /* @__PURE__ */ jsx5(Static, { items, children: (it) => /* @__PURE__ */ jsx5(ItemView, { it, s, version, modelName: model }, it.id) }),
3304
+ s.busy && /* @__PURE__ */ jsxs4(Box5, { flexDirection: "column", marginTop: 1, borderStyle: "round", borderColor: COLORS.fire, paddingX: 1, children: [
3305
+ /* @__PURE__ */ jsxs4(Box5, { justifyContent: "space-between", children: [
3306
+ /* @__PURE__ */ jsxs4(Text5, { color: COLORS.fire, bold: true, children: [
3307
+ orbitFrame(frame),
3308
+ " ",
3309
+ PULSE[frame % PULSE.length],
3310
+ " ",
3311
+ model,
3312
+ " \xB7 Neural Stream Active"
3313
+ ] }),
3314
+ /* @__PURE__ */ jsxs4(Text5, { color: COLORS.coral, children: [
3315
+ liveWave,
3316
+ " ",
3317
+ streamedTokens > 0 ? `\xB7 ${streamedTokens} tok` : "",
3318
+ " \xB7 Esc to stop"
3319
+ ] })
3320
+ ] }),
3321
+ todo && /* @__PURE__ */ jsx5(Text5, { color: T3.muted, children: todo }),
3322
+ acts.slice(-6).map((a, i) => /* @__PURE__ */ jsxs4(Text5, { color: T3.muted, children: [
3323
+ " \u23BF ",
3324
+ a
3325
+ ] }, i)),
3326
+ livePreview && /* @__PURE__ */ jsx5(Box5, { marginTop: 0, children: /* @__PURE__ */ jsx5(Text5, { children: livePreview }) }),
3327
+ !pending && /* @__PURE__ */ jsxs4(Text5, { color: COLORS.fire, children: [
3328
+ PULSE[frame % PULSE.length],
3329
+ " ",
3330
+ /* @__PURE__ */ jsxs4(Text5, { color: T3.muted, children: [
3331
+ model,
3332
+ " is working \xB7 Esc to stop"
3333
+ ] })
3334
+ ] })
3335
+ ] }),
3336
+ pending && /* @__PURE__ */ jsx5(ApprovalBox, { a: pending, onAnswer: (x) => app.respond(pending.id, x) }),
3337
+ login && /* @__PURE__ */ jsxs4(Box5, { borderStyle: "round", borderColor: COLORS.coral, paddingX: 1, flexDirection: "column", children: [
3338
+ /* @__PURE__ */ jsxs4(Text5, { children: [
3339
+ "Sign in in your browser. Your code: ",
3340
+ /* @__PURE__ */ jsx5(Text5, { bold: true, color: COLORS.fire, children: login.code })
3341
+ ] }),
3342
+ /* @__PURE__ */ jsx5(Text5, { color: T3.muted, children: login.url })
3343
+ ] }),
3344
+ pick && /* @__PURE__ */ jsx5(Picker, { title: pick.title, items: pick.items, onPick: (v) => {
3345
+ setPick(null);
3346
+ pick.onPick(v);
3347
+ }, onCancel: () => setPick(null) }),
3348
+ !pick && !pending && /* @__PURE__ */ jsxs4(Box5, { flexDirection: "column", marginTop: 1, children: [
3349
+ /* @__PURE__ */ jsxs4(Box5, { justifyContent: "space-between", paddingX: 1, children: [
3350
+ /* @__PURE__ */ jsx5(Text5, { color: typingEnergy > 0 || voiceOn ? COLORS.fire : T3.faint, children: typingEnergy > 0 ? `${orbitFrame(frame)} LIVE INPUT \xB7 ${liveWave}` : voiceOn ? `\u25C9 VOICE LINK ACTIVE ($0 LOCAL) \xB7 ${liveWave}` : `\u2726 ${model.toUpperCase()} READY \xB7 ${liveWave}` }),
3351
+ /* @__PURE__ */ jsxs4(Text5, { color: T3.faint, children: [
3352
+ lastReply ? "Ctrl+Y or /copy: copy latest output \xB7 " : "",
3353
+ "/voice: talk \xB7 /swarm: tandem"
3354
+ ] })
3355
+ ] }),
3356
+ /* @__PURE__ */ jsxs4(Box5, { borderStyle: "round", borderColor: s.busy ? T3.border : typingEnergy > 0 || voiceOn ? COLORS.fire : COLORS.coral, paddingX: 1, children: [
3357
+ /* @__PURE__ */ jsx5(Text5, { color: COLORS.fire, children: typingEnergy > 0 ? `${orbitFrame(frame)} \u203A ` : voiceOn ? "\u25C9 \u203A " : "\u203A " }),
3358
+ /* @__PURE__ */ jsx5(
3359
+ TextInput,
3360
+ {
3361
+ value: input,
3362
+ onChange: handleInputChange,
3363
+ onSubmit: run,
3364
+ history,
3365
+ active: !pick && !pending && !login,
3366
+ placeholder: s.busy ? "Working\u2026 (Esc to stop)" : `Ask ${model}, type / for commands, or /voice to talk`,
3367
+ onTab: () => {
3368
+ if (suggestions[0]) handleInputChange(`/${suggestions[0].name} `);
3369
+ },
3370
+ onShiftTab: cycleApprovals
3371
+ }
3372
+ )
3373
+ ] }),
3374
+ suggestions.map((c) => /* @__PURE__ */ jsxs4(Text5, { color: T3.muted, children: [
3375
+ " ",
3376
+ /* @__PURE__ */ jsxs4(Text5, { color: COLORS.coral, children: [
3377
+ "/",
3378
+ c.name.padEnd(12)
3379
+ ] }),
3380
+ c.help
3381
+ ] }, c.name)),
3382
+ /* @__PURE__ */ jsx5(
3383
+ Status,
3384
+ {
3385
+ s,
3386
+ voiceOn,
3387
+ copiedAt: copiedFlash,
3388
+ hasLatestReply: Boolean(lastReply),
3389
+ tick: frame,
3390
+ activeWave: Boolean(typingEnergy > 0 || isTyping)
3391
+ }
3392
+ )
3393
+ ] })
3394
+ ] });
3395
+ }
3396
+ function ItemView({ it, s, version, modelName }) {
3397
+ if (it.kind === "banner") {
3398
+ return /* @__PURE__ */ jsx5(Box5, { marginBottom: 1, flexDirection: "column", children: /* @__PURE__ */ jsxs4(Box5, { children: [
3399
+ /* @__PURE__ */ jsx5(Box5, { flexDirection: "column", marginRight: 2, children: logoRuns().map((runs, i) => /* @__PURE__ */ jsx5(Text5, { children: runs.map(([t, c], j) => /* @__PURE__ */ jsx5(Text5, { color: c, children: t }, j)) }, i)) }),
3400
+ /* @__PURE__ */ jsxs4(Box5, { flexDirection: "column", justifyContent: "center", children: [
3401
+ /* @__PURE__ */ jsxs4(Text5, { bold: true, color: COLORS.alabaster, children: [
3402
+ "Sundial ",
3403
+ /* @__PURE__ */ jsxs4(Text5, { color: T3.faint, children: [
3404
+ "v",
3405
+ version
3406
+ ] }),
3407
+ " ",
3408
+ /* @__PURE__ */ jsxs4(Text5, { color: COLORS.fire, children: [
3409
+ "\u2726 ",
3410
+ modelName
3411
+ ] })
3412
+ ] }),
3413
+ /* @__PURE__ */ jsx5(Text5, { color: T3.muted, children: "Promethea Research \xB7 Cognitive Architecture & Tandem Swarm" }),
3414
+ /* @__PURE__ */ jsx5(Text5, { color: T3.muted, children: s.folder }),
3415
+ /* @__PURE__ */ jsxs4(Text5, { color: T3.faint, children: [
3416
+ s.signedIn ? `${s.email} \xB7 ${s.plan?.name ?? ""}` : "Not signed in: /login (or ask as a guest)",
3417
+ " \xB7 /help \xB7 /voice \xB7 /copy (Ctrl+Y)"
3418
+ ] })
3419
+ ] })
3420
+ ] }) });
3421
+ }
3422
+ if (it.kind === "user") return /* @__PURE__ */ jsxs4(Box5, { marginTop: 1, children: [
3423
+ /* @__PURE__ */ jsx5(Text5, { color: COLORS.coral, children: "\u203A " }),
3424
+ /* @__PURE__ */ jsx5(Text5, { color: COLORS.alabaster, children: it.text })
3425
+ ] });
3426
+ if (it.kind === "assistant") {
3427
+ return /* @__PURE__ */ jsxs4(Box5, { marginTop: 1, flexDirection: "column", children: [
3428
+ /* @__PURE__ */ jsxs4(Text5, { color: COLORS.fire, children: [
3429
+ "\u25C8 ",
3430
+ /* @__PURE__ */ jsx5(Text5, { bold: true, color: COLORS.alabaster, children: modelName }),
3431
+ " ",
3432
+ /* @__PURE__ */ jsx5(Text5, { color: T3.faint, children: "\xB7 /copy or Ctrl+Y to copy" })
3433
+ ] }),
3434
+ /* @__PURE__ */ jsx5(Text5, { children: renderMarkdown(it.text) })
3435
+ ] });
3436
+ }
3437
+ if (it.kind === "activity") return /* @__PURE__ */ jsx5(Box5, { flexDirection: "column", marginTop: 1, children: it.lines.map((l, i) => /* @__PURE__ */ jsxs4(Text5, { color: T3.muted, children: [
3438
+ " \u23BF ",
3439
+ l
3440
+ ] }, i)) });
3441
+ if (it.kind === "diff") return /* @__PURE__ */ jsxs4(Box5, { flexDirection: "column", marginTop: 1, children: [
3442
+ /* @__PURE__ */ jsx5(Text5, { bold: true, children: it.text }),
3443
+ /* @__PURE__ */ jsx5(DiffView, { lines: it.lines, max: 200 })
3444
+ ] });
3445
+ const color = it.level === "error" ? COLORS.fire : it.level === "warn" ? COLORS.coral : T3.muted;
3446
+ return /* @__PURE__ */ jsx5(Box5, { marginTop: 1, children: /* @__PURE__ */ jsx5(Text5, { color, children: it.text }) });
3447
+ }
3448
+
3449
+ // src/index.tsx
3450
+ import { jsx as jsx6 } from "react/jsx-runtime";
3451
+ function parse(argv) {
3452
+ const o = {};
3453
+ const pos = [];
3454
+ for (let i = 0; i < argv.length; i++) {
3455
+ const a = argv[i];
3456
+ if (a.startsWith("--")) {
3457
+ const [k, v] = a.slice(2).split("=", 2);
3458
+ o[k] = v ?? (argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[++i] : "true");
3459
+ } else pos.push(a);
3460
+ }
3461
+ return { o, pos };
3462
+ }
3463
+ async function main() {
3464
+ const { o, pos } = parse(process.argv.slice(2));
3465
+ if (o.version) {
3466
+ console.log(VERSION);
3467
+ return;
3468
+ }
3469
+ const isExec = pos[0] === "exec";
3470
+ const isRemote = pos[0] === "remote";
3471
+ const folder = (isExec ? pos[2] : isRemote ? pos[1] : pos[0]) ?? process.cwd();
3472
+ const app = new SundialApp(folder, config_exports.serverUrl(o.server));
3473
+ config_exports.addProject(app.folder);
3474
+ if (o.approvals) app.policy.approvals = o.approvals;
3475
+ if (o.sandbox) app.policy.sandbox = o.sandbox;
3476
+ await app.refresh();
3477
+ if (o.model) app.session.model = o.model;
3478
+ if (o.effort) app.session.effort = o.effort;
3479
+ if (isRemote) {
3480
+ const os4 = await import("node:os");
3481
+ const res = await app.api.json(
3482
+ "/api/remote",
3483
+ { method: "POST", body: JSON.stringify({ action: "register", hostname: os4.hostname(), cwd: app.folder }) }
3484
+ );
3485
+ console.log(`Remote Control active: session ${res.session.sessionId} paired with ${app.snapshot().server} (${os4.hostname()}:${app.folder})`);
3486
+ app.close();
3487
+ return;
3488
+ }
3489
+ await app.startMcp();
3490
+ if (isExec) {
3491
+ const turns = o.turns ? JSON.parse(fs9.readFileSync(o.turns, "utf8")) : [pos[1] ?? ""];
3492
+ const json = o.json === "true";
3493
+ app.on((e) => {
3494
+ if (e.type === "approval") app.respond(e.approval.id, "no");
3495
+ if (e.type === "delta" && !json) process.stdout.write(e.text);
3496
+ if (e.type === "activity" || e.type === "auto") process.stderr.write(`\xB7 ${e.note}
3497
+ `);
3498
+ if (e.type === "limit") process.stderr.write(`${e.limit.message}
3499
+ Upgrade: ${e.upgradeUrl}
3500
+ `);
3501
+ });
3502
+ const replies = [], errors = [];
3503
+ let failed = false;
3504
+ const gap = o.pace ? 6e4 / Math.max(1, Number(o.pace)) : 0;
3505
+ let last = 0;
3506
+ for (const t of turns) {
3507
+ if (gap && last) await new Promise((res) => setTimeout(res, Math.max(0, last + gap - Date.now())));
3508
+ last = Date.now();
3509
+ const r = await app.send(t, { code: o.code === "true" });
3510
+ replies.push(r?.reply?.content ?? "");
3511
+ errors.push(r?.error ?? (r?.limit ? "limit" : r ? null : "no reply"));
3512
+ if (!r || r.error || r.limit) {
3513
+ failed = true;
3514
+ if (r?.error) process.stderr.write(r.error + "\n");
3515
+ break;
3516
+ }
3517
+ if (!json) process.stdout.write("\n");
3518
+ }
3519
+ if (json) process.stdout.write(JSON.stringify({ replies, errors }) + "\n");
3520
+ app.close();
3521
+ process.exitCode = failed ? 1 : 0;
3522
+ return;
3523
+ }
3524
+ const ink = render(/* @__PURE__ */ jsx6(App, { app, version: VERSION }), { exitOnCtrlC: false });
3525
+ await ink.waitUntilExit();
3526
+ }
3527
+ main().catch((e) => {
3528
+ console.error(e.message);
3529
+ process.exit(1);
3530
+ });