sakuraai 0.0.16 → 0.0.18

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.
Files changed (2) hide show
  1. package/dist/index.js +1423 -460
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -24,16 +24,16 @@ function readTsnetState() {
24
24
  function ensureDir(dir) {
25
25
  fs.mkdirSync(dir, { recursive: true });
26
26
  }
27
- function readJson(file, fallback) {
27
+ function readJson(file2, fallback) {
28
28
  try {
29
- return { ...fallback, ...JSON.parse(fs.readFileSync(file, "utf8")) };
29
+ return { ...fallback, ...JSON.parse(fs.readFileSync(file2, "utf8")) };
30
30
  } catch {
31
31
  return fallback;
32
32
  }
33
33
  }
34
- function writeJson(file, value) {
35
- ensureDir(path.dirname(file));
36
- fs.writeFileSync(file, JSON.stringify(value, null, 2) + "\n", { mode: 384 });
34
+ function writeJson(file2, value) {
35
+ ensureDir(path.dirname(file2));
36
+ fs.writeFileSync(file2, JSON.stringify(value, null, 2) + "\n", { mode: 384 });
37
37
  }
38
38
  function defaultConfig() {
39
39
  const hostname2 = os.hostname();
@@ -103,8 +103,8 @@ var init_config = __esm({
103
103
  function apiBase() {
104
104
  return (loadAuth().serverUrl || DEFAULT_API_URL).replace(/\/+$/, "");
105
105
  }
106
- async function postJson(base, path22, body, token) {
107
- const res = await fetch(`${base}${path22}`, {
106
+ async function postJson(base, path24, body, token) {
107
+ const res = await fetch(`${base}${path24}`, {
108
108
  method: "POST",
109
109
  headers: {
110
110
  "Content-Type": "application/json",
@@ -114,7 +114,7 @@ async function postJson(base, path22, body, token) {
114
114
  });
115
115
  if (!res.ok) {
116
116
  const text = await res.text().catch(() => "");
117
- throw new Error(`${path22} \u2192 ${res.status} ${res.statusText}${text ? `: ${text}` : ""}`);
117
+ throw new Error(`${path24} \u2192 ${res.status} ${res.statusText}${text ? `: ${text}` : ""}`);
118
118
  }
119
119
  return await res.json();
120
120
  }
@@ -345,11 +345,11 @@ function trimOutput(s) {
345
345
  function str(v) {
346
346
  return typeof v === "string" && v ? v : void 0;
347
347
  }
348
- function diffStrings(file, before, after) {
348
+ function diffStrings(file2, before, after) {
349
349
  const a = before ? before.split("\n") : [];
350
350
  const b = after ? after.split("\n") : [];
351
351
  if (a.length * b.length > 25e4) {
352
- return capDiff(file, [...a.map((l) => `-${l}`), ...b.map((l) => `+${l}`)]);
352
+ return capDiff(file2, [...a.map((l) => `-${l}`), ...b.map((l) => `+${l}`)]);
353
353
  }
354
354
  const dp = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
355
355
  for (let i2 = a.length - 1; i2 >= 0; i2--)
@@ -368,22 +368,22 @@ function diffStrings(file, before, after) {
368
368
  }
369
369
  while (i < a.length) lines2.push(`-${a[i++]}`);
370
370
  while (j < b.length) lines2.push(`+${b[j++]}`);
371
- return capDiff(file, lines2);
371
+ return capDiff(file2, lines2);
372
372
  }
373
- function diffFromHunks(file, hunks) {
373
+ function diffFromHunks(file2, hunks) {
374
374
  const lines2 = [];
375
375
  for (const h of hunks) {
376
376
  if (lines2.length) lines2.push(`@@ ${h?.newStart ?? ""}`);
377
377
  for (const l of Array.isArray(h?.lines) ? h.lines : []) lines2.push(String(l));
378
378
  }
379
- return capDiff(file, lines2);
379
+ return capDiff(file2, lines2);
380
380
  }
381
- function capDiff(file, lines2) {
381
+ function capDiff(file2, lines2) {
382
382
  const added = lines2.filter((l) => l.startsWith("+")).length;
383
383
  const removed = lines2.filter((l) => l.startsWith("-")).length;
384
384
  const truncated = lines2.length > DIFF_LINE_LIMIT;
385
385
  return {
386
- file: shortPath(file),
386
+ file: shortPath(file2),
387
387
  added,
388
388
  removed,
389
389
  lines: truncated ? lines2.slice(0, DIFF_LINE_LIMIT) : lines2,
@@ -393,7 +393,7 @@ function capDiff(file, lines2) {
393
393
  function toolPart(id, rawName, input2) {
394
394
  const name = canonicalTool(rawName);
395
395
  const inp = typeof input2 === "string" ? safeJson(input2) ?? { command: input2 } : input2 ?? {};
396
- const file = str(inp.file_path) ?? str(inp.filePath) ?? str(inp.path) ?? str(inp.file);
396
+ const file2 = str(inp.file_path) ?? str(inp.filePath) ?? str(inp.path) ?? str(inp.file);
397
397
  let title;
398
398
  let diff;
399
399
  let todos;
@@ -402,19 +402,19 @@ function toolPart(id, rawName, input2) {
402
402
  title = str(inp.description) ?? str(inp.command) ?? str(inp.cmd) ?? (Array.isArray(inp.command) ? inp.command.join(" ") : "Run command");
403
403
  break;
404
404
  case "Edit":
405
- title = file ? shortPath(file) : "Edit file";
406
- if (file && (inp.old_string != null || inp.oldString != null))
407
- diff = diffStrings(file, inp.old_string ?? inp.oldString ?? "", inp.new_string ?? inp.newString ?? "");
408
- else if (file && Array.isArray(inp.edits))
409
- diff = diffStrings(file, inp.edits.map((e) => e.old_string ?? "").join("\n"), inp.edits.map((e) => e.new_string ?? "").join("\n"));
405
+ title = file2 ? shortPath(file2) : "Edit file";
406
+ if (file2 && (inp.old_string != null || inp.oldString != null))
407
+ diff = diffStrings(file2, inp.old_string ?? inp.oldString ?? "", inp.new_string ?? inp.newString ?? "");
408
+ else if (file2 && Array.isArray(inp.edits))
409
+ diff = diffStrings(file2, inp.edits.map((e) => e.old_string ?? "").join("\n"), inp.edits.map((e) => e.new_string ?? "").join("\n"));
410
410
  break;
411
411
  case "Write":
412
- title = file ? shortPath(file) : "Write file";
413
- if (file && typeof inp.content === "string") diff = diffStrings(file, "", inp.content);
412
+ title = file2 ? shortPath(file2) : "Write file";
413
+ if (file2 && typeof inp.content === "string") diff = diffStrings(file2, "", inp.content);
414
414
  break;
415
415
  case "Read":
416
416
  case "List":
417
- title = file ? shortPath(file) : name === "List" ? "List files" : "Read file";
417
+ title = file2 ? shortPath(file2) : name === "List" ? "List files" : "Read file";
418
418
  break;
419
419
  case "Grep":
420
420
  case "Glob":
@@ -437,7 +437,7 @@ function toolPart(id, rawName, input2) {
437
437
  break;
438
438
  }
439
439
  default:
440
- title = file ? shortPath(file) : str(inp.description) ?? str(inp.command) ?? str(inp.query) ?? "";
440
+ title = file2 ? shortPath(file2) : str(inp.description) ?? str(inp.command) ?? str(inp.query) ?? "";
441
441
  }
442
442
  return {
443
443
  type: "tool",
@@ -581,10 +581,10 @@ var init_util = __esm({
581
581
  import fs3 from "fs";
582
582
  import path3 from "path";
583
583
  import { spawn as spawn2 } from "child_process";
584
- function* jsonlEntries(file) {
584
+ function* jsonlEntries(file2) {
585
585
  let content;
586
586
  try {
587
- content = fs3.readFileSync(file, "utf8");
587
+ content = fs3.readFileSync(file2, "utf8");
588
588
  } catch {
589
589
  return;
590
590
  }
@@ -596,9 +596,9 @@ function* jsonlEntries(file) {
596
596
  }
597
597
  }
598
598
  }
599
- function sessionTitle(file) {
599
+ function sessionTitle(file2) {
600
600
  for (let pass = 0; pass < 2; pass++) {
601
- for (const entry of jsonlEntries(file)) {
601
+ for (const entry of jsonlEntries(file2)) {
602
602
  if (entry?.type !== "user") continue;
603
603
  if (pass === 0 && entry?.userType !== "external") continue;
604
604
  const title = extractTextFromContent(entry?.message?.content);
@@ -607,9 +607,9 @@ function sessionTitle(file) {
607
607
  }
608
608
  return "Untitled";
609
609
  }
610
- function headCwd(file) {
610
+ function headCwd(file2) {
611
611
  try {
612
- const fd = fs3.openSync(file, "r");
612
+ const fd = fs3.openSync(file2, "r");
613
613
  const buf = Buffer.alloc(64 * 1024);
614
614
  const n = fs3.readSync(fd, buf, 0, buf.length, 0);
615
615
  fs3.closeSync(fd);
@@ -680,12 +680,12 @@ function resultText(content) {
680
680
  if (!Array.isArray(content)) return "";
681
681
  return content.filter((b) => b?.type === "text" && typeof b.text === "string").map((b) => b.text).join("\n");
682
682
  }
683
- function readMessages(file, sessionId = path3.basename(file, ".jsonl")) {
683
+ function readMessages(file2, sessionId = path3.basename(file2, ".jsonl")) {
684
684
  const msgs = [];
685
685
  const tools = /* @__PURE__ */ new Map();
686
686
  let current = null;
687
687
  let lastUserSecs = null;
688
- for (const entry of jsonlEntries(file)) {
688
+ for (const entry of jsonlEntries(file2)) {
689
689
  if (entry?.isSidechain === true) continue;
690
690
  const tsStr = entry?.timestamp ?? "";
691
691
  const tsSecs = parseIsoUnix(tsStr);
@@ -759,9 +759,9 @@ function readMessages(file, sessionId = path3.basename(file, ".jsonl")) {
759
759
  return msgs;
760
760
  }
761
761
  function imageBlock(sessionId, uuid, idx) {
762
- const file = findFile(sessionId);
763
- if (!file) return null;
764
- for (const entry of jsonlEntries(file)) {
762
+ const file2 = findFile(sessionId);
763
+ if (!file2) return null;
764
+ for (const entry of jsonlEntries(file2)) {
765
765
  if (entry?.uuid !== uuid) continue;
766
766
  const b = entry?.message?.content?.[idx];
767
767
  if (b?.type !== "image" || b?.source?.type !== "base64") return null;
@@ -770,13 +770,13 @@ function imageBlock(sessionId, uuid, idx) {
770
770
  return null;
771
771
  }
772
772
  function messages(sessionId) {
773
- const file = findFile(sessionId);
774
- return file ? readMessages(file, sessionId) : [];
773
+ const file2 = findFile(sessionId);
774
+ return file2 ? readMessages(file2, sessionId) : [];
775
775
  }
776
776
  function sessionCwd(sessionId) {
777
- const file = findFile(sessionId);
778
- if (!file) return void 0;
779
- for (const entry of jsonlEntries(file)) {
777
+ const file2 = findFile(sessionId);
778
+ if (!file2) return void 0;
779
+ for (const entry of jsonlEntries(file2)) {
780
780
  if (typeof entry?.cwd === "string" && entry.cwd) return entry.cwd;
781
781
  }
782
782
  return void 0;
@@ -784,7 +784,7 @@ function sessionCwd(sessionId) {
784
784
  function prepareNew(sessionId, cwd) {
785
785
  pendingNew.set(sessionId, cwd);
786
786
  }
787
- function send(sessionId, message, onData, images, model, run5 = {}) {
787
+ function send(sessionId, message, onData, images, model, run6 = {}) {
788
788
  return new Promise((resolve) => {
789
789
  const bin = process.env.CLAUDE_BIN || "claude";
790
790
  const newCwd = pendingNew.get(sessionId);
@@ -799,9 +799,9 @@ ${refs}` : refs;
799
799
  }
800
800
  const modelArgs = model ? ["--model", model] : [];
801
801
  const runArgs = [
802
- ...run5.effort ? ["--effort", run5.effort] : [],
803
- ...run5.mode ? ["--permission-mode", run5.mode] : [],
804
- ...run5.fast ? ["--settings", JSON.stringify({ fastMode: true })] : []
802
+ ...run6.effort ? ["--effort", run6.effort] : [],
803
+ ...run6.mode ? ["--permission-mode", run6.mode] : [],
804
+ ...run6.fast ? ["--settings", JSON.stringify({ fastMode: true })] : []
805
805
  ];
806
806
  const child2 = spawn2(
807
807
  bin,
@@ -882,7 +882,7 @@ function codexBin() {
882
882
  if (fs4.existsSync(MAC_APP_BIN)) return MAC_APP_BIN;
883
883
  return "codex";
884
884
  }
885
- function listSessions2() {
885
+ function indexSessions() {
886
886
  const host = hostname();
887
887
  const now = nowSecs();
888
888
  let content;
@@ -919,6 +919,61 @@ function listSessions2() {
919
919
  }
920
920
  return out;
921
921
  }
922
+ function stateDbPath() {
923
+ try {
924
+ const dbs = fs4.readdirSync(CODEX_DIR).filter((f) => /^state_\d+\.sqlite$/.test(f));
925
+ const latest = dbs.sort((a, b) => Number(a.match(/\d+/)[0]) - Number(b.match(/\d+/)[0])).pop();
926
+ return latest ? path4.join(CODEX_DIR, latest) : null;
927
+ } catch {
928
+ return null;
929
+ }
930
+ }
931
+ async function stateSessions() {
932
+ const file2 = stateDbPath();
933
+ if (!file2) return null;
934
+ try {
935
+ const mod = await import("better-sqlite3");
936
+ const Ctor = mod.default ?? mod;
937
+ const db = new Ctor(file2, { readonly: true, fileMustExist: true });
938
+ try {
939
+ const rows = db.prepare(
940
+ "SELECT id, COALESCE(NULLIF(name, ''), NULLIF(title, ''), NULLIF(first_user_message, ''), 'New session') AS title, updated_at, cwd, archived FROM threads WHERE attached_thread_parent_id IS NULL ORDER BY updated_at DESC"
941
+ ).all();
942
+ for (const r of rows) if (r.archived) archivedInCodex.add(r.id);
943
+ const host = hostname();
944
+ const now = nowSecs();
945
+ return rows.filter((r) => !r.archived).map((r) => {
946
+ const age = Math.max(0, now - r.updated_at);
947
+ return {
948
+ id: r.id,
949
+ title: r.title.split("\n")[0].slice(0, 200),
950
+ agent: "codex",
951
+ status: statusFromAge(age),
952
+ updatedAt: formatAge(age),
953
+ machine: host,
954
+ mtime: r.updated_at,
955
+ cwd: r.cwd || void 0
956
+ };
957
+ });
958
+ } finally {
959
+ db.close();
960
+ }
961
+ } catch {
962
+ return null;
963
+ }
964
+ }
965
+ async function listSessions2() {
966
+ const indexed = indexSessions();
967
+ const fromState = await stateSessions();
968
+ if (!fromState) return indexed;
969
+ const named = new Map(indexed.map((s) => [s.id, s]));
970
+ const out = fromState.map((s) => {
971
+ const idx = named.get(s.id);
972
+ return idx ? { ...s, title: idx.title, mtime: Math.max(s.mtime, idx.mtime), updatedAt: s.mtime >= idx.mtime ? s.updatedAt : idx.updatedAt } : s;
973
+ });
974
+ const seen = new Set(out.map((s) => s.id));
975
+ return [...out, ...indexed.filter((s) => !seen.has(s.id) && !archivedInCodex.has(s.id))];
976
+ }
922
977
  async function threadCwds() {
923
978
  const out = /* @__PURE__ */ new Map();
924
979
  let dbs = [];
@@ -981,10 +1036,10 @@ function execInput(name, input2) {
981
1036
  }
982
1037
  return { name, input: input2 };
983
1038
  }
984
- function readMessages2(file) {
1039
+ function readMessages2(file2) {
985
1040
  let content;
986
1041
  try {
987
- content = fs4.readFileSync(file, "utf8");
1042
+ content = fs4.readFileSync(file2, "utf8");
988
1043
  } catch {
989
1044
  return [];
990
1045
  }
@@ -1067,14 +1122,16 @@ function readMessages2(file) {
1067
1122
  return msgs;
1068
1123
  }
1069
1124
  function messages2(sessionId) {
1070
- const file = findFile2(sessionId);
1071
- return file ? readMessages2(file) : [];
1125
+ const file2 = findFile2(sessionId);
1126
+ return file2 ? readMessages2(file2) : [];
1072
1127
  }
1073
- function send2(sessionId, message, onData, images, model) {
1128
+ function send2(sessionId, message, onData, images, model, cwd) {
1074
1129
  return new Promise((resolve) => {
1075
1130
  const imageArgs = (images ?? []).flatMap((p) => ["-i", p]);
1076
1131
  const modelArgs = model ? ["--model", model] : [];
1077
- const child2 = spawn3(codexBin(), ["exec", ...modelArgs, "resume", sessionId, ...imageArgs, message], {
1132
+ const target2 = sessionId ? ["resume", sessionId] : ["--skip-git-repo-check"];
1133
+ const child2 = spawn3(codexBin(), ["exec", ...modelArgs, ...target2, ...imageArgs, message], {
1134
+ cwd,
1078
1135
  stdio: ["ignore", "pipe", "pipe"],
1079
1136
  env: process.env
1080
1137
  });
@@ -1091,12 +1148,17 @@ function send2(sessionId, message, onData, images, model) {
1091
1148
  (code) => resolve({
1092
1149
  ok: code === 0,
1093
1150
  output: out.trim(),
1094
- error: code === 0 ? void 0 : err.trim() || `exited ${code}`
1151
+ error: code === 0 ? void 0 : codexError(err) || `exited ${code}`
1095
1152
  })
1096
1153
  );
1097
1154
  });
1098
1155
  }
1099
- var CODEX_DIR, INDEX_PATH, SESSIONS_DIR, MAC_APP_BIN;
1156
+ function codexError(stderr) {
1157
+ const lines2 = stderr.split("\n").map((l) => l.trim()).filter(Boolean);
1158
+ const errors = lines2.filter((l) => /^ERROR:/i.test(l)).map((l) => l.replace(/^ERROR:\s*/i, ""));
1159
+ return errors.at(-1) ?? lines2.at(-1) ?? "";
1160
+ }
1161
+ var CODEX_DIR, INDEX_PATH, SESSIONS_DIR, MAC_APP_BIN, archivedInCodex;
1100
1162
  var init_codex = __esm({
1101
1163
  "src/runtime/codex.ts"() {
1102
1164
  "use strict";
@@ -1106,6 +1168,7 @@ var init_codex = __esm({
1106
1168
  INDEX_PATH = path4.join(CODEX_DIR, "session_index.jsonl");
1107
1169
  SESSIONS_DIR = path4.join(CODEX_DIR, "sessions");
1108
1170
  MAC_APP_BIN = "/Applications/Codex.app/Contents/Resources/codex";
1171
+ archivedInCodex = /* @__PURE__ */ new Set();
1109
1172
  }
1110
1173
  });
1111
1174
 
@@ -1243,6 +1306,134 @@ var init_sqlite_transcript = __esm({
1243
1306
  }
1244
1307
  });
1245
1308
 
1309
+ // src/runtime/opencode-v2.ts
1310
+ function hasV2(db) {
1311
+ return !!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'session_v2'").get();
1312
+ }
1313
+ function listSessionsV2(db, host) {
1314
+ const now = nowSecs();
1315
+ const rows = db.prepare(
1316
+ "SELECT id, title, time_updated, directory FROM session_v2 WHERE time_archived IS NULL AND parent_id IS NULL ORDER BY time_updated DESC"
1317
+ ).all();
1318
+ return rows.map((r) => {
1319
+ const mtime = Math.floor(r.time_updated / 1e3);
1320
+ const age = Math.max(0, now - mtime);
1321
+ return {
1322
+ id: r.id,
1323
+ title: r.title || "New session",
1324
+ agent: "opencode",
1325
+ status: statusFromAge(age),
1326
+ updatedAt: formatAge(age),
1327
+ machine: host,
1328
+ mtime,
1329
+ cwd: r.directory || void 0
1330
+ };
1331
+ });
1332
+ }
1333
+ function isV2Session(db, sessionId) {
1334
+ return hasV2(db) && !!db.prepare("SELECT 1 FROM session_v2 WHERE id = ?").get(sessionId);
1335
+ }
1336
+ function toolFromV2(c) {
1337
+ const st = c.state ?? {};
1338
+ const part = toolPart(String(c.id ?? ""), String(c.name ?? "tool"), st.input);
1339
+ part.status = st.status === "completed" ? "done" : st.status === "error" ? "error" : "running";
1340
+ const md = typeof st.metadata?.diff === "string" ? st.metadata.diff : null;
1341
+ if (md && part.diff) {
1342
+ const lines2 = unifiedLines(md);
1343
+ part.diff = {
1344
+ ...part.diff,
1345
+ lines: lines2.slice(0, 300),
1346
+ added: lines2.filter((l) => l.startsWith("+")).length,
1347
+ removed: lines2.filter((l) => l.startsWith("-")).length
1348
+ };
1349
+ }
1350
+ if (!(part.diff && part.status === "done")) {
1351
+ const text = Array.isArray(st.content) ? st.content.filter((x) => x?.type === "text").map((x) => x.text).join("\n") : void 0;
1352
+ const err = typeof st.error === "string" ? st.error : st.error?.message;
1353
+ part.output = trimOutput(err ?? text);
1354
+ }
1355
+ return part;
1356
+ }
1357
+ function buildMessagesV2(db, sessionId) {
1358
+ const rows = db.prepare(
1359
+ "SELECT id, type, time_created, data FROM session_message WHERE session_id = ? AND type IN ('user', 'assistant') ORDER BY seq ASC"
1360
+ ).all(sessionId);
1361
+ const out = [];
1362
+ let current = null;
1363
+ let lastUserMs = null;
1364
+ for (const r of rows) {
1365
+ let v;
1366
+ try {
1367
+ v = JSON.parse(r.data);
1368
+ } catch {
1369
+ continue;
1370
+ }
1371
+ const ts = chronoIso(Math.floor(r.time_created / 1e3));
1372
+ if (r.type === "user") {
1373
+ const parts2 = [];
1374
+ if (typeof v.text === "string" && v.text.trim()) parts2.push({ type: "text", text: v.text });
1375
+ (Array.isArray(v.files) ? v.files : []).forEach((f, i) => {
1376
+ if (typeof f?.mime === "string" && f.mime.startsWith("image/")) {
1377
+ parts2.push({
1378
+ type: "image",
1379
+ url: `/blobs/opencode/${encodeURIComponent(sessionId)}/${encodeURIComponent(`${r.id}:${i}`)}`,
1380
+ mediaType: f.mime
1381
+ });
1382
+ }
1383
+ });
1384
+ if (!parts2.length) continue;
1385
+ current = null;
1386
+ lastUserMs = r.time_created;
1387
+ out.push({ id: r.id, role: "user", content: textOf(parts2), timestamp: ts, hasToolUse: false, parts: parts2 });
1388
+ continue;
1389
+ }
1390
+ const parts = [];
1391
+ for (const c of Array.isArray(v.content) ? v.content : []) {
1392
+ if (c?.type === "text" && typeof c.text === "string" && c.text.trim()) parts.push({ type: "text", text: c.text });
1393
+ else if (c?.type === "tool") parts.push(toolFromV2(c));
1394
+ }
1395
+ const err = v.error?.message ?? (typeof v.error === "string" ? v.error : void 0);
1396
+ if (!parts.length && err) parts.push({ type: "text", text: `Error: ${err}` });
1397
+ if (!parts.length) continue;
1398
+ if (!current) {
1399
+ current = { id: r.id, role: "assistant", content: "", timestamp: ts, parts: [] };
1400
+ out.push(current);
1401
+ }
1402
+ current.parts.push(...parts);
1403
+ current.content = textOf(current.parts);
1404
+ current.hasToolUse = current.parts.some((p) => p.type === "tool");
1405
+ const t = v.tokens ?? {};
1406
+ const ctx = (t.input ?? 0) + (t.cache?.read ?? 0) + (t.cache?.write ?? 0);
1407
+ if (ctx > 0) current.inputTokens = ctx;
1408
+ if (typeof v.model?.id === "string" && v.model.id) current.model = v.model.id;
1409
+ const end = v.time?.completed ?? r.time_created;
1410
+ if (lastUserMs != null) current.elapsedSecs = Math.max(0, Math.floor((end - lastUserMs) / 1e3));
1411
+ }
1412
+ return out;
1413
+ }
1414
+ function imageV2(db, sessionId, ref) {
1415
+ const cut = ref.lastIndexOf(":");
1416
+ if (cut < 0) return null;
1417
+ const row = db.prepare("SELECT data FROM session_message WHERE id = ? AND session_id = ? LIMIT 1").get(ref.slice(0, cut), sessionId);
1418
+ if (!row) return null;
1419
+ try {
1420
+ const f = JSON.parse(row.data)?.files?.[Number(ref.slice(cut + 1))];
1421
+ if (typeof f?.mime !== "string" || !f.mime.startsWith("image/") || typeof f.data !== "string") return null;
1422
+ const b64 = f.data.replace(/^data:[^;]+;base64,/, "");
1423
+ return { mediaType: f.mime, data: Buffer.from(b64, "base64") };
1424
+ } catch {
1425
+ return null;
1426
+ }
1427
+ }
1428
+ var init_opencode_v2 = __esm({
1429
+ "src/runtime/opencode-v2.ts"() {
1430
+ "use strict";
1431
+ init_parts();
1432
+ init_sqlite_transcript();
1433
+ init_util();
1434
+ }
1435
+ });
1436
+
1246
1437
  // src/runtime/opencode.ts
1247
1438
  import path5 from "path";
1248
1439
  import fs6 from "fs";
@@ -1281,10 +1472,12 @@ async function listSessions3() {
1281
1472
  const host = hostname();
1282
1473
  const now = nowSecs();
1283
1474
  try {
1475
+ const v2 = hasV2(db) ? listSessionsV2(db, host) : [];
1476
+ const seen = new Set(v2.map((x) => x.id));
1284
1477
  const rows = db.prepare(
1285
1478
  "SELECT id, title, time_updated, directory FROM session WHERE time_archived IS NULL ORDER BY time_updated DESC"
1286
1479
  ).all();
1287
- return rows.map((r) => {
1480
+ const v1 = rows.filter((r) => !seen.has(r.id)).map((r) => {
1288
1481
  const mtime = Math.floor(r.time_updated / 1e3);
1289
1482
  const age = Math.max(0, now - mtime);
1290
1483
  return {
@@ -1298,6 +1491,7 @@ async function listSessions3() {
1298
1491
  cwd: r.directory || void 0
1299
1492
  };
1300
1493
  });
1494
+ return [...v2, ...v1].sort((a, b) => b.mtime - a.mtime);
1301
1495
  } finally {
1302
1496
  db.close();
1303
1497
  }
@@ -1306,7 +1500,7 @@ async function messages3(sessionId) {
1306
1500
  const db = await open();
1307
1501
  if (!db) return [];
1308
1502
  try {
1309
- return buildMessages(db, "opencode", sessionId);
1503
+ return isV2Session(db, sessionId) ? buildMessagesV2(db, sessionId) : buildMessages(db, "opencode", sessionId);
1310
1504
  } finally {
1311
1505
  db.close();
1312
1506
  }
@@ -1315,18 +1509,20 @@ async function image(sessionId, partId) {
1315
1509
  const db = await open();
1316
1510
  if (!db) return null;
1317
1511
  try {
1318
- return filePartImage(db, sessionId, partId);
1512
+ return isV2Session(db, sessionId) ? imageV2(db, sessionId, partId) : filePartImage(db, sessionId, partId);
1319
1513
  } catch {
1320
1514
  return null;
1321
1515
  } finally {
1322
1516
  db.close();
1323
1517
  }
1324
1518
  }
1325
- function send3(sessionId, message, onData, images, model) {
1519
+ function send3(sessionId, message, onData, images, model, cwd) {
1326
1520
  return new Promise((resolve) => {
1327
1521
  const fileArgs = (images ?? []).flatMap((p) => ["-f", p]);
1328
1522
  const modelArgs = model ? ["-m", model] : [];
1329
- const child2 = spawn4(opencodeBin(), ["run", "-s", sessionId, ...modelArgs, ...fileArgs, message], {
1523
+ const sessionArgs = sessionId ? ["-s", sessionId] : [];
1524
+ const child2 = spawn4(opencodeBin(), ["run", ...sessionArgs, ...modelArgs, ...fileArgs, message], {
1525
+ cwd,
1330
1526
  stdio: ["ignore", "pipe", "pipe"],
1331
1527
  env: process.env
1332
1528
  });
@@ -1338,14 +1534,18 @@ function send3(sessionId, message, onData, images, model) {
1338
1534
  });
1339
1535
  child2.stderr.on("data", (d) => err += d.toString());
1340
1536
  child2.on("error", (e) => resolve({ ok: false, output: "", error: e.message }));
1341
- child2.on(
1342
- "close",
1343
- (code) => resolve({
1344
- ok: code === 0,
1345
- output: out.trim(),
1346
- error: code === 0 ? void 0 : err.trim() || `exited ${code}`
1347
- })
1348
- );
1537
+ child2.on("close", (code) => {
1538
+ const strip = (t) => t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
1539
+ const plain = strip(out);
1540
+ const printed = /^Error:\s*(.+)$/m.exec(`${plain}
1541
+ ${strip(err)}`)?.[1]?.trim();
1542
+ const ok2 = code === 0 && !printed;
1543
+ resolve({
1544
+ ok: ok2,
1545
+ output: plain.trim(),
1546
+ error: ok2 ? void 0 : printed || err.trim() || `exited ${code}`
1547
+ });
1548
+ });
1349
1549
  });
1350
1550
  }
1351
1551
  var DB_PATH, MAC_APP_BIN2, _ctor;
@@ -1353,6 +1553,7 @@ var init_opencode = __esm({
1353
1553
  "src/runtime/opencode.ts"() {
1354
1554
  "use strict";
1355
1555
  init_sqlite_transcript();
1556
+ init_opencode_v2();
1356
1557
  init_util();
1357
1558
  DB_PATH = path5.join(HOME, ".local", "share", "opencode", "opencode.db");
1358
1559
  MAC_APP_BIN2 = "/Applications/OpenCode.app/Contents/MacOS/opencode-cli";
@@ -1481,10 +1682,10 @@ async function image2(sessionId, partId) {
1481
1682
  db.close();
1482
1683
  }
1483
1684
  }
1484
- function send4(sessionId, message, onData, images, _model) {
1685
+ function send4(sessionId, message, onData, images, _model, cwd) {
1485
1686
  return new Promise(async (resolve) => {
1486
- const args = ["--resume", sessionId];
1487
- const dir = await sessionDir(sessionId).catch(() => null);
1687
+ const args = sessionId ? ["--resume", sessionId] : [];
1688
+ const dir = cwd ?? await sessionDir(sessionId).catch(() => null);
1488
1689
  if (dir && fs7.existsSync(dir)) args.push("--cwd", dir);
1489
1690
  for (const p of images ?? []) args.push("--attach", p);
1490
1691
  args.push("--output-format", "stream-json", "--prompt", message);
@@ -1565,16 +1766,16 @@ function available3() {
1565
1766
  function zstdSupported() {
1566
1767
  return typeof zlib.zstdDecompressSync === "function";
1567
1768
  }
1568
- function decompress(file) {
1769
+ function decompress(file2) {
1569
1770
  if (!zstdSupported()) return null;
1570
1771
  try {
1571
- return zlib.zstdDecompressSync(fs8.readFileSync(file)).toString("utf8");
1772
+ return zlib.zstdDecompressSync(fs8.readFileSync(file2)).toString("utf8");
1572
1773
  } catch {
1573
1774
  return null;
1574
1775
  }
1575
1776
  }
1576
- function parseSessionFile(file) {
1577
- const raw = decompress(file);
1777
+ function parseSessionFile(file2) {
1778
+ const raw = decompress(file2);
1578
1779
  if (!raw) return null;
1579
1780
  const events = [];
1580
1781
  let header = null;
@@ -1608,16 +1809,16 @@ function allSessionFiles() {
1608
1809
  }
1609
1810
  for (const e of entries) {
1610
1811
  if (!e.startsWith("session-")) continue;
1611
- const file = path7.join(dir, e, "session.v4.jsonl.zstd");
1812
+ const file2 = path7.join(dir, e, "session.v4.jsonl.zstd");
1612
1813
  let stat;
1613
1814
  try {
1614
- stat = fs8.statSync(file);
1815
+ stat = fs8.statSync(file2);
1615
1816
  } catch {
1616
1817
  continue;
1617
1818
  }
1618
- const parsed = parseSessionFile(file);
1819
+ const parsed = parseSessionFile(file2);
1619
1820
  if (!parsed) continue;
1620
- out.push({ file, header: parsed.header, events: parsed.events, stat });
1821
+ out.push({ file: file2, header: parsed.header, events: parsed.events, stat });
1621
1822
  }
1622
1823
  }
1623
1824
  out.sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
@@ -1673,15 +1874,15 @@ function findFile3(sessionId) {
1673
1874
  return null;
1674
1875
  }
1675
1876
  for (const bucket of buckets) {
1676
- const file = path7.join(SESSIONS_DIR2, bucket, sessionId, "session.v4.jsonl.zstd");
1677
- if (fs8.existsSync(file)) return file;
1877
+ const file2 = path7.join(SESSIONS_DIR2, bucket, sessionId, "session.v4.jsonl.zstd");
1878
+ if (fs8.existsSync(file2)) return file2;
1678
1879
  }
1679
1880
  return null;
1680
1881
  }
1681
1882
  async function messages5(sessionId) {
1682
- const file = findFile3(sessionId);
1683
- if (!file) return [];
1684
- const parsed = parseSessionFile(file);
1883
+ const file2 = findFile3(sessionId);
1884
+ if (!file2) return [];
1885
+ const parsed = parseSessionFile(file2);
1685
1886
  if (!parsed) return [];
1686
1887
  const createdAtMs = parsed.header.createdAt ?? Date.now();
1687
1888
  const out = [];
@@ -1706,14 +1907,14 @@ async function messages5(sessionId) {
1706
1907
  }
1707
1908
  return out;
1708
1909
  }
1709
- function send5(sessionId, message, onData, images, _model) {
1910
+ function send5(sessionId, message, onData, images, _model, dir) {
1710
1911
  return new Promise((resolve) => {
1711
- const file = findFile3(sessionId);
1712
- let cwd;
1713
- if (file) {
1714
- const parsed = parseSessionFile(file);
1715
- const dir = parsed?.header?.cwd;
1716
- if (dir && fs8.existsSync(dir)) cwd = dir;
1912
+ const file2 = sessionId ? findFile3(sessionId) : null;
1913
+ let cwd = dir;
1914
+ if (file2) {
1915
+ const parsed = parseSessionFile(file2);
1916
+ const dir2 = parsed?.header?.cwd;
1917
+ if (dir2 && fs8.existsSync(dir2)) cwd = dir2;
1717
1918
  }
1718
1919
  let prompt = message;
1719
1920
  if (images?.length) {
@@ -1722,7 +1923,8 @@ function send5(sessionId, message, onData, images, _model) {
1722
1923
 
1723
1924
  ${refs}` : refs;
1724
1925
  }
1725
- const child2 = spawn6(dshBin(), ["headless", "--json", "--session-id", sessionId, "-"], {
1926
+ const sessionArgs = sessionId ? ["--session-id", sessionId] : [];
1927
+ const child2 = spawn6(dshBin(), ["headless", "--json", ...sessionArgs, "-"], {
1726
1928
  cwd,
1727
1929
  stdio: ["pipe", "pipe", "pipe"],
1728
1930
  env: process.env
@@ -1782,55 +1984,576 @@ var init_deepseek = __esm({
1782
1984
  }
1783
1985
  });
1784
1986
 
1785
- // src/runtime/meta.ts
1987
+ // src/runtime/acp.ts
1786
1988
  import fs9 from "fs";
1989
+ import os5 from "os";
1787
1990
  import path8 from "path";
1788
- function read() {
1991
+ import { createHash, randomUUID as randomUUID2 } from "crypto";
1992
+ import { execFile, spawn as spawn7 } from "child_process";
1993
+ import { promisify } from "util";
1994
+ async function registry(force = false) {
1995
+ if (!force && registryMem && Date.now() - registryMem.at < REGISTRY_TTL_MS) return registryMem.agents;
1996
+ try {
1997
+ const src = process.env.SAKURA_ACP_REGISTRY || REGISTRY_URL;
1998
+ let body;
1999
+ if (/^https?:/.test(src)) {
2000
+ const res = await fetch(src, { signal: AbortSignal.timeout(15e3) });
2001
+ if (!res.ok) throw new Error(`registry ${res.status}`);
2002
+ body = await res.json();
2003
+ } else {
2004
+ body = JSON.parse(fs9.readFileSync(src, "utf8"));
2005
+ }
2006
+ const agents = (body.agents ?? []).filter((a) => a?.id && a?.name && a?.distribution);
2007
+ fs9.mkdirSync(ACP_DIR, { recursive: true });
2008
+ fs9.writeFileSync(REGISTRY_CACHE, JSON.stringify(agents));
2009
+ registryMem = { at: Date.now(), agents };
2010
+ return agents;
2011
+ } catch {
2012
+ if (registryMem) return registryMem.agents;
2013
+ try {
2014
+ const agents = JSON.parse(fs9.readFileSync(REGISTRY_CACHE, "utf8"));
2015
+ registryMem = { at: Date.now() - REGISTRY_TTL_MS + 6e4, agents };
2016
+ return agents;
2017
+ } catch {
2018
+ return [];
2019
+ }
2020
+ }
2021
+ }
2022
+ async function findAgent(id) {
2023
+ return (await registry()).find((a) => a.id === id) ?? null;
2024
+ }
2025
+ function method(a) {
2026
+ if (a.distribution.binary?.[PLATFORM]) return "binary";
2027
+ if (a.distribution.npx?.package && onPath("npx")) return "npx";
2028
+ if (a.distribution.uvx?.package && onPath("uvx")) return "uvx";
2029
+ return null;
2030
+ }
2031
+ function installed(a) {
2032
+ const m = method(a);
2033
+ if (m !== "binary") return m != null;
2034
+ const t = a.distribution.binary[PLATFORM];
2035
+ return fs9.existsSync(path8.join(binDir(a), t.cmd));
2036
+ }
2037
+ async function catalog() {
2038
+ const enabled = new Set(loadConfig().acpAgents ?? []);
2039
+ return (await registry()).map((a) => ({
2040
+ id: a.id,
2041
+ name: a.name,
2042
+ version: a.version,
2043
+ description: a.description,
2044
+ website: a.website ?? a.repository,
2045
+ icon: a.icon,
2046
+ via: method(a),
2047
+ installed: installed(a),
2048
+ enabled: enabled.has(a.id)
2049
+ }));
2050
+ }
2051
+ function install(a) {
2052
+ if (method(a) !== "binary" || installed(a)) return Promise.resolve();
2053
+ const t = a.distribution.binary[PLATFORM];
2054
+ const existing = installing.get(a.id);
2055
+ if (existing) return existing;
2056
+ const job = (async () => {
2057
+ const dir = binDir(a);
2058
+ const stage = `${dir}.${randomUUID2().slice(0, 8)}`;
2059
+ fs9.mkdirSync(stage, { recursive: true });
2060
+ try {
2061
+ const file2 = path8.join(stage, path8.basename(new URL(t.archive).pathname));
2062
+ await run("curl", ["-fsSL", "--retry", "2", "-o", file2, t.archive], { timeout: 6e5 });
2063
+ if (t.sha256) {
2064
+ const sum = createHash("sha256").update(fs9.readFileSync(file2)).digest("hex");
2065
+ if (sum !== t.sha256.toLowerCase()) throw new Error(`checksum mismatch for ${a.name}`);
2066
+ }
2067
+ if (/\.zip$/i.test(file2)) await run("unzip", ["-q", "-o", file2, "-d", stage], { timeout: 12e4 });
2068
+ else if (/\.tar\.(gz|bz2|xz)$|\.tgz$/i.test(file2)) await run("tar", ["xf", file2, "-C", stage], { timeout: 12e4 });
2069
+ else fs9.copyFileSync(file2, path8.join(stage, t.cmd));
2070
+ fs9.rmSync(file2, { force: true });
2071
+ const bin = path8.join(stage, t.cmd);
2072
+ if (!fs9.existsSync(bin)) throw new Error(`${a.name}'s archive has no ${t.cmd}`);
2073
+ fs9.chmodSync(bin, 493);
2074
+ fs9.rmSync(dir, { recursive: true, force: true });
2075
+ fs9.mkdirSync(path8.dirname(dir), { recursive: true });
2076
+ fs9.renameSync(stage, dir);
2077
+ } finally {
2078
+ fs9.rmSync(stage, { recursive: true, force: true });
2079
+ }
2080
+ })().finally(() => installing.delete(a.id));
2081
+ installing.set(a.id, job);
2082
+ return job;
2083
+ }
2084
+ async function setEnabled(id, on) {
2085
+ const a = await findAgent(id);
2086
+ if (!a) throw new Error(`${id} is not in the ACP registry`);
2087
+ if (on) {
2088
+ if (!method(a)) throw new Error(`${a.name} can't run on this Mac (it needs ${a.distribution.npx ? "npx" : a.distribution.uvx ? "uvx" : `a ${PLATFORM} build`}).`);
2089
+ await install(a);
2090
+ }
2091
+ updateConfig((c) => {
2092
+ const set = new Set(c.acpAgents ?? []);
2093
+ if (on) set.add(id);
2094
+ else set.delete(id);
2095
+ c.acpAgents = [...set];
2096
+ });
2097
+ return (await catalog()).find((x) => x.id === id);
2098
+ }
2099
+ function launchCommand(a) {
2100
+ const m = method(a);
2101
+ if (m === "binary") {
2102
+ const t = a.distribution.binary[PLATFORM];
2103
+ return { cmd: path8.join(binDir(a), t.cmd), args: t.args ?? [], env: t.env ?? {} };
2104
+ }
2105
+ if (m === "npx") {
2106
+ const d = a.distribution.npx;
2107
+ return { cmd: "npx", args: ["-y", d.package, ...d.args ?? []], env: d.env ?? {} };
2108
+ }
2109
+ if (m === "uvx") {
2110
+ const d = a.distribution.uvx;
2111
+ return { cmd: "uvx", args: [d.package, ...d.args ?? []], env: d.env ?? {} };
2112
+ }
2113
+ throw new Error(`${a.name} can't run on this Mac.`);
2114
+ }
2115
+ function read(id) {
2116
+ try {
2117
+ return JSON.parse(fs9.readFileSync(file(id), "utf8"));
2118
+ } catch {
2119
+ return null;
2120
+ }
2121
+ }
2122
+ function write2(s) {
2123
+ fs9.mkdirSync(SESSIONS_DIR3, { recursive: true });
2124
+ const tmp = `${file(s.id)}.${process.pid}.tmp`;
2125
+ fs9.writeFileSync(tmp, JSON.stringify(s));
2126
+ fs9.renameSync(tmp, file(s.id));
2127
+ }
2128
+ async function prepareNew2(sessionId, cwd, acpId) {
2129
+ const a = await findAgent(acpId);
2130
+ if (!a) throw new Error(`${acpId} is not in the ACP registry`);
2131
+ const now = Date.now();
2132
+ write2({ id: sessionId, acp: acpId, name: a.name, cwd, title: "", createdAt: now, updatedAt: now, messages: [] });
2133
+ }
2134
+ function listSessions6() {
2135
+ let names = [];
2136
+ try {
2137
+ names = fs9.readdirSync(SESSIONS_DIR3).filter((f) => f.endsWith(".json"));
2138
+ } catch {
2139
+ return [];
2140
+ }
2141
+ const host = hostname();
2142
+ const now = nowSecs();
2143
+ const out = [];
2144
+ for (const n of names) {
2145
+ const s = read(n.slice(0, -5));
2146
+ if (!s) continue;
2147
+ const mtime = Math.floor(s.updatedAt / 1e3);
2148
+ const age = Math.max(0, now - mtime);
2149
+ out.push({
2150
+ id: s.id,
2151
+ title: s.title || "New chat",
2152
+ agent: "acp",
2153
+ status: statusFromAge(age),
2154
+ updatedAt: formatAge(age),
2155
+ machine: host,
2156
+ mtime,
2157
+ cwd: s.cwd,
2158
+ acp: { id: s.acp, name: s.name }
2159
+ });
2160
+ }
2161
+ return out;
2162
+ }
2163
+ function messages6(id) {
2164
+ return read(id)?.messages ?? [];
2165
+ }
2166
+ function cachedModels() {
2167
+ try {
2168
+ return JSON.parse(fs9.readFileSync(MODELS_CACHE, "utf8"));
2169
+ } catch {
2170
+ return {};
2171
+ }
2172
+ }
2173
+ function models(acpId) {
2174
+ return [{ id: "", label: "Default" }, ...cachedModels()[acpId] ?? []];
2175
+ }
2176
+ function rememberModels(acpId, list4) {
2177
+ const all2 = cachedModels();
2178
+ all2[acpId] = list4.map((m) => ({ id: m.modelId, label: m.name || m.modelId, desc: m.description ?? void 0 }));
2179
+ try {
2180
+ fs9.mkdirSync(ACP_DIR, { recursive: true });
2181
+ fs9.writeFileSync(MODELS_CACHE, JSON.stringify(all2));
2182
+ } catch {
2183
+ }
2184
+ }
2185
+ function blockText(c) {
2186
+ if (!c) return "";
2187
+ if (c.type === "text") return c.text ?? "";
2188
+ if (c.type === "content") return blockText(c.content);
2189
+ if (c.type === "diff") return `${c.path ?? ""}`;
2190
+ if (c.type === "resource_link") return c.uri ?? "";
2191
+ if (c.type === "resource") return c.resource?.text ?? "";
2192
+ return "";
2193
+ }
2194
+ function primer(prior) {
2195
+ const lines2 = prior.map((m) => `${m.role === "user" ? "User" : "Assistant"}: ${m.content}`.trim());
2196
+ let text = lines2.join("\n\n");
2197
+ if (text.length > 6e4) text = `\u2026${text.slice(-6e4)}`;
2198
+ return `This conversation is continuing in a new session. Here is everything so far:
2199
+
2200
+ <conversation>
2201
+ ${text}
2202
+ </conversation>
2203
+
2204
+ `;
2205
+ }
2206
+ async function send6(sessionId, message, onData, images, model, runOpts = {}) {
2207
+ const s = read(sessionId);
2208
+ if (!s) return { ok: false, output: "", error: "chat not found" };
2209
+ const a = await findAgent(s.acp);
2210
+ if (!a) return { ok: false, output: "", error: `${s.name} is no longer in the ACP registry` };
2211
+ try {
2212
+ await install(a);
2213
+ } catch (e) {
2214
+ return { ok: false, output: "", error: `Couldn't install ${a.name}: ${e.message}` };
2215
+ }
2216
+ const prior = s.messages.slice();
2217
+ const now = () => (/* @__PURE__ */ new Date()).toISOString();
2218
+ s.messages.push({ id: randomUUID2(), role: "user", content: message, timestamp: now() });
2219
+ if (!s.title) s.title = message.length > 60 ? `${message.slice(0, 57)}\u2026` : message;
2220
+ const reply = { id: randomUUID2(), role: "assistant", content: "", timestamp: now(), parts: [], model: model || void 0 };
2221
+ s.messages.push(reply);
2222
+ const started = Date.now();
2223
+ const save = () => {
2224
+ reply.content = reply.parts.filter((p) => p.type === "text").map((p) => p.text).join("");
2225
+ reply.hasToolUse = reply.parts.some((p) => p.type === "tool");
2226
+ reply.elapsedSecs = Math.round((Date.now() - started) / 1e3);
2227
+ s.updatedAt = Date.now();
2228
+ write2(s);
2229
+ };
2230
+ save();
2231
+ const appendText = (text) => {
2232
+ if (!text) return;
2233
+ const last = reply.parts[reply.parts.length - 1];
2234
+ if (last?.type === "text") last.text += text;
2235
+ else reply.parts.push({ type: "text", text });
2236
+ onData?.(text);
2237
+ };
2238
+ const tools = /* @__PURE__ */ new Map();
2239
+ const toolUpdate = (u) => {
2240
+ const id = String(u.toolCallId ?? randomUUID2());
2241
+ let t = tools.get(id);
2242
+ if (!t) {
2243
+ t = { type: "tool", id, name: TOOL_NAMES[u.kind] ?? "Tool", title: u.title ?? "Tool call", status: "running" };
2244
+ tools.set(id, t);
2245
+ reply.parts.push(t);
2246
+ }
2247
+ if (u.title) t.title = u.title;
2248
+ if (u.kind) t.name = TOOL_NAMES[u.kind] ?? t.name;
2249
+ if (u.status === "completed") t.status = "done";
2250
+ else if (u.status === "failed") t.status = "error";
2251
+ const out = (u.content ?? []).map(blockText).filter(Boolean).join("\n");
2252
+ if (out) t.output = out.length > 4e3 ? `${out.slice(0, 4e3)}\u2026` : out;
2253
+ if (u.rawInput?.command && t.name === "Bash") t.title = String(u.rawInput.command);
2254
+ };
2255
+ let loading = false;
2256
+ let lastSave = 0;
2257
+ const onNotify = (method2, params) => {
2258
+ if (method2 !== "session/update" || loading) return;
2259
+ const u = params?.update ?? {};
2260
+ switch (u.sessionUpdate) {
2261
+ case "agent_message_chunk":
2262
+ appendText(blockText(u.content));
2263
+ break;
2264
+ case "tool_call":
2265
+ case "tool_call_update":
2266
+ toolUpdate(u);
2267
+ break;
2268
+ case "plan":
2269
+ reply.parts.push({
2270
+ type: "tool",
2271
+ id: `plan-${Date.now()}`,
2272
+ name: "Todos",
2273
+ title: "Plan",
2274
+ status: "done",
2275
+ todos: (u.entries ?? []).map((e) => ({ content: e.content, status: e.status }))
2276
+ });
2277
+ break;
2278
+ default:
2279
+ return;
2280
+ }
2281
+ if (Date.now() - lastSave > 250) {
2282
+ lastSave = Date.now();
2283
+ save();
2284
+ }
2285
+ };
2286
+ const onRequest = async (method2, params) => {
2287
+ if (method2 === "session/request_permission") {
2288
+ const opts = params?.options ?? [];
2289
+ const readOnly = ["read", "search", "think", "fetch"].includes(params?.toolCall?.kind);
2290
+ const allow = runOpts.mode !== "plan" || readOnly;
2291
+ const pick2 = allow ? opts.find((o) => o.kind === "allow_once") ?? opts.find((o) => o.kind.startsWith("allow")) : opts.find((o) => o.kind === "reject_once") ?? opts.find((o) => o.kind.startsWith("reject"));
2292
+ return pick2 ? { outcome: { outcome: "selected", optionId: pick2.optionId } } : { outcome: { outcome: "cancelled" } };
2293
+ }
2294
+ const err = new Error(`Sakura doesn't handle ${method2}`);
2295
+ err.code = -32601;
2296
+ throw err;
2297
+ };
2298
+ const { cmd, args, env } = launchCommand(a);
2299
+ let child2;
2300
+ try {
2301
+ child2 = spawn7(cmd, args, { cwd: fs9.existsSync(s.cwd) ? s.cwd : os5.homedir(), stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...env } });
2302
+ } catch (e) {
2303
+ return finish(false, e.message);
2304
+ }
2305
+ const rpc = new Rpc(child2, onNotify, onRequest);
2306
+ function finish(ok2, error) {
2307
+ if (!ok2 && error && !reply.parts.length) reply.parts.push({ type: "text", text: `\u26A0\uFE0F ${error}` });
2308
+ save();
2309
+ return { ok: ok2, output: reply.content, error: ok2 ? void 0 : error };
2310
+ }
2311
+ try {
2312
+ const init = await rpc.call("initialize", {
2313
+ protocolVersion: 1,
2314
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
2315
+ clientInfo: { name: "sakura", version: "1" }
2316
+ }, 3e5);
2317
+ const caps = init?.agentCapabilities ?? {};
2318
+ const mcpServers = [];
2319
+ let remote = s.remoteId;
2320
+ let resumed = false;
2321
+ if (remote && caps.loadSession) {
2322
+ loading = true;
2323
+ try {
2324
+ await rpc.call("session/load", { sessionId: remote, cwd: s.cwd, mcpServers }, 12e4);
2325
+ resumed = true;
2326
+ } catch {
2327
+ remote = void 0;
2328
+ } finally {
2329
+ loading = false;
2330
+ }
2331
+ }
2332
+ if (!resumed) {
2333
+ let created;
2334
+ try {
2335
+ created = await rpc.call("session/new", { cwd: s.cwd, mcpServers }, 12e4);
2336
+ } catch (e) {
2337
+ const methods = init?.authMethods ?? [];
2338
+ if (e.code !== -32e3 || !methods.length) throw e;
2339
+ await rpc.call("authenticate", { methodId: methods[0].id }, 18e4).catch(() => {
2340
+ throw new Error(`${a.name} needs you to sign in on your Mac first (${methods.map((m) => m.name ?? m.id).join(", ")}).`);
2341
+ });
2342
+ created = await rpc.call("session/new", { cwd: s.cwd, mcpServers }, 12e4);
2343
+ }
2344
+ remote = created?.sessionId;
2345
+ s.remoteId = remote;
2346
+ const avail = created?.models?.availableModels;
2347
+ if (Array.isArray(avail) && avail.length) rememberModels(a.id, avail);
2348
+ }
2349
+ if (!remote) throw new Error(`${a.name} didn't open a session`);
2350
+ if (model) await rpc.call("session/set_model", { sessionId: remote, modelId: model }, 3e4).catch(() => {
2351
+ });
2352
+ const prompt = [];
2353
+ const text = !resumed && prior.length ? `${primer(prior)}${message}` : message;
2354
+ prompt.push({ type: "text", text });
2355
+ for (const p of images ?? []) {
2356
+ const mediaType = /\.png$/i.test(p) ? "image/png" : /\.gif$/i.test(p) ? "image/gif" : /\.webp$/i.test(p) ? "image/webp" : "image/jpeg";
2357
+ if (caps.promptCapabilities?.image) prompt.push({ type: "image", mimeType: mediaType, data: fs9.readFileSync(p).toString("base64") });
2358
+ else prompt[0] = { type: "text", text: `${text}
2359
+
2360
+ [Image: ${p}]` };
2361
+ }
2362
+ const result = await rpc.call("session/prompt", { sessionId: remote, prompt });
2363
+ const stop2 = result?.stopReason;
2364
+ for (const t of tools.values()) if (t.status === "running") t.status = "done";
2365
+ if (stop2 === "refusal") return finish(false, `${a.name} declined this request.`);
2366
+ return finish(true);
2367
+ } catch (e) {
2368
+ const msg = e.message || rpc.lastError() || "the agent failed";
2369
+ return finish(false, msg);
2370
+ } finally {
2371
+ child2.stdin?.end();
2372
+ child2.kill("SIGTERM");
2373
+ setTimeout(() => {
2374
+ if (child2.exitCode == null) child2.kill("SIGKILL");
2375
+ }, 3e3).unref();
2376
+ }
2377
+ }
2378
+ var run, REGISTRY_URL, ACP_DIR, SESSIONS_DIR3, BIN_DIR, REGISTRY_CACHE, MODELS_CACHE, REGISTRY_TTL_MS, registryMem, PLATFORM, onPath, binDir, installing, file, has, Rpc, TOOL_NAMES;
2379
+ var init_acp = __esm({
2380
+ "src/runtime/acp.ts"() {
2381
+ "use strict";
2382
+ init_config();
2383
+ init_util();
2384
+ run = promisify(execFile);
2385
+ REGISTRY_URL = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json";
2386
+ ACP_DIR = path8.join(SAKURA_DIR, "acp");
2387
+ SESSIONS_DIR3 = path8.join(ACP_DIR, "sessions");
2388
+ BIN_DIR = path8.join(ACP_DIR, "bin");
2389
+ REGISTRY_CACHE = path8.join(ACP_DIR, "registry.json");
2390
+ MODELS_CACHE = path8.join(ACP_DIR, "models.json");
2391
+ REGISTRY_TTL_MS = 6 * 36e5;
2392
+ registryMem = null;
2393
+ PLATFORM = `${{ darwin: "darwin", linux: "linux", win32: "windows" }[process.platform] ?? process.platform}-${{ arm64: "aarch64", x64: "x86_64" }[process.arch] ?? process.arch}`;
2394
+ onPath = (bin) => (process.env.PATH ?? "").split(path8.delimiter).some((d) => d && fs9.existsSync(path8.join(d, bin)));
2395
+ binDir = (a) => path8.join(BIN_DIR, a.id, a.version);
2396
+ installing = /* @__PURE__ */ new Map();
2397
+ file = (id) => path8.join(SESSIONS_DIR3, `${id}.json`);
2398
+ has = (id) => fs9.existsSync(file(id));
2399
+ Rpc = class {
2400
+ constructor(child2, onNotify, onRequest) {
2401
+ this.child = child2;
2402
+ this.onNotify = onNotify;
2403
+ this.onRequest = onRequest;
2404
+ child2.stdout.on("data", (d) => this.feed(d.toString()));
2405
+ child2.stderr.on("data", (d) => {
2406
+ this.stderr = (this.stderr + d.toString()).slice(-4e3);
2407
+ });
2408
+ this.exited = new Promise((resolve) => child2.on("close", (code) => {
2409
+ for (const p of this.pending.values()) p.reject(new Error(this.lastError() || `agent exited (${code})`));
2410
+ this.pending.clear();
2411
+ resolve(code);
2412
+ }));
2413
+ child2.on("error", (e) => {
2414
+ for (const p of this.pending.values()) p.reject(e);
2415
+ this.pending.clear();
2416
+ });
2417
+ }
2418
+ child;
2419
+ onNotify;
2420
+ onRequest;
2421
+ next = 1;
2422
+ pending = /* @__PURE__ */ new Map();
2423
+ buf = "";
2424
+ stderr = "";
2425
+ exited;
2426
+ lastError() {
2427
+ return this.stderr.trim().split("\n").filter(Boolean).pop() ?? "";
2428
+ }
2429
+ send(msg) {
2430
+ this.child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...msg })}
2431
+ `);
2432
+ }
2433
+ call(method2, params, timeoutMs = 0) {
2434
+ const id = this.next++;
2435
+ return new Promise((resolve, reject) => {
2436
+ const timer = timeoutMs ? setTimeout(() => {
2437
+ this.pending.delete(id);
2438
+ reject(new Error(`${method2} timed out`));
2439
+ }, timeoutMs) : null;
2440
+ this.pending.set(id, {
2441
+ resolve: (v) => {
2442
+ if (timer) clearTimeout(timer);
2443
+ resolve(v);
2444
+ },
2445
+ reject: (e) => {
2446
+ if (timer) clearTimeout(timer);
2447
+ reject(e);
2448
+ }
2449
+ });
2450
+ this.send({ id, method: method2, params });
2451
+ });
2452
+ }
2453
+ feed(chunk) {
2454
+ this.buf += chunk;
2455
+ let nl;
2456
+ while ((nl = this.buf.indexOf("\n")) >= 0) {
2457
+ const line = this.buf.slice(0, nl).trim();
2458
+ this.buf = this.buf.slice(nl + 1);
2459
+ if (!line) continue;
2460
+ let msg;
2461
+ try {
2462
+ msg = JSON.parse(line);
2463
+ } catch {
2464
+ continue;
2465
+ }
2466
+ if (msg.id != null && msg.method) {
2467
+ this.onRequest(msg.method, msg.params).then(
2468
+ (result) => this.send({ id: msg.id, result }),
2469
+ (e) => this.send({ id: msg.id, error: { code: e.code ?? -32603, message: e.message } })
2470
+ );
2471
+ } else if (msg.id != null) {
2472
+ const p = this.pending.get(msg.id);
2473
+ if (!p) continue;
2474
+ this.pending.delete(msg.id);
2475
+ if (msg.error) {
2476
+ const err = new Error(msg.error.message || "agent error");
2477
+ err.code = msg.error.code;
2478
+ err.data = msg.error.data;
2479
+ p.reject(err);
2480
+ } else {
2481
+ p.resolve(msg.result);
2482
+ }
2483
+ } else if (msg.method) {
2484
+ this.onNotify(msg.method, msg.params);
2485
+ }
2486
+ }
2487
+ }
2488
+ };
2489
+ TOOL_NAMES = {
2490
+ read: "Read",
2491
+ edit: "Edit",
2492
+ delete: "Edit",
2493
+ move: "Edit",
2494
+ search: "Grep",
2495
+ execute: "Bash",
2496
+ think: "Think",
2497
+ fetch: "Fetch",
2498
+ switch_mode: "Mode",
2499
+ other: "Tool"
2500
+ };
2501
+ }
2502
+ });
2503
+
2504
+ // src/runtime/meta.ts
2505
+ import fs10 from "fs";
2506
+ import path9 from "path";
2507
+ function read2() {
1789
2508
  try {
1790
- return JSON.parse(fs9.readFileSync(META_PATH, "utf8"));
2509
+ return JSON.parse(fs10.readFileSync(META_PATH, "utf8"));
1791
2510
  } catch {
1792
2511
  return {};
1793
2512
  }
1794
2513
  }
1795
- function write2(store) {
1796
- fs9.mkdirSync(path8.dirname(META_PATH), { recursive: true });
1797
- fs9.writeFileSync(META_PATH, JSON.stringify(store, null, 2) + "\n", { mode: 384 });
2514
+ function write3(store) {
2515
+ fs10.mkdirSync(path9.dirname(META_PATH), { recursive: true });
2516
+ fs10.writeFileSync(META_PATH, JSON.stringify(store, null, 2) + "\n", { mode: 384 });
1798
2517
  }
1799
2518
  function all() {
1800
- return read();
2519
+ return read2();
1801
2520
  }
1802
2521
  function setTitle(sessionId, title) {
1803
- const store = read();
2522
+ const store = read2();
1804
2523
  store[sessionId] = { ...store[sessionId], title };
1805
- write2(store);
2524
+ write3(store);
1806
2525
  }
1807
2526
  function setArchived(sessionId, archived) {
1808
- const store = read();
2527
+ const store = read2();
1809
2528
  store[sessionId] = { ...store[sessionId], archived };
1810
2529
  if (!store[sessionId].title && !store[sessionId].archived) delete store[sessionId];
1811
- write2(store);
2530
+ write3(store);
1812
2531
  }
1813
2532
  var META_PATH;
1814
2533
  var init_meta = __esm({
1815
2534
  "src/runtime/meta.ts"() {
1816
2535
  "use strict";
1817
2536
  init_config();
1818
- META_PATH = path8.join(SAKURA_DIR, "session-meta.json");
2537
+ META_PATH = path9.join(SAKURA_DIR, "session-meta.json");
1819
2538
  }
1820
2539
  });
1821
2540
 
1822
2541
  // src/runtime/sessions.ts
1823
- import { spawn as spawn7 } from "child_process";
2542
+ import { spawn as spawn8 } from "child_process";
2543
+ import fs11 from "fs";
2544
+ import os6 from "os";
2545
+ import path10 from "path";
1824
2546
  async function list(opts = {}) {
1825
2547
  let sessions = [];
1826
2548
  if (!opts.agent || opts.agent === "claude") sessions.push(...listSessions());
1827
- if (!opts.agent || opts.agent === "codex") sessions.push(...listSessions2());
2549
+ if (!opts.agent || opts.agent === "codex") sessions.push(...await listSessions2());
1828
2550
  if (!opts.agent || opts.agent === "opencode")
1829
2551
  sessions.push(...await listSessions3());
1830
2552
  if (!opts.agent || opts.agent === "zcode")
1831
2553
  sessions.push(...await listSessions4());
1832
2554
  if (!opts.agent || opts.agent === "deepseek")
1833
2555
  sessions.push(...await listSessions5());
2556
+ if (!opts.agent || opts.agent === "acp") sessions.push(...listSessions6());
1834
2557
  sessions.sort((a, b) => b.mtime - a.mtime);
1835
2558
  if (sessions.some((s) => s.agent === "codex")) {
1836
2559
  const cwds = await threadCwds();
@@ -1861,6 +2584,7 @@ async function show(sessionId) {
1861
2584
  }
1862
2585
  async function detectAgent(sessionId) {
1863
2586
  if (findFile(sessionId)) return "claude";
2587
+ if (has(sessionId)) return "acp";
1864
2588
  if (findFile2(sessionId)) return "codex";
1865
2589
  if (sessionId.startsWith("session-") && findFile3(sessionId)) return "deepseek";
1866
2590
  if (await hasSession(sessionId)) return "zcode";
@@ -1868,7 +2592,7 @@ async function detectAgent(sessionId) {
1868
2592
  if (oc.length) return "opencode";
1869
2593
  return null;
1870
2594
  }
1871
- async function messages6(sessionId, agent) {
2595
+ async function messages7(sessionId, agent) {
1872
2596
  const a = agent ?? await detectAgent(sessionId);
1873
2597
  switch (a) {
1874
2598
  case "claude":
@@ -1881,31 +2605,70 @@ async function messages6(sessionId, agent) {
1881
2605
  return messages4(sessionId);
1882
2606
  case "deepseek":
1883
2607
  return messages5(sessionId);
2608
+ case "acp":
2609
+ return messages6(sessionId);
1884
2610
  default:
1885
2611
  return [];
1886
2612
  }
1887
2613
  }
1888
2614
  async function history(sessionId, opts = {}, agent) {
1889
- let msgs = await messages6(sessionId, agent);
2615
+ let msgs = await messages7(sessionId, agent);
1890
2616
  if (!opts.all && opts.limit && opts.limit > 0) {
1891
2617
  msgs = msgs.slice(-opts.limit);
1892
2618
  }
1893
2619
  if (opts.reverse) msgs = [...msgs].reverse();
1894
2620
  return msgs;
1895
2621
  }
1896
- async function chat(sessionId, prompt, agent, onData, images, model, run5) {
2622
+ async function chat(sessionId, prompt, agent, onData, images, model, run6) {
1897
2623
  const a = agent ?? await detectAgent(sessionId);
1898
- if (a === "claude") return send(sessionId, prompt, onData, images, model, run5);
2624
+ if (a === "claude") return send(sessionId, prompt, onData, images, model, run6);
1899
2625
  if (a === "codex") return send2(sessionId, prompt, onData, images, model);
1900
2626
  if (a === "opencode") return send3(sessionId, prompt, onData, images, model);
1901
2627
  if (a === "zcode") return send4(sessionId, prompt, onData, images, model);
1902
2628
  if (a === "deepseek") return send5(sessionId, prompt, onData, images, model);
2629
+ if (a === "acp") return send6(sessionId, prompt, onData, images, model, run6);
1903
2630
  return {
1904
2631
  ok: false,
1905
2632
  output: "",
1906
2633
  error: `Sending is not supported for this session (got ${a ?? "unknown"}).`
1907
2634
  };
1908
2635
  }
2636
+ function chatNew(agent, cwd, prompt, onData, model) {
2637
+ if (agent === "codex") return send2("", prompt, onData, void 0, model, cwd);
2638
+ if (agent === "opencode") return send3("", prompt, onData, void 0, model, cwd);
2639
+ if (agent === "zcode") return send4("", prompt, onData, void 0, model, cwd);
2640
+ if (agent === "deepseek") return send5("", prompt, onData, void 0, model, cwd);
2641
+ return Promise.resolve({ ok: false, output: "", error: `Can't start a ${agent} session this way.` });
2642
+ }
2643
+ async function awaitNewSession(agent, cwd, before, done, timeoutMs = 6e4) {
2644
+ let finished = false;
2645
+ void done.finally(() => {
2646
+ finished = true;
2647
+ });
2648
+ const deadline = Date.now() + timeoutMs;
2649
+ for (; ; ) {
2650
+ const fresh = (await list({ agent, all: true })).filter((s) => !before.has(s.id));
2651
+ const pick2 = fresh.find((s) => s.cwd === cwd) ?? fresh[0];
2652
+ if (pick2) return pick2.id;
2653
+ if (finished || Date.now() > deadline) return null;
2654
+ await new Promise((r) => setTimeout(r, 400));
2655
+ }
2656
+ }
2657
+ function runnableAgents() {
2658
+ const bins = {
2659
+ claude: () => onPath2(process.env.CLAUDE_BIN || "claude") || fs11.existsSync(path10.join(os6.homedir(), ".local", "bin", "claude")),
2660
+ codex: () => onPath2(codexBin()),
2661
+ opencode: () => onPath2(opencodeBin()),
2662
+ zcode: () => {
2663
+ const { cmd, args } = launchArgs([]);
2664
+ return cmd === process.execPath ? fs11.existsSync(args[0] ?? "") : onPath2(cmd);
2665
+ },
2666
+ deepseek: () => onPath2(dshBin()),
2667
+ acp: () => false
2668
+ // registry agents are listed on their own (acp.enabledAgents)
2669
+ };
2670
+ return Object.keys(bins).filter((a) => bins[a]());
2671
+ }
1909
2672
  function create(prompt, opts = {}) {
1910
2673
  const agent = opts.agent ?? "claude";
1911
2674
  if (agent === "claude") return runCreate(process.env.CLAUDE_BIN || "claude", ["-p", prompt], opts.cwd);
@@ -1923,7 +2686,7 @@ function create(prompt, opts = {}) {
1923
2686
  }
1924
2687
  function runCreate(cmd, args, cwd, env = process.env) {
1925
2688
  return new Promise((resolve) => {
1926
- const child2 = spawn7(cmd, args, {
2689
+ const child2 = spawn8(cmd, args, {
1927
2690
  cwd: cwd || process.cwd(),
1928
2691
  stdio: ["ignore", "pipe", "pipe"],
1929
2692
  env
@@ -1943,6 +2706,7 @@ function runCreate(cmd, args, cwd, env = process.env) {
1943
2706
  );
1944
2707
  });
1945
2708
  }
2709
+ var onPath2;
1946
2710
  var init_sessions = __esm({
1947
2711
  "src/runtime/sessions.ts"() {
1948
2712
  "use strict";
@@ -1951,7 +2715,70 @@ var init_sessions = __esm({
1951
2715
  init_opencode();
1952
2716
  init_zcode();
1953
2717
  init_deepseek();
2718
+ init_acp();
1954
2719
  init_meta();
2720
+ onPath2 = (bin) => path10.isAbsolute(bin) ? fs11.existsSync(bin) : (process.env.PATH ?? "").split(path10.delimiter).some((d) => d && fs11.existsSync(path10.join(d, bin)));
2721
+ }
2722
+ });
2723
+
2724
+ // src/runtime/handoff.ts
2725
+ function render(m, who) {
2726
+ const body = [];
2727
+ for (const p of m.parts ?? [{ type: "text", text: m.content }]) {
2728
+ if (p.type === "text" && p.text.trim()) body.push(p.text.trim());
2729
+ else if (p.type === "tool") body.push(`- ${p.name}: ${p.title}${p.status === "error" ? " (failed)" : ""}`);
2730
+ }
2731
+ return body.length ? `**${m.role === "user" ? "User" : who}:**
2732
+ ${body.join("\n")}` : "";
2733
+ }
2734
+ async function handoffTitle(from) {
2735
+ const first = (await list({ all: true })).find((x) => x.id === from[0]?.id);
2736
+ const more = from.length > 1 ? ` +${from.length - 1}` : "";
2737
+ return `Continued: ${first?.title ?? "conversation"}${more}`.slice(0, 80);
2738
+ }
2739
+ async function handoffPrompt(from, ask) {
2740
+ const all2 = await list({ all: true });
2741
+ const blocks = [];
2742
+ for (const src of from) {
2743
+ const s = all2.find((x) => x.id === src.id && x.agent === src.agent);
2744
+ const who = s?.acp?.name ?? LABEL[src.agent];
2745
+ const msgs = await messages7(src.id, src.agent);
2746
+ let text = msgs.map((m) => render(m, who)).filter(Boolean).join("\n\n");
2747
+ if (text.length > PER_CHAT) text = `[earlier part cut]
2748
+ ${text.slice(-PER_CHAT)}`;
2749
+ blocks.push(`## ${s?.title ?? "Conversation"} (with ${who})
2750
+
2751
+ ${text || "(empty)"}`);
2752
+ }
2753
+ let context = blocks.join("\n\n---\n\n");
2754
+ if (context.length > TOTAL) context = `[earlier part cut]
2755
+ ${context.slice(-TOTAL)}`;
2756
+ const n = from.length;
2757
+ return [
2758
+ `<sakura-handoff count="${n}">`,
2759
+ `You're picking up ${n === 1 ? "a conversation" : `${n} conversations`} the user had with another coding agent in this project. Treat it as your own history: the files it changed are already changed.`,
2760
+ "",
2761
+ context,
2762
+ "</sakura-handoff>",
2763
+ "",
2764
+ ask?.trim() || "Pick up where this left off: say in a few lines where things stand, then carry on with what was in progress."
2765
+ ].join("\n");
2766
+ }
2767
+ var LABEL, PER_CHAT, TOTAL;
2768
+ var init_handoff = __esm({
2769
+ "src/runtime/handoff.ts"() {
2770
+ "use strict";
2771
+ init_sessions();
2772
+ LABEL = {
2773
+ claude: "Claude Code",
2774
+ codex: "Codex",
2775
+ opencode: "OpenCode",
2776
+ zcode: "ZCode",
2777
+ deepseek: "DeepSeek",
2778
+ acp: "ACP agent"
2779
+ };
2780
+ PER_CHAT = 3e4;
2781
+ TOTAL = 9e4;
1955
2782
  }
1956
2783
  });
1957
2784
 
@@ -1965,12 +2792,12 @@ function addPushToken(token) {
1965
2792
  async function sendPush(title, body, data = {}) {
1966
2793
  const tokens = loadConfig().pushTokens ?? [];
1967
2794
  if (tokens.length === 0) return;
1968
- const messages7 = tokens.map((to) => ({ to, title, body, sound: "default", data }));
2795
+ const messages8 = tokens.map((to) => ({ to, title, body, sound: "default", data }));
1969
2796
  try {
1970
2797
  const res = await fetch(EXPO_PUSH_URL, {
1971
2798
  method: "POST",
1972
2799
  headers: { "Content-Type": "application/json", Accept: "application/json" },
1973
- body: JSON.stringify(messages7)
2800
+ body: JSON.stringify(messages8)
1974
2801
  });
1975
2802
  if (!res.ok) console.error(`[push] send failed: HTTP ${res.status}`);
1976
2803
  } catch (e) {
@@ -2044,10 +2871,10 @@ __export(registry_exports, {
2044
2871
  thisMachine: () => thisMachine,
2045
2872
  updateAgentConfig: () => updateAgentConfig
2046
2873
  });
2047
- import os5 from "os";
2048
- import fs10 from "fs";
2049
- import path9 from "path";
2050
- import { randomUUID as randomUUID2 } from "crypto";
2874
+ import os7 from "os";
2875
+ import fs12 from "fs";
2876
+ import path11 from "path";
2877
+ import { randomUUID as randomUUID3 } from "crypto";
2051
2878
  function listWorkspaces() {
2052
2879
  return loadConfig().workspaces;
2053
2880
  }
@@ -2060,24 +2887,24 @@ function detectCli() {
2060
2887
  zcode: process.env.ZCODE_BIN || "zcode",
2061
2888
  deepseek: process.env.DSH_BIN || "dsh"
2062
2889
  };
2063
- const pathDirs = (process.env.PATH || "").split(path9.delimiter);
2890
+ const pathDirs = (process.env.PATH || "").split(path11.delimiter);
2064
2891
  for (const [name, bin] of Object.entries(candidates)) {
2065
- const onPath = pathDirs.some((dir) => {
2892
+ const onPath3 = pathDirs.some((dir) => {
2066
2893
  try {
2067
- return fs10.existsSync(path9.join(dir, bin));
2894
+ return fs12.existsSync(path11.join(dir, bin));
2068
2895
  } catch {
2069
2896
  return false;
2070
2897
  }
2071
2898
  });
2072
- const home = os5.homedir();
2899
+ const home = os7.homedir();
2073
2900
  const dataDirs = {
2074
- claude: path9.join(home, ".claude"),
2075
- codex: path9.join(home, ".codex"),
2076
- opencode: path9.join(home, ".local", "share", "opencode"),
2077
- zcode: path9.join(home, ".zcode"),
2078
- deepseek: path9.join(home, ".dsh")
2901
+ claude: path11.join(home, ".claude"),
2902
+ codex: path11.join(home, ".codex"),
2903
+ opencode: path11.join(home, ".local", "share", "opencode"),
2904
+ zcode: path11.join(home, ".zcode"),
2905
+ deepseek: path11.join(home, ".dsh")
2079
2906
  };
2080
- if (onPath || fs10.existsSync(dataDirs[name] ?? "")) found.push(name);
2907
+ if (onPath3 || fs12.existsSync(dataDirs[name] ?? "")) found.push(name);
2081
2908
  }
2082
2909
  return found;
2083
2910
  }
@@ -2087,8 +2914,8 @@ function thisMachine() {
2087
2914
  id: cfg.machineId,
2088
2915
  name: cfg.machineName,
2089
2916
  online: true,
2090
- os: `${os5.type()} ${os5.release()}`,
2091
- hostname: os5.hostname(),
2917
+ os: `${os7.type()} ${os7.release()}`,
2918
+ hostname: os7.hostname(),
2092
2919
  cli: detectCli()
2093
2920
  };
2094
2921
  }
@@ -2101,15 +2928,15 @@ function listProjects() {
2101
2928
  return loadConfig().projects;
2102
2929
  }
2103
2930
  function addProject(dir, name) {
2104
- const abs = path9.resolve(dir);
2105
- if (!fs10.existsSync(abs) || !fs10.statSync(abs).isDirectory()) {
2931
+ const abs = path11.resolve(dir);
2932
+ if (!fs12.existsSync(abs) || !fs12.statSync(abs).isDirectory()) {
2106
2933
  throw new Error(`Not a directory: ${abs}`);
2107
2934
  }
2108
2935
  const existing = loadConfig().projects.find((p) => p.path === abs);
2109
2936
  if (existing) return existing;
2110
2937
  const project = {
2111
- id: randomUUID2(),
2112
- name: name || path9.basename(abs),
2938
+ id: randomUUID3(),
2939
+ name: name || path11.basename(abs),
2113
2940
  path: abs,
2114
2941
  addedAt: Date.now()
2115
2942
  };
@@ -2123,7 +2950,7 @@ function deleteProject(idOrNameOrPath) {
2123
2950
  updateConfig((cfg) => {
2124
2951
  const before = cfg.projects.length;
2125
2952
  cfg.projects = cfg.projects.filter(
2126
- (p) => p.id !== idOrNameOrPath && p.name !== idOrNameOrPath && p.path !== path9.resolve(idOrNameOrPath)
2953
+ (p) => p.id !== idOrNameOrPath && p.name !== idOrNameOrPath && p.path !== path11.resolve(idOrNameOrPath)
2127
2954
  );
2128
2955
  removed = cfg.projects.length !== before;
2129
2956
  });
@@ -2131,7 +2958,7 @@ function deleteProject(idOrNameOrPath) {
2131
2958
  }
2132
2959
  function resolveProject(idOrNameOrPath) {
2133
2960
  const cfg = loadConfig();
2134
- const abs = path9.resolve(idOrNameOrPath);
2961
+ const abs = path11.resolve(idOrNameOrPath);
2135
2962
  return cfg.projects.find(
2136
2963
  (p) => p.id === idOrNameOrPath || p.name === idOrNameOrPath || p.path === abs
2137
2964
  ) ?? null;
@@ -2154,7 +2981,7 @@ function resolveAgentConfig(idOrName) {
2154
2981
  function createAgentConfig(input2) {
2155
2982
  const now = Date.now();
2156
2983
  const config = {
2157
- id: randomUUID2(),
2984
+ id: randomUUID3(),
2158
2985
  name: input2.name,
2159
2986
  agentType: input2.agentType,
2160
2987
  description: input2.description,
@@ -2225,14 +3052,14 @@ var init_registry = __esm({
2225
3052
  });
2226
3053
 
2227
3054
  // src/runtime/projects.ts
2228
- import fs11 from "fs";
2229
- import path10 from "path";
2230
- import { createHash, randomUUID as randomUUID3 } from "crypto";
2231
- import { execFile } from "child_process";
2232
- import { promisify } from "util";
3055
+ import fs13 from "fs";
3056
+ import path12 from "path";
3057
+ import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
3058
+ import { execFile as execFile2 } from "child_process";
3059
+ import { promisify as promisify2 } from "util";
2233
3060
  async function git(cwd, args) {
2234
3061
  try {
2235
- const { stdout } = await run("git", args, {
3062
+ const { stdout } = await run2("git", args, {
2236
3063
  cwd,
2237
3064
  timeout: 5e3,
2238
3065
  maxBuffer: 4 * 1024 * 1024,
@@ -2247,11 +3074,11 @@ async function git(cwd, args) {
2247
3074
  async function projectRoot(cwd) {
2248
3075
  if (rootCache.has(cwd)) return rootCache.get(cwd);
2249
3076
  let root = null;
2250
- if (fs11.existsSync(cwd)) {
3077
+ if (fs13.existsSync(cwd)) {
2251
3078
  const out = await git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir", "--show-toplevel"]);
2252
3079
  if (out) {
2253
3080
  const [common, top] = out.trim().split("\n");
2254
- root = common && path10.basename(common) === ".git" ? path10.dirname(common) : top || cwd;
3081
+ root = common && path12.basename(common) === ".git" ? path12.dirname(common) : top || cwd;
2255
3082
  } else {
2256
3083
  root = cwd;
2257
3084
  }
@@ -2262,9 +3089,9 @@ async function projectRoot(cwd) {
2262
3089
  function isScratch(p) {
2263
3090
  if (p === HOME || p === "/") return true;
2264
3091
  if (/^\/(private\/)?(tmp|var\/folders)(\/|$)/.test(p)) return true;
2265
- const rel = path10.relative(HOME, p);
3092
+ const rel = path12.relative(HOME, p);
2266
3093
  if (rel.startsWith("..")) return false;
2267
- return rel.split(path10.sep).some((seg) => seg.startsWith(".")) || /(^|\/)default-workspace$/.test(rel);
3094
+ return rel.split(path12.sep).some((seg) => seg.startsWith(".")) || /(^|\/)default-workspace$/.test(rel);
2268
3095
  }
2269
3096
  function githubSlug(url) {
2270
3097
  const m = /github\.com[:/]([^/]+\/[^/]+?)(\.git)?$/.exec(url.trim());
@@ -2303,19 +3130,29 @@ async function list2() {
2303
3130
  const last = ss.length ? Math.max(...ss.map((s) => s.mtime)) : null;
2304
3131
  return {
2305
3132
  id: projectId(p),
2306
- name: registered.get(p)?.name ?? path10.basename(p),
3133
+ name: registered.get(p)?.name ?? path12.basename(p),
2307
3134
  path: p,
2308
3135
  registered: registered.has(p),
2309
3136
  sessions: ss.length,
2310
3137
  agents: [...new Set(ss.map((s) => s.agent))],
2311
3138
  lastActive: last,
2312
3139
  updatedAt: last != null ? formatAge(Math.max(0, now - last)) : null,
2313
- git: fs11.existsSync(p) ? await gitSummary(p) : null
3140
+ git: fs13.existsSync(p) ? await gitSummary(p) : null
2314
3141
  };
2315
3142
  })
2316
3143
  );
2317
3144
  return out.sort((a, b) => (b.lastActive ?? 0) - (a.lastActive ?? 0) || a.name.localeCompare(b.name));
2318
3145
  }
3146
+ async function tagSessions(list4) {
3147
+ const cfg = loadConfig();
3148
+ const hidden = new Set(cfg.hiddenProjects ?? []);
3149
+ const names = new Map(cfg.projects.map((p) => [p.path, p.name]));
3150
+ return Promise.all(list4.map(async (s) => {
3151
+ const root = s.cwd ? await projectRoot(s.cwd) : null;
3152
+ if (!root || hidden.has(root) || isScratch(root)) return s;
3153
+ return { ...s, project: { id: projectId(root), name: names.get(root) ?? path12.basename(root) } };
3154
+ }));
3155
+ }
2319
3156
  async function find(id) {
2320
3157
  return (await list2()).find((p) => p.id === id) ?? null;
2321
3158
  }
@@ -2334,16 +3171,16 @@ async function detail(id) {
2334
3171
  ]);
2335
3172
  const counts = /* @__PURE__ */ new Map();
2336
3173
  for (const line of (numstat ?? "").split("\n")) {
2337
- const [a, d, file] = line.split(" ");
2338
- if (file) counts.set(file.replace(/^.*\{.* => (.*)\}.*$/, "$1"), [Number(a) || 0, Number(d) || 0]);
3174
+ const [a, d, file2] = line.split(" ");
3175
+ if (file2) counts.set(file2.replace(/^.*\{.* => (.*)\}.*$/, "$1"), [Number(a) || 0, Number(d) || 0]);
2339
3176
  }
2340
3177
  const changes = [];
2341
3178
  for (const line of (status2 ?? "").split("\n")) {
2342
3179
  if (line.length < 4) continue;
2343
3180
  const code = line[0] !== " " ? line[0] : line[1];
2344
- const file = line.slice(3).split(" -> ").pop().replace(/^"|"$/g, "");
2345
- const [additions, deletions] = counts.get(file) ?? [0, 0];
2346
- changes.push({ path: file, status: STATUS[code] ?? "modified", additions, deletions });
3181
+ const file2 = line.slice(3).split(" -> ").pop().replace(/^"|"$/g, "");
3182
+ const [additions, deletions] = counts.get(file2) ?? [0, 0];
3183
+ changes.push({ path: file2, status: STATUS[code] ?? "modified", additions, deletions });
2347
3184
  }
2348
3185
  const commits = (log2 ?? "").split("\n").filter(Boolean).map((l) => {
2349
3186
  const [hash, subject, author, ct] = l.split("");
@@ -2353,7 +3190,7 @@ async function detail(id) {
2353
3190
  return { ...p, changes, commits, branches, sessionList };
2354
3191
  }
2355
3192
  function add(dir) {
2356
- const abs = path10.resolve(dir.replace(/^~(?=$|\/)/, HOME));
3193
+ const abs = path12.resolve(dir.replace(/^~(?=$|\/)/, HOME));
2357
3194
  addProject(abs);
2358
3195
  updateConfig((c) => {
2359
3196
  c.hiddenProjects = (c.hiddenProjects ?? []).filter((h) => h !== abs);
@@ -2370,47 +3207,60 @@ async function remove(id) {
2370
3207
  return true;
2371
3208
  }
2372
3209
  function browse(dir) {
2373
- const abs = path10.resolve((dir || HOME).replace(/^~(?=$|\/)/, HOME));
2374
- if (path10.relative(HOME, abs).startsWith("..")) throw new Error("Only folders inside your home folder can be added.");
3210
+ const abs = path12.resolve((dir || HOME).replace(/^~(?=$|\/)/, HOME));
3211
+ if (path12.relative(HOME, abs).startsWith("..")) throw new Error("Only folders inside your home folder can be added.");
2375
3212
  const entries = [];
2376
- for (const d of fs11.readdirSync(abs, { withFileTypes: true })) {
3213
+ for (const d of fs13.readdirSync(abs, { withFileTypes: true })) {
2377
3214
  if (!d.isDirectory() || d.name.startsWith(".") || d.name === "node_modules") continue;
2378
- const p = path10.join(abs, d.name);
2379
- entries.push({ name: d.name, path: p, isGit: fs11.existsSync(path10.join(p, ".git")) });
3215
+ const p = path12.join(abs, d.name);
3216
+ entries.push({ name: d.name, path: p, isGit: fs13.existsSync(path12.join(p, ".git")) });
2380
3217
  }
2381
3218
  entries.sort((a, b) => Number(b.isGit) - Number(a.isGit) || a.name.localeCompare(b.name));
2382
- return { path: abs, parent: abs === HOME ? null : path10.dirname(abs), entries: entries.slice(0, 400) };
3219
+ return { path: abs, parent: abs === HOME ? null : path12.dirname(abs), entries: entries.slice(0, 400) };
2383
3220
  }
2384
- async function prepareSession(id, agent, worktree) {
3221
+ async function prepareSession(id, agent, worktree, acpId) {
2385
3222
  const p = await find(id);
2386
3223
  if (!p) throw new Error("project not found");
2387
- if (agent !== "claude") throw new Error("Starting chats from a project currently supports Claude Code.");
2388
- const sessionId = randomUUID3();
3224
+ const sessionId = randomUUID4();
2389
3225
  let cwd = p.path;
2390
3226
  let branch;
2391
3227
  if (worktree) {
2392
3228
  if (!p.git) throw new Error("Worktrees need a git repository.");
2393
3229
  const short = sessionId.slice(0, 8);
2394
3230
  branch = `sakura/${short}`;
2395
- cwd = path10.join(WORKTREES_DIR, `${p.name}-${short}`);
2396
- fs11.mkdirSync(WORKTREES_DIR, { recursive: true });
3231
+ cwd = path12.join(WORKTREES_DIR, `${p.name}-${short}`);
3232
+ fs13.mkdirSync(WORKTREES_DIR, { recursive: true });
2397
3233
  if (await git(p.path, ["worktree", "add", "-b", branch, cwd]) == null) {
2398
3234
  throw new Error("Could not create a git worktree for this chat.");
2399
3235
  }
2400
3236
  }
2401
- prepareNew(sessionId, cwd);
3237
+ await prepareFor(agent, sessionId, cwd, acpId);
2402
3238
  return { sessionId, cwd, branch };
2403
3239
  }
3240
+ async function prepareScratch(agent, acpId) {
3241
+ const sessionId = randomUUID4();
3242
+ const cwd = path12.join(SAKURA_DIR, "chats", sessionId.slice(0, 8));
3243
+ fs13.mkdirSync(cwd, { recursive: true });
3244
+ await prepareFor(agent, sessionId, cwd, acpId);
3245
+ return { sessionId, cwd };
3246
+ }
3247
+ async function prepareFor(agent, sessionId, cwd, acpId) {
3248
+ if (agent === "claude") prepareNew(sessionId, cwd);
3249
+ if (agent === "acp") {
3250
+ if (!acpId) throw new Error("Pick which ACP agent to use.");
3251
+ await prepareNew2(sessionId, cwd, acpId);
3252
+ }
3253
+ }
2404
3254
  async function chatContext(sessionId, agent) {
2405
3255
  const s = (await list({})).find((x) => x.id === sessionId && x.agent === agent);
2406
3256
  const cwd = s?.cwd ?? pendingCwd(sessionId) ?? null;
2407
3257
  const machine = loadConfig().machineName || hostname();
2408
- if (!cwd || !fs11.existsSync(cwd)) return { cwd, project: null, git: null, machine };
3258
+ if (!cwd || !fs13.existsSync(cwd)) return { cwd, project: null, git: null, machine };
2409
3259
  const root = await projectRoot(cwd);
2410
- const project = root && !isScratch(root) ? { id: projectId(root), name: path10.basename(root), path: root } : null;
3260
+ const project = root && !isScratch(root) ? { id: projectId(root), name: path12.basename(root), path: root } : null;
2411
3261
  return { cwd, project, git: await gitSummary(cwd), machine };
2412
3262
  }
2413
- var run, WORKTREES_DIR, projectId, rootCache, STATUS;
3263
+ var run2, WORKTREES_DIR, projectId, rootCache, STATUS;
2414
3264
  var init_projects = __esm({
2415
3265
  "src/runtime/projects.ts"() {
2416
3266
  "use strict";
@@ -2418,34 +3268,35 @@ var init_projects = __esm({
2418
3268
  init_registry();
2419
3269
  init_sessions();
2420
3270
  init_claude();
3271
+ init_acp();
2421
3272
  init_util();
2422
- run = promisify(execFile);
2423
- WORKTREES_DIR = path10.join(HOME, ".sakura", "worktrees");
2424
- projectId = (p) => createHash("sha1").update(p).digest("hex").slice(0, 12);
3273
+ run2 = promisify2(execFile2);
3274
+ WORKTREES_DIR = path12.join(HOME, ".sakura", "worktrees");
3275
+ projectId = (p) => createHash2("sha1").update(p).digest("hex").slice(0, 12);
2425
3276
  rootCache = /* @__PURE__ */ new Map();
2426
3277
  STATUS = { M: "modified", A: "added", D: "deleted", R: "renamed", "?": "untracked" };
2427
3278
  }
2428
3279
  });
2429
3280
 
2430
3281
  // src/runtime/fsops.ts
2431
- import fs12 from "fs";
2432
- import path11 from "path";
2433
- import os6 from "os";
3282
+ import fs14 from "fs";
3283
+ import path13 from "path";
3284
+ import os8 from "os";
2434
3285
  function expand(p) {
2435
3286
  if (!p || p === "~") return HOME2;
2436
- if (p.startsWith("~/")) return path11.join(HOME2, p.slice(2));
2437
- return path11.resolve(p);
3287
+ if (p.startsWith("~/")) return path13.join(HOME2, p.slice(2));
3288
+ return path13.resolve(p);
2438
3289
  }
2439
3290
  function list3(dir) {
2440
3291
  const abs = expand(dir);
2441
- const dirents = fs12.readdirSync(abs, { withFileTypes: true });
3292
+ const dirents = fs14.readdirSync(abs, { withFileTypes: true });
2442
3293
  const entries = [];
2443
3294
  for (const d of dirents) {
2444
- const p = path11.join(abs, d.name);
3295
+ const p = path13.join(abs, d.name);
2445
3296
  let size = 0;
2446
3297
  let mtime = 0;
2447
3298
  try {
2448
- const st = fs12.statSync(p);
3299
+ const st = fs14.statSync(p);
2449
3300
  size = st.size;
2450
3301
  mtime = Math.floor(st.mtimeMs / 1e3);
2451
3302
  } catch {
@@ -2458,7 +3309,7 @@ function list3(dir) {
2458
3309
  if (a.type !== "dir" && b.type === "dir") return 1;
2459
3310
  return a.name.localeCompare(b.name);
2460
3311
  });
2461
- const parent = abs === "/" ? null : path11.dirname(abs);
3312
+ const parent = abs === "/" ? null : path13.dirname(abs);
2462
3313
  return { path: abs, parent, entries };
2463
3314
  }
2464
3315
  function looksBinary(buf) {
@@ -2466,14 +3317,14 @@ function looksBinary(buf) {
2466
3317
  for (let i = 0; i < n; i++) if (buf[i] === 0) return true;
2467
3318
  return false;
2468
3319
  }
2469
- function read2(file) {
2470
- const abs = expand(file);
2471
- const st = fs12.statSync(abs);
2472
- const fd = fs12.openSync(abs, "r");
3320
+ function read3(file2) {
3321
+ const abs = expand(file2);
3322
+ const st = fs14.statSync(abs);
3323
+ const fd = fs14.openSync(abs, "r");
2473
3324
  try {
2474
3325
  const len = Math.min(st.size, READ_CAP);
2475
3326
  const buf = Buffer.alloc(len);
2476
- fs12.readSync(fd, buf, 0, len, 0);
3327
+ fs14.readSync(fd, buf, 0, len, 0);
2477
3328
  const binary = looksBinary(buf);
2478
3329
  return {
2479
3330
  path: abs,
@@ -2483,40 +3334,40 @@ function read2(file) {
2483
3334
  content: binary ? "" : buf.toString("utf8")
2484
3335
  };
2485
3336
  } finally {
2486
- fs12.closeSync(fd);
3337
+ fs14.closeSync(fd);
2487
3338
  }
2488
3339
  }
2489
- function write3(file, content) {
2490
- const abs = expand(file);
2491
- fs12.mkdirSync(path11.dirname(abs), { recursive: true });
2492
- fs12.writeFileSync(abs, content, "utf8");
3340
+ function write4(file2, content) {
3341
+ const abs = expand(file2);
3342
+ fs14.mkdirSync(path13.dirname(abs), { recursive: true });
3343
+ fs14.writeFileSync(abs, content, "utf8");
2493
3344
  return { path: abs, bytes: Buffer.byteLength(content, "utf8") };
2494
3345
  }
2495
3346
  function mkdir(dir) {
2496
3347
  const abs = expand(dir);
2497
- fs12.mkdirSync(abs, { recursive: true });
3348
+ fs14.mkdirSync(abs, { recursive: true });
2498
3349
  return { path: abs };
2499
3350
  }
2500
3351
  var HOME2, READ_CAP;
2501
3352
  var init_fsops = __esm({
2502
3353
  "src/runtime/fsops.ts"() {
2503
3354
  "use strict";
2504
- HOME2 = os6.homedir();
3355
+ HOME2 = os8.homedir();
2505
3356
  READ_CAP = 512 * 1024;
2506
3357
  }
2507
3358
  });
2508
3359
 
2509
3360
  // src/tailscale.ts
2510
- import fs13 from "fs";
2511
- import { spawn as spawn8 } from "child_process";
3361
+ import fs15 from "fs";
3362
+ import { spawn as spawn9 } from "child_process";
2512
3363
  function tsBin() {
2513
3364
  const macPath = "/Applications/Tailscale.app/Contents/MacOS/Tailscale";
2514
- if (fs13.existsSync(macPath)) return macPath;
3365
+ if (fs15.existsSync(macPath)) return macPath;
2515
3366
  return process.env.TAILSCALE_BIN || "tailscale";
2516
3367
  }
2517
3368
  function runTs(args, timeoutMs = 6e4) {
2518
3369
  return new Promise((resolve) => {
2519
- const child2 = spawn8(tsBin(), args, { stdio: ["ignore", "pipe", "pipe"] });
3370
+ const child2 = spawn9(tsBin(), args, { stdio: ["ignore", "pipe", "pipe"] });
2520
3371
  let out = "";
2521
3372
  let err = "";
2522
3373
  const timer = setTimeout(() => {
@@ -2607,7 +3458,7 @@ function serve(port2) {
2607
3458
  function serveOff() {
2608
3459
  return runTs(["serve", "--https=443", "off"]);
2609
3460
  }
2610
- async function installed() {
3461
+ async function installed2() {
2611
3462
  const r = await runTs(["version"]);
2612
3463
  return { installed: r.code !== "not_installed", version: r.stdout, code: r.code };
2613
3464
  }
@@ -2626,8 +3477,8 @@ var init_tailscale = __esm({
2626
3477
  });
2627
3478
 
2628
3479
  // src/runtime/usage.ts
2629
- import fs14 from "fs";
2630
- import path12 from "path";
3480
+ import fs16 from "fs";
3481
+ import path14 from "path";
2631
3482
  import readline from "readline";
2632
3483
  function claudeCost(model, u) {
2633
3484
  const p = CLAUDE_PRICES.find((x) => x.match.test(model));
@@ -2645,28 +3496,28 @@ function add2(b, ms, agent, model, tokens, cost) {
2645
3496
  if (cost == null) cur.unpriced += tokens;
2646
3497
  else cur.cost += cost;
2647
3498
  }
2648
- async function* lines(file) {
2649
- const rl = readline.createInterface({ input: fs14.createReadStream(file, "utf8"), crlfDelay: Infinity });
3499
+ async function* lines(file2) {
3500
+ const rl = readline.createInterface({ input: fs16.createReadStream(file2, "utf8"), crlfDelay: Infinity });
2650
3501
  for await (const line of rl) yield line;
2651
3502
  }
2652
3503
  function walk(dir, out = []) {
2653
3504
  let entries;
2654
3505
  try {
2655
- entries = fs14.readdirSync(dir, { withFileTypes: true });
3506
+ entries = fs16.readdirSync(dir, { withFileTypes: true });
2656
3507
  } catch {
2657
3508
  return out;
2658
3509
  }
2659
3510
  for (const e of entries) {
2660
- const p = path12.join(dir, e.name);
3511
+ const p = path14.join(dir, e.name);
2661
3512
  if (e.isDirectory()) walk(p, out);
2662
3513
  else if (e.name.endsWith(".jsonl")) out.push(p);
2663
3514
  }
2664
3515
  return out;
2665
3516
  }
2666
- async function scanClaude(file) {
3517
+ async function scanClaude(file2) {
2667
3518
  const b = {};
2668
3519
  const seen = /* @__PURE__ */ new Set();
2669
- for await (const line of lines(file)) {
3520
+ for await (const line of lines(file2)) {
2670
3521
  if (!line.includes('"usage"')) continue;
2671
3522
  let e;
2672
3523
  try {
@@ -2693,12 +3544,12 @@ function limitWindow(w) {
2693
3544
  resetsAt: typeof w.resets_at === "number" ? w.resets_at : null
2694
3545
  };
2695
3546
  }
2696
- async function scanCodex(file) {
3547
+ async function scanCodex(file2) {
2697
3548
  const b = {};
2698
3549
  const extra = { plans: {}, limits: null };
2699
3550
  let model = "codex";
2700
3551
  let prevTotal = 0;
2701
- for await (const line of lines(file)) {
3552
+ for await (const line of lines(file2)) {
2702
3553
  const isCount = line.includes('"token_count"');
2703
3554
  if (!isCount && !line.includes('"model"')) continue;
2704
3555
  let e;
@@ -2734,7 +3585,7 @@ async function scanCodex(file) {
2734
3585
  }
2735
3586
  async function scanSqlite(agent, dbPath) {
2736
3587
  const b = {};
2737
- if (!fs14.existsSync(dbPath)) return b;
3588
+ if (!fs16.existsSync(dbPath)) return b;
2738
3589
  let Ctor;
2739
3590
  try {
2740
3591
  const mod = await import("better-sqlite3");
@@ -2768,7 +3619,7 @@ async function scanSqlite(agent, dbPath) {
2768
3619
  }
2769
3620
  function loadCache() {
2770
3621
  try {
2771
- const raw = JSON.parse(fs14.readFileSync(CACHE_FILE, "utf8"));
3622
+ const raw = JSON.parse(fs16.readFileSync(CACHE_FILE, "utf8"));
2772
3623
  return raw?.version === CACHE_VERSION ? raw.files ?? {} : {};
2773
3624
  } catch {
2774
3625
  return {};
@@ -2776,8 +3627,8 @@ function loadCache() {
2776
3627
  }
2777
3628
  function saveCache(files) {
2778
3629
  try {
2779
- fs14.mkdirSync(SAKURA_DIR, { recursive: true });
2780
- fs14.writeFileSync(CACHE_FILE, JSON.stringify({ version: CACHE_VERSION, files }));
3630
+ fs16.mkdirSync(SAKURA_DIR, { recursive: true });
3631
+ fs16.writeFileSync(CACHE_FILE, JSON.stringify({ version: CACHE_VERSION, files }));
2781
3632
  } catch {
2782
3633
  }
2783
3634
  }
@@ -2787,22 +3638,22 @@ async function scanAll() {
2787
3638
  const cache2 = loadCache();
2788
3639
  const next = {};
2789
3640
  const jobs = [
2790
- ...walk(path12.join(HOME, ".claude", "projects")).map((f) => [f, scanClaude]),
2791
- ...walk(path12.join(HOME, ".codex", "sessions")).map((f) => [f, scanCodex])
3641
+ ...walk(path14.join(HOME, ".claude", "projects")).map((f) => [f, scanClaude]),
3642
+ ...walk(path14.join(HOME, ".codex", "sessions")).map((f) => [f, scanCodex])
2792
3643
  ];
2793
- for (const [file, scan] of jobs) {
3644
+ for (const [file2, scan] of jobs) {
2794
3645
  let st;
2795
3646
  try {
2796
- st = fs14.statSync(file);
3647
+ st = fs16.statSync(file2);
2797
3648
  } catch {
2798
3649
  continue;
2799
3650
  }
2800
- const hit = cache2[file];
3651
+ const hit = cache2[file2];
2801
3652
  if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) {
2802
- next[file] = hit;
3653
+ next[file2] = hit;
2803
3654
  } else {
2804
- const r = await scan(file);
2805
- next[file] = { mtimeMs: st.mtimeMs, size: st.size, buckets: r.buckets, ...r.extra ? { codex: r.extra } : {} };
3655
+ const r = await scan(file2);
3656
+ next[file2] = { mtimeMs: st.mtimeMs, size: st.size, buckets: r.buckets, ...r.extra ? { codex: r.extra } : {} };
2806
3657
  }
2807
3658
  }
2808
3659
  saveCache(next);
@@ -2826,8 +3677,8 @@ async function scanAll() {
2826
3677
  const l = f.codex?.limits;
2827
3678
  if (l && (!codexLimits || l.ts > codexLimits.ts)) codexLimits = l;
2828
3679
  }
2829
- merge(await scanSqlite("opencode", path12.join(HOME, ".local", "share", "opencode", "opencode.db")));
2830
- merge(await scanSqlite("zcode", path12.join(HOME, ".zcode", "cli", "db", "db.sqlite")));
3680
+ merge(await scanSqlite("opencode", path14.join(HOME, ".local", "share", "opencode", "opencode.db")));
3681
+ merge(await scanSqlite("zcode", path14.join(HOME, ".zcode", "cli", "db", "db.sqlite")));
2831
3682
  return { buckets: merged, codexPlans, codexLimits };
2832
3683
  })().finally(() => {
2833
3684
  inflight = null;
@@ -3026,7 +3877,7 @@ var init_usage = __esm({
3026
3877
  { match: /haiku-5/, input: 0.1, output: 0.5, cacheRead: 0.01 },
3027
3878
  { match: /haiku/, input: 1, output: 5, cacheRead: 0.1 }
3028
3879
  ];
3029
- CACHE_FILE = path12.join(SAKURA_DIR, "usage-cache.json");
3880
+ CACHE_FILE = path14.join(SAKURA_DIR, "usage-cache.json");
3030
3881
  CACHE_VERSION = 2;
3031
3882
  inflight = null;
3032
3883
  RANGE_MS = { "24h": 864e5, "7d": 7 * 864e5, "30d": 30 * 864e5, all: Infinity };
@@ -3051,21 +3902,21 @@ var init_usage = __esm({
3051
3902
  });
3052
3903
 
3053
3904
  // src/runtime/limits.ts
3054
- import fs15 from "fs";
3055
- import path13 from "path";
3056
- import { execFile as execFile2 } from "child_process";
3057
- import { promisify as promisify2 } from "util";
3905
+ import fs17 from "fs";
3906
+ import path15 from "path";
3907
+ import { execFile as execFile3 } from "child_process";
3908
+ import { promisify as promisify3 } from "util";
3058
3909
  async function claudeToken() {
3059
3910
  let raw = null;
3060
3911
  if (process.platform === "darwin") {
3061
3912
  try {
3062
- raw = (await run2("security", ["find-generic-password", "-s", "Claude Code-credentials", "-w"], { timeout: 3e3 })).stdout;
3913
+ raw = (await run3("security", ["find-generic-password", "-s", "Claude Code-credentials", "-w"], { timeout: 3e3 })).stdout;
3063
3914
  } catch {
3064
3915
  }
3065
3916
  }
3066
3917
  if (!raw) {
3067
3918
  try {
3068
- raw = fs15.readFileSync(path13.join(HOME, ".claude", ".credentials.json"), "utf8");
3919
+ raw = fs17.readFileSync(path15.join(HOME, ".claude", ".credentials.json"), "utf8");
3069
3920
  } catch {
3070
3921
  return null;
3071
3922
  }
@@ -3105,13 +3956,13 @@ async function planLimits(agent) {
3105
3956
  }
3106
3957
  return [];
3107
3958
  }
3108
- var run2, CLAUDE_WINDOWS, cache;
3959
+ var run3, CLAUDE_WINDOWS, cache;
3109
3960
  var init_limits = __esm({
3110
3961
  "src/runtime/limits.ts"() {
3111
3962
  "use strict";
3112
3963
  init_util();
3113
3964
  init_usage();
3114
- run2 = promisify2(execFile2);
3965
+ run3 = promisify3(execFile3);
3115
3966
  CLAUDE_WINDOWS = [
3116
3967
  ["seven_day", "Weekly"],
3117
3968
  ["five_hour", "5 hours"],
@@ -3123,12 +3974,12 @@ var init_limits = __esm({
3123
3974
  });
3124
3975
 
3125
3976
  // src/runtime/models.ts
3126
- import fs16 from "fs";
3127
- import path14 from "path";
3977
+ import fs18 from "fs";
3978
+ import path16 from "path";
3128
3979
  import { execFileSync } from "child_process";
3129
3980
  function configuredClaudeModel() {
3130
3981
  try {
3131
- const m = JSON.parse(fs16.readFileSync(path14.join(HOME, ".claude", "settings.json"), "utf8")).model;
3982
+ const m = JSON.parse(fs18.readFileSync(path16.join(HOME, ".claude", "settings.json"), "utf8")).model;
3132
3983
  return typeof m === "string" && m ? m : void 0;
3133
3984
  } catch {
3134
3985
  return void 0;
@@ -3146,7 +3997,7 @@ async function claudeModels() {
3146
3997
  if (!res.ok) return claudeCache?.models ?? CLAUDE_ALIASES;
3147
3998
  const list4 = (await res.json())?.data ?? [];
3148
3999
  const seen = /* @__PURE__ */ new Set();
3149
- const models = list4.map((m) => {
4000
+ const models2 = list4.map((m) => {
3150
4001
  const family = /claude-([a-z]+)/.exec(m.id)?.[1] ?? "";
3151
4002
  const desc = FAMILY_DESC[family]?.[seen.has(family) ? 1 : 0];
3152
4003
  seen.add(family);
@@ -3159,20 +4010,29 @@ async function claudeModels() {
3159
4010
  const i = Object.values(FAMILY_DESC).findIndex(([latest]) => latest === m.desc);
3160
4011
  return i < 0 ? 99 : i;
3161
4012
  };
3162
- models.sort((a, b) => rank(a) - rank(b));
3163
- const out = [{ id: "", label: "Default", desc: defLabel }, ...models];
4013
+ models2.sort((a, b) => rank(a) - rank(b));
4014
+ const out = [{ id: "", label: "Default", desc: defLabel }, ...models2];
3164
4015
  claudeCache = { at: Date.now(), models: out };
3165
4016
  return out;
3166
4017
  } catch {
3167
4018
  return claudeCache?.models ?? CLAUDE_ALIASES;
3168
4019
  }
3169
4020
  }
4021
+ function codexCatalog() {
4022
+ try {
4023
+ const d = JSON.parse(fs18.readFileSync(path16.join(HOME, ".codex", "models_cache.json"), "utf8"));
4024
+ const list4 = Array.isArray(d?.models) ? d.models : [];
4025
+ return list4.filter((m) => typeof m?.slug === "string" && m.visibility !== "hide").sort((a, b) => (a.priority ?? 99) - (b.priority ?? 99)).map((m) => ({ id: m.slug, label: m.display_name || m.slug, desc: m.description || void 0 }));
4026
+ } catch {
4027
+ return [];
4028
+ }
4029
+ }
3170
4030
  function codexModels() {
3171
4031
  const out = [{ id: "", label: "Default" }];
3172
4032
  const seen = /* @__PURE__ */ new Set();
3173
4033
  let configured;
3174
4034
  try {
3175
- const cfg = fs16.readFileSync(path14.join(HOME, ".codex", "config.toml"), "utf8");
4035
+ const cfg = fs18.readFileSync(path16.join(HOME, ".codex", "config.toml"), "utf8");
3176
4036
  configured = /^\s*model\s*=\s*"([^"]+)"/m.exec(cfg)?.[1];
3177
4037
  for (const m of cfg.matchAll(/model\s*=\s*"([^"]+)"/g)) {
3178
4038
  const id = m[1];
@@ -3183,24 +4043,24 @@ function codexModels() {
3183
4043
  }
3184
4044
  } catch {
3185
4045
  }
3186
- for (const id of CODEX_CURATED) {
3187
- if (!seen.has(id)) {
3188
- seen.add(id);
3189
- out.push({ id, label: id });
4046
+ for (const m of codexCatalog()) {
4047
+ if (!seen.has(m.id)) {
4048
+ seen.add(m.id);
4049
+ out.push(m);
3190
4050
  }
3191
4051
  }
3192
4052
  return out;
3193
4053
  }
3194
- function opencodeModels() {
3195
- const out = [{ id: "", label: "Default" }];
3196
- const allowed = /* @__PURE__ */ new Set(["opencode"]);
4054
+ function opencodeCatalog() {
3197
4055
  try {
3198
- const auth = JSON.parse(
3199
- fs16.readFileSync(path14.join(HOME, ".local", "share", "opencode", "auth.json"), "utf8")
3200
- );
3201
- for (const k of Object.keys(auth)) allowed.add(k);
4056
+ return JSON.parse(fs18.readFileSync(path16.join(HOME, ".cache", "opencode", "models.json"), "utf8"));
3202
4057
  } catch {
4058
+ return {};
3203
4059
  }
4060
+ }
4061
+ function opencodeModels() {
4062
+ const out = [{ id: "", label: "Default" }];
4063
+ const catalog2 = opencodeCatalog();
3204
4064
  try {
3205
4065
  const raw = execFileSync(opencodeBin(), ["models"], { encoding: "utf8", timeout: 15e3 });
3206
4066
  for (const line of raw.split("\n").map((l) => l.trim()).filter(Boolean)) {
@@ -3208,18 +4068,21 @@ function opencodeModels() {
3208
4068
  if (slash < 0) continue;
3209
4069
  const provider = line.slice(0, slash);
3210
4070
  const model = line.slice(slash + 1);
3211
- if (!allowed.has(provider)) continue;
4071
+ const info2 = catalog2[provider]?.models?.[model];
4072
+ const cost = info2?.cost;
4073
+ const free = cost ? !cost.input && !cost.output : /(^|-)free$/i.test(model);
3212
4074
  out.push({
3213
4075
  id: line,
3214
4076
  // opencode wants the full provider/model string
3215
- label: model,
4077
+ label: info2?.name ?? model,
3216
4078
  group: OC_PROVIDER_LABELS[provider] ?? provider,
3217
- free: provider === "opencode" || /free/i.test(model)
4079
+ free
3218
4080
  });
3219
4081
  }
3220
4082
  } catch {
3221
4083
  }
3222
- return out;
4084
+ const rank = (g) => g === "OpenCode Go" ? 0 : g === "OpenCode Zen" ? 1 : 2;
4085
+ return [out[0], ...out.slice(1).sort((a, b) => rank(a.group) - rank(b.group))];
3223
4086
  }
3224
4087
  async function listModels(agent) {
3225
4088
  if (agent === "codex") return codexModels();
@@ -3235,7 +4098,7 @@ function zcodeModels() {
3235
4098
  function deepseekModels() {
3236
4099
  return [{ id: "", label: "Default" }];
3237
4100
  }
3238
- var CLAUDE_ALIASES, FAMILY_DESC, claudeCache, shortName, CODEX_CURATED, OC_PROVIDER_LABELS;
4101
+ var CLAUDE_ALIASES, FAMILY_DESC, claudeCache, shortName, OC_PROVIDER_LABELS;
3239
4102
  var init_models = __esm({
3240
4103
  "src/runtime/models.ts"() {
3241
4104
  "use strict";
@@ -3258,7 +4121,6 @@ var init_models = __esm({
3258
4121
  };
3259
4122
  claudeCache = null;
3260
4123
  shortName = (display) => display.replace(/^Claude\s+/i, "");
3261
- CODEX_CURATED = ["gpt-5.5-codex", "gpt-5.5", "gpt-5-codex", "gpt-5"];
3262
4124
  OC_PROVIDER_LABELS = {
3263
4125
  opencode: "OpenCode Zen",
3264
4126
  "opencode-go": "OpenCode Go",
@@ -3271,12 +4133,12 @@ var init_models = __esm({
3271
4133
  });
3272
4134
 
3273
4135
  // src/runtime/mentions.ts
3274
- import fs17 from "fs";
3275
- import path15 from "path";
3276
- function frontmatter(file) {
4136
+ import fs19 from "fs";
4137
+ import path17 from "path";
4138
+ function frontmatter(file2) {
3277
4139
  let text;
3278
4140
  try {
3279
- text = fs17.readFileSync(file, "utf8").slice(0, 4e3);
4141
+ text = fs19.readFileSync(file2, "utf8").slice(0, 4e3);
3280
4142
  } catch {
3281
4143
  return {};
3282
4144
  }
@@ -3298,31 +4160,31 @@ function frontmatter(file) {
3298
4160
  function skillsIn(dir, source, prefix = "") {
3299
4161
  let names;
3300
4162
  try {
3301
- names = fs17.readdirSync(path15.join(dir, "skills"));
4163
+ names = fs19.readdirSync(path17.join(dir, "skills"));
3302
4164
  } catch {
3303
4165
  return [];
3304
4166
  }
3305
4167
  return names.flatMap((n) => {
3306
- const file = path15.join(dir, "skills", n, "SKILL.md");
3307
- if (!fs17.existsSync(file)) return [];
3308
- const fm = frontmatter(file);
4168
+ const file2 = path17.join(dir, "skills", n, "SKILL.md");
4169
+ if (!fs19.existsSync(file2)) return [];
4170
+ const fm = frontmatter(file2);
3309
4171
  return [{ name: `${prefix}${fm.name || n}`, description: fm.description ?? "", source }];
3310
4172
  });
3311
4173
  }
3312
4174
  function commandsIn(dir, source, prefix = "") {
3313
- const root = path15.join(dir, "commands");
4175
+ const root = path17.join(dir, "commands");
3314
4176
  const out = [];
3315
4177
  const walk2 = (d, ns) => {
3316
4178
  let entries;
3317
4179
  try {
3318
- entries = fs17.readdirSync(d, { withFileTypes: true });
4180
+ entries = fs19.readdirSync(d, { withFileTypes: true });
3319
4181
  } catch {
3320
4182
  return;
3321
4183
  }
3322
4184
  for (const e of entries) {
3323
- if (e.isDirectory()) walk2(path15.join(d, e.name), [...ns, e.name]);
4185
+ if (e.isDirectory()) walk2(path17.join(d, e.name), [...ns, e.name]);
3324
4186
  else if (e.name.endsWith(".md")) {
3325
- const fm = frontmatter(path15.join(d, e.name));
4187
+ const fm = frontmatter(path17.join(d, e.name));
3326
4188
  const name = [...ns, e.name.slice(0, -3)].join(":");
3327
4189
  out.push({ name: `${prefix}${name}`, description: fm.description ?? "", source });
3328
4190
  }
@@ -3333,19 +4195,19 @@ function commandsIn(dir, source, prefix = "") {
3333
4195
  }
3334
4196
  function plugins() {
3335
4197
  try {
3336
- const file = path15.join(HOME, ".claude", "plugins", "installed_plugins.json");
3337
- const all2 = JSON.parse(fs17.readFileSync(file, "utf8")).plugins ?? {};
4198
+ const file2 = path17.join(HOME, ".claude", "plugins", "installed_plugins.json");
4199
+ const all2 = JSON.parse(fs19.readFileSync(file2, "utf8")).plugins ?? {};
3338
4200
  return Object.entries(all2).flatMap(([key, installs]) => {
3339
4201
  const dir = installs?.[0]?.installPath;
3340
- return dir && fs17.existsSync(dir) ? [{ name: key.split("@")[0], dir }] : [];
4202
+ return dir && fs19.existsSync(dir) ? [{ name: key.split("@")[0], dir }] : [];
3341
4203
  });
3342
4204
  } catch {
3343
4205
  return [];
3344
4206
  }
3345
4207
  }
3346
4208
  function mentions(cwd) {
3347
- const user = path15.join(HOME, ".claude");
3348
- const project = cwd ? path15.join(cwd, ".claude") : null;
4209
+ const user = path17.join(HOME, ".claude");
4210
+ const project = cwd ? path17.join(cwd, ".claude") : null;
3349
4211
  const plug = plugins();
3350
4212
  const skills = [
3351
4213
  ...project ? skillsIn(project, "project") : [],
@@ -3419,7 +4281,7 @@ var init_hub = __esm({
3419
4281
  function turnState(agent, sessionId) {
3420
4282
  return turns.get(sessionKey(agent, sessionId)) ?? null;
3421
4283
  }
3422
- async function runTurn(sessionId, agent, prompt, images, model, run5) {
4284
+ async function runTurn(sessionId, agent, prompt, images, model, run6, launched) {
3423
4285
  const key = sessionKey(agent, sessionId);
3424
4286
  const turn = { status: "running", startedAt: Date.now() };
3425
4287
  turns.set(key, turn);
@@ -3444,7 +4306,7 @@ async function runTurn(sessionId, agent, prompt, images, model, run5) {
3444
4306
  emitLive("");
3445
4307
  const baseIds = /* @__PURE__ */ new Set();
3446
4308
  try {
3447
- for (const m of await messages6(sessionId, agent)) baseIds.add(m.id);
4309
+ for (const m of await messages7(sessionId, agent)) baseIds.add(m.id);
3448
4310
  } catch {
3449
4311
  }
3450
4312
  let stdoutAcc = "";
@@ -3475,13 +4337,13 @@ async function runTurn(sessionId, agent, prompt, images, model, run5) {
3475
4337
  if (polling) return;
3476
4338
  polling = true;
3477
4339
  try {
3478
- pushFresh(await messages6(sessionId, agent));
4340
+ pushFresh(await messages7(sessionId, agent));
3479
4341
  } catch {
3480
4342
  } finally {
3481
4343
  polling = false;
3482
4344
  }
3483
4345
  }, POLL_MS);
3484
- const result = await chat(sessionId, prompt, agent, onData, images, model, run5);
4346
+ const result = await (launched ? launched(onData) : chat(sessionId, prompt, agent, onData, images, model, run6));
3485
4347
  clearInterval(timer);
3486
4348
  turn.status = result.ok ? "done" : "error";
3487
4349
  turn.finishedAt = Date.now();
@@ -3514,8 +4376,8 @@ var init_stream = __esm({
3514
4376
  });
3515
4377
 
3516
4378
  // src/runtime/presence.ts
3517
- import fs18 from "fs";
3518
- import path16 from "path";
4379
+ import fs20 from "fs";
4380
+ import path18 from "path";
3519
4381
  import { execFileSync as execFileSync2 } from "child_process";
3520
4382
  function alive(pid) {
3521
4383
  try {
@@ -3526,16 +4388,16 @@ function alive(pid) {
3526
4388
  }
3527
4389
  }
3528
4390
  function claudePresence(sessionId) {
3529
- const dir = path16.join(HOME, ".claude", "sessions");
4391
+ const dir = path18.join(HOME, ".claude", "sessions");
3530
4392
  let files = [];
3531
4393
  try {
3532
- files = fs18.readdirSync(dir).filter((f) => f.endsWith(".json"));
4394
+ files = fs20.readdirSync(dir).filter((f) => f.endsWith(".json"));
3533
4395
  } catch {
3534
4396
  return { open: false };
3535
4397
  }
3536
4398
  for (const f of files) {
3537
4399
  try {
3538
- const rec = JSON.parse(fs18.readFileSync(path16.join(dir, f), "utf8"));
4400
+ const rec = JSON.parse(fs20.readFileSync(path18.join(dir, f), "utf8"));
3539
4401
  if (rec?.sessionId !== sessionId || typeof rec.pid !== "number") continue;
3540
4402
  if (rec.kind && rec.kind !== "interactive") continue;
3541
4403
  if (!alive(rec.pid)) continue;
@@ -3584,8 +4446,8 @@ var init_presence = __esm({
3584
4446
  });
3585
4447
 
3586
4448
  // src/daemon/terminal.ts
3587
- import os7 from "os";
3588
- import { spawn as spawn9 } from "child_process";
4449
+ import os9 from "os";
4450
+ import { spawn as spawn10 } from "child_process";
3589
4451
  function cleanOutput(t, chunk) {
3590
4452
  let s = t.buf + chunk;
3591
4453
  s = s.replace(OSC, "").replace(CSI, "").replace(ESC2, "");
@@ -3603,8 +4465,8 @@ function defaultShell() {
3603
4465
  }
3604
4466
  function openTerminal(ws, opts) {
3605
4467
  const shell = defaultShell();
3606
- const child2 = spawn9(shell, ["-i"], {
3607
- cwd: opts?.cwd && opts.cwd.trim() ? opts.cwd : os7.homedir(),
4468
+ const child2 = spawn10(shell, ["-i"], {
4469
+ cwd: opts?.cwd && opts.cwd.trim() ? opts.cwd : os9.homedir(),
3608
4470
  env: {
3609
4471
  ...process.env,
3610
4472
  TERM: "dumb",
@@ -3635,7 +4497,7 @@ function openTerminal(ws, opts) {
3635
4497
  [shell error: ${e.message}]
3636
4498
  `));
3637
4499
  try {
3638
- ws.send(JSON.stringify({ type: "ready", shell, cwd: opts?.cwd || os7.homedir() }));
4500
+ ws.send(JSON.stringify({ type: "ready", shell, cwd: opts?.cwd || os9.homedir() }));
3639
4501
  } catch {
3640
4502
  }
3641
4503
  }
@@ -3670,43 +4532,78 @@ var init_terminal = __esm({
3670
4532
  });
3671
4533
 
3672
4534
  // src/daemon/sim.ts
3673
- import fs19 from "fs";
3674
- import os8 from "os";
3675
- import path17 from "path";
3676
- import { execFile as execFile3, spawn as spawn10 } from "child_process";
3677
- import { promisify as promisify3 } from "util";
4535
+ import fs21 from "fs";
4536
+ import os10 from "os";
4537
+ import path19 from "path";
4538
+ import { execFile as execFile4, spawn as spawn11 } from "child_process";
4539
+ import { promisify as promisify4 } from "util";
3678
4540
  import { randomBytes as randomBytes2 } from "crypto";
3679
4541
  async function devices() {
3680
- const { stdout } = await run3("xcrun", ["simctl", "list", "devices", "available", "-j"], { timeout: 1e4 });
4542
+ const { stdout } = await run4("xcrun", ["simctl", "list", "devices", "available", "-j"], { timeout: 1e4 });
3681
4543
  const out = [];
3682
4544
  for (const [runtime, list4] of Object.entries(JSON.parse(stdout).devices ?? {})) {
3683
4545
  const m = /SimRuntime\.(\w+)-([\d-]+)$/.exec(runtime);
3684
4546
  if (!m || m[1] !== "iOS") continue;
3685
- const os12 = `${m[1]} ${m[2].replace(/-/g, ".")}`;
3686
- for (const d of list4) out.push({ udid: d.udid, name: d.name, os: os12, booted: d.state === "Booted" });
4547
+ const os14 = `${m[1]} ${m[2].replace(/-/g, ".")}`;
4548
+ for (const d of list4) out.push({ udid: d.udid, name: d.name, os: os14, booted: d.state === "Booted" });
3687
4549
  }
3688
4550
  return out.sort((a, b) => Number(b.booted) - Number(a.booted) || b.os.localeCompare(a.os, void 0, { numeric: true }));
3689
4551
  }
3690
4552
  async function boot(udid) {
3691
- await run3("xcrun", ["simctl", "boot", udid], { timeout: 6e4 }).catch((e) => {
4553
+ await run4("xcrun", ["simctl", "boot", udid], { timeout: 6e4 }).catch((e) => {
3692
4554
  if (!/current state: Booted/.test(String(e?.stderr))) throw e;
3693
4555
  });
3694
- spawn10("open", ["-g", "-a", "Simulator"], { stdio: "ignore", detached: true }).unref();
4556
+ spawn11("open", ["-g", "-a", "Simulator"], { stdio: "ignore", detached: true }).unref();
4557
+ }
4558
+ function axePath() {
4559
+ if (foundAxe) return foundAxe;
4560
+ const dirs = [AXE_DIR, ...(process.env.PATH ?? "").split(":"), "/opt/homebrew/bin", "/usr/local/bin"];
4561
+ foundAxe = dirs.map((d) => path19.join(d, "axe")).find((p) => fs21.existsSync(p)) ?? null;
4562
+ return foundAxe;
4563
+ }
4564
+ function ensureAxe() {
4565
+ const have = axePath();
4566
+ if (have) return Promise.resolve(have);
4567
+ installing2 ??= (async () => {
4568
+ const stage = `${AXE_DIR}.${randomBytes2(4).toString("hex")}`;
4569
+ fs21.mkdirSync(stage, { recursive: true });
4570
+ try {
4571
+ const tgz = path19.join(stage, "axe.tar.gz");
4572
+ await run4("curl", ["-fsSL", "--retry", "2", "-o", tgz, AXE_URL], { timeout: 6e5 });
4573
+ await run4("tar", ["xzf", tgz, "-C", stage], { timeout: 6e4 });
4574
+ fs21.rmSync(tgz, { force: true });
4575
+ const { stdout } = await run4("find", [stage, "-name", "axe", "-type", "f", "-perm", "-u+x"], { timeout: 1e4 });
4576
+ const bin = stdout.split("\n").filter(Boolean).sort((a, b) => a.length - b.length)[0];
4577
+ if (!bin) throw new Error("no axe binary in the download");
4578
+ fs21.rmSync(AXE_DIR, { recursive: true, force: true });
4579
+ fs21.renameSync(path19.dirname(bin), AXE_DIR);
4580
+ return foundAxe = path19.join(AXE_DIR, "axe");
4581
+ } finally {
4582
+ fs21.rmSync(stage, { recursive: true, force: true });
4583
+ }
4584
+ })().finally(() => {
4585
+ installing2 = null;
4586
+ });
4587
+ return installing2;
3695
4588
  }
3696
4589
  async function axe(args) {
3697
- const bin = axePath();
3698
- if (!bin) throw new Error("Touch needs AXe on your Mac: brew install cameroncooke/axe/axe");
3699
- await run3(bin, args, { timeout: 15e3 });
4590
+ let bin;
4591
+ try {
4592
+ bin = await ensureAxe();
4593
+ } catch (e) {
4594
+ throw new Error(`Couldn\u2019t set up touch on your Mac (${e?.message ?? e}). Check its internet connection and try again.`);
4595
+ }
4596
+ await run4(bin, args, { timeout: 15e3 });
3700
4597
  }
3701
4598
  async function frame(udid, maxSide = 1e3) {
3702
- fs19.mkdirSync(TMP, { recursive: true });
3703
- const file = path17.join(TMP, `${randomBytes2(6).toString("hex")}.jpg`);
4599
+ fs21.mkdirSync(TMP, { recursive: true });
4600
+ const file2 = path19.join(TMP, `${randomBytes2(6).toString("hex")}.jpg`);
3704
4601
  try {
3705
- await run3("xcrun", ["simctl", "io", udid, "screenshot", "--type=jpeg", file], { timeout: 1e4 });
3706
- if (maxSide > 0) await run3("sips", ["-Z", String(maxSide), "-s", "formatOptions", "60", file], { timeout: 1e4 });
3707
- return fs19.readFileSync(file);
4602
+ await run4("xcrun", ["simctl", "io", udid, "screenshot", "--type=jpeg", file2], { timeout: 1e4 });
4603
+ if (maxSide > 0) await run4("sips", ["-Z", String(maxSide), "-s", "formatOptions", "60", file2], { timeout: 1e4 });
4604
+ return fs21.readFileSync(file2);
3708
4605
  } finally {
3709
- fs19.rmSync(file, { force: true });
4606
+ fs21.rmSync(file2, { force: true });
3710
4607
  }
3711
4608
  }
3712
4609
  function jpegSize(buf) {
@@ -3783,20 +4680,20 @@ async function input(udid, ev) {
3783
4680
  case "text":
3784
4681
  if (canTouch()) return axe(["type", ev.text, "--udid", udid]);
3785
4682
  await new Promise((resolve, reject) => {
3786
- const p = spawn10("xcrun", ["simctl", "pbcopy", udid]);
4683
+ const p = spawn11("xcrun", ["simctl", "pbcopy", udid]);
3787
4684
  p.on("error", reject);
3788
4685
  p.on("exit", (c) => c === 0 ? resolve() : reject(new Error("pbcopy failed")));
3789
4686
  p.stdin.end(ev.text);
3790
4687
  });
3791
4688
  return;
3792
4689
  case "openurl":
3793
- await run3("xcrun", ["simctl", "openurl", udid, ev.url], { timeout: 15e3 });
4690
+ await run4("xcrun", ["simctl", "openurl", udid, ev.url], { timeout: 15e3 });
3794
4691
  return;
3795
4692
  case "appearance":
3796
- await run3("xcrun", ["simctl", "ui", udid, "appearance", ev.mode], { timeout: 15e3 });
4693
+ await run4("xcrun", ["simctl", "ui", udid, "appearance", ev.mode], { timeout: 15e3 });
3797
4694
  return;
3798
4695
  case "shake":
3799
- await run3("xcrun", ["simctl", "spawn", udid, "notifyutil", "-p", "com.apple.UIKit.SimulatorShake"], { timeout: 15e3 });
4696
+ await run4("xcrun", ["simctl", "spawn", udid, "notifyutil", "-p", "com.apple.UIKit.SimulatorShake"], { timeout: 15e3 });
3800
4697
  return;
3801
4698
  }
3802
4699
  }
@@ -3851,7 +4748,11 @@ function viewer(udid, framed) {
3851
4748
  async function handle(req, res, route, url) {
3852
4749
  const udid = url.searchParams.get("udid") ?? "";
3853
4750
  try {
3854
- if (route === "/devices") return json(res, 200, { ok: true, devices: await devices(), touch: canTouch() });
4751
+ if (route === "/devices") {
4752
+ ensureAxe().catch(() => {
4753
+ });
4754
+ return json(res, 200, { ok: true, devices: await devices(), touch: canTouch() });
4755
+ }
3855
4756
  if (!/^[0-9A-F-]{36}$/i.test(udid)) return json(res, 400, { ok: false, error: "udid required" });
3856
4757
  if (route === "/view") {
3857
4758
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
@@ -3878,22 +4779,19 @@ async function handle(req, res, route, url) {
3878
4779
  json(res, 500, { ok: false, error: String(e?.stderr || e?.message || e).trim().split("\n").pop() });
3879
4780
  }
3880
4781
  }
3881
- var run3, TMP, axePath, canTouch, pointSize;
4782
+ var run4, TMP, AXE_VERSION, AXE_DIR, AXE_URL, foundAxe, installing2, canTouch, pointSize;
3882
4783
  var init_sim = __esm({
3883
4784
  "src/daemon/sim.ts"() {
3884
4785
  "use strict";
3885
- run3 = promisify3(execFile3);
3886
- TMP = path17.join(os8.tmpdir(), "sakura-sim");
3887
- axePath = /* @__PURE__ */ (() => {
3888
- let cached;
3889
- return () => {
3890
- if (cached !== void 0) return cached;
3891
- const dirs = [...(process.env.PATH ?? "").split(":"), "/opt/homebrew/bin", "/usr/local/bin"];
3892
- cached = dirs.map((d) => path17.join(d, "axe")).find((p) => fs19.existsSync(p)) ?? null;
3893
- return cached;
3894
- };
3895
- })();
3896
- canTouch = () => axePath() != null;
4786
+ init_config();
4787
+ run4 = promisify4(execFile4);
4788
+ TMP = path19.join(os10.tmpdir(), "sakura-sim");
4789
+ AXE_VERSION = "1.8.0";
4790
+ AXE_DIR = path19.join(SAKURA_DIR, "axe", AXE_VERSION);
4791
+ AXE_URL = `https://github.com/cameroncooke/AXe/releases/download/v${AXE_VERSION}/AXe-macOS-v${AXE_VERSION}-universal.tar.gz`;
4792
+ foundAxe = null;
4793
+ installing2 = null;
4794
+ canTouch = () => process.platform === "darwin";
3897
4795
  pointSize = /* @__PURE__ */ new Map();
3898
4796
  }
3899
4797
  });
@@ -3902,8 +4800,8 @@ var init_sim = __esm({
3902
4800
  import http from "http";
3903
4801
  import net from "net";
3904
4802
  import { randomBytes as randomBytes3 } from "crypto";
3905
- import { execFile as execFile4 } from "child_process";
3906
- import { promisify as promisify4 } from "util";
4803
+ import { execFile as execFile5 } from "child_process";
4804
+ import { promisify as promisify5 } from "util";
3907
4805
  function cookies(req) {
3908
4806
  const out = {};
3909
4807
  for (const part of String(req.headers.cookie ?? "").split(";")) {
@@ -3994,7 +4892,7 @@ async function control(req, res, url) {
3994
4892
  async function ports(daemonPort) {
3995
4893
  let out = "";
3996
4894
  try {
3997
- ({ stdout: out } = await run4("lsof", ["-nP", "-iTCP", "-sTCP:LISTEN", "-Fcn"], { timeout: 4e3 }));
4895
+ ({ stdout: out } = await run5("lsof", ["-nP", "-iTCP", "-sTCP:LISTEN", "-Fcn"], { timeout: 4e3 }));
3998
4896
  } catch (e) {
3999
4897
  out = e?.stdout ?? "";
4000
4898
  }
@@ -4012,13 +4910,13 @@ async function ports(daemonPort) {
4012
4910
  }
4013
4911
  return [...seen].map(([port2, process2]) => ({ port: port2, process: process2 })).sort((a, b) => a.port - b.port);
4014
4912
  }
4015
- var run4, KEY, KEY_COOKIE, PORT_COOKIE, authed, SYSTEM;
4913
+ var run5, KEY, KEY_COOKIE, PORT_COOKIE, authed, SYSTEM;
4016
4914
  var init_preview = __esm({
4017
4915
  "src/daemon/preview.ts"() {
4018
4916
  "use strict";
4019
4917
  init_auth();
4020
4918
  init_sim();
4021
- run4 = promisify4(execFile4);
4919
+ run5 = promisify5(execFile5);
4022
4920
  KEY = randomBytes3(24).toString("hex");
4023
4921
  KEY_COOKIE = "sakura_pk";
4024
4922
  PORT_COOKIE = "sakura_pp";
@@ -4029,22 +4927,22 @@ var init_preview = __esm({
4029
4927
 
4030
4928
  // src/daemon/server.ts
4031
4929
  import http2 from "http";
4032
- import fs20 from "fs";
4033
- import os9 from "os";
4930
+ import fs22 from "fs";
4931
+ import os11 from "os";
4034
4932
  import zlib2 from "zlib";
4035
- import path18 from "path";
4933
+ import path20 from "path";
4036
4934
  import { URL as URL2 } from "url";
4037
4935
  import { execFileSync as execFileSync3 } from "child_process";
4038
4936
  import { WebSocketServer } from "ws";
4039
- function add3(method, path22, handler) {
4937
+ function add3(method2, path24, handler) {
4040
4938
  const keys = [];
4041
4939
  const pattern = new RegExp(
4042
- "^" + path22.replace(/:[^/]+/g, (m) => {
4940
+ "^" + path24.replace(/:[^/]+/g, (m) => {
4043
4941
  keys.push(m.slice(1));
4044
4942
  return "([^/]+)";
4045
4943
  }) + "/?$"
4046
4944
  );
4047
- routes.push({ method, pattern, keys, handler });
4945
+ routes.push({ method: method2, pattern, keys, handler });
4048
4946
  }
4049
4947
  function runOptions(body) {
4050
4948
  return {
@@ -4069,8 +4967,8 @@ function sniffExt(buf) {
4069
4967
  return null;
4070
4968
  }
4071
4969
  function saveImages(sessionId, images) {
4072
- const dir = path18.join(os9.tmpdir(), "sakura-uploads", sessionId.slice(0, 24));
4073
- fs20.mkdirSync(dir, { recursive: true });
4970
+ const dir = path20.join(os11.tmpdir(), "sakura-uploads", sessionId.slice(0, 24));
4971
+ fs22.mkdirSync(dir, { recursive: true });
4074
4972
  const paths = [];
4075
4973
  images.forEach((img, i) => {
4076
4974
  const raw = String(img?.data ?? "");
@@ -4081,22 +4979,22 @@ function saveImages(sessionId, images) {
4081
4979
  }
4082
4980
  const bytes = Buffer.from(m[2], "base64");
4083
4981
  const ext = sniffExt(bytes) ?? EXT_BY_MIME[m[1]] ?? "png";
4084
- const base = img.name ? path18.parse(img.name).name.replace(/[^\w.\-]/g, "_") : "";
4982
+ const base = img.name ? path20.parse(img.name).name.replace(/[^\w.\-]/g, "_") : "";
4085
4983
  const stem = `${base || "image"}-${Date.now()}-${i + 1}`;
4086
- let file = path18.join(dir, `${stem}.${ext}`);
4087
- fs20.writeFileSync(file, bytes);
4984
+ let file2 = path20.join(dir, `${stem}.${ext}`);
4985
+ fs22.writeFileSync(file2, bytes);
4088
4986
  if (ext === "heic") {
4089
- const jpg = path18.join(dir, `${stem}.jpg`);
4987
+ const jpg = path20.join(dir, `${stem}.jpg`);
4090
4988
  try {
4091
- execFileSync3("sips", ["-s", "format", "jpeg", file, "--out", jpg], { stdio: "ignore" });
4092
- fs20.rmSync(file, { force: true });
4093
- file = jpg;
4989
+ execFileSync3("sips", ["-s", "format", "jpeg", file2, "--out", jpg], { stdio: "ignore" });
4990
+ fs22.rmSync(file2, { force: true });
4991
+ file2 = jpg;
4094
4992
  } catch {
4095
- log.info(`saveImages: HEIC\u2192JPEG conversion failed for ${file}; sending HEIC as-is`);
4993
+ log.info(`saveImages: HEIC\u2192JPEG conversion failed for ${file2}; sending HEIC as-is`);
4096
4994
  }
4097
4995
  }
4098
- log.info(`saveImages: wrote ${file} (${bytes.length} bytes)`);
4099
- paths.push(file);
4996
+ log.info(`saveImages: wrote ${file2} (${bytes.length} bytes)`);
4997
+ paths.push(file2);
4100
4998
  });
4101
4999
  return paths;
4102
5000
  }
@@ -4114,6 +5012,28 @@ function sendBytes(res, img) {
4114
5012
  });
4115
5013
  res.end(img.data);
4116
5014
  }
5015
+ async function startChat(agent, prepared, cwd, prompt, model, run6) {
5016
+ const fail2 = (id2) => (e) => log.warn(`new session ${id2} failed: ${e.message}`);
5017
+ if (agent === "claude" || agent === "acp") {
5018
+ void runTurn(prepared, agent, prompt, void 0, model, run6).catch(fail2(prepared));
5019
+ return prepared;
5020
+ }
5021
+ const before = new Set((await list({ agent, all: true })).map((x) => x.id));
5022
+ let sink = null;
5023
+ const early = [];
5024
+ const done = chatNew(agent, cwd, prompt, (c) => sink ? sink(c) : early.push(c), model);
5025
+ const id = await awaitNewSession(agent, cwd, before, done);
5026
+ if (!id) {
5027
+ const r = await done;
5028
+ throw new Error(r.error || `${agent} didn't start a session`);
5029
+ }
5030
+ void runTurn(id, agent, prompt, void 0, model, run6, (onData) => {
5031
+ sink = onData;
5032
+ early.splice(0).forEach(onData);
5033
+ return done;
5034
+ }).catch(fail2(id));
5035
+ return id;
5036
+ }
4117
5037
  function kvToObj(env) {
4118
5038
  if (!Array.isArray(env)) return void 0;
4119
5039
  const out = {};
@@ -4139,7 +5059,7 @@ function readBody(req) {
4139
5059
  req.on("error", () => resolve(null));
4140
5060
  });
4141
5061
  }
4142
- function send6(res, status2, payload) {
5062
+ function send7(res, status2, payload) {
4143
5063
  const body = JSON.stringify(payload);
4144
5064
  const headers = {
4145
5065
  "Content-Type": "application/json",
@@ -4159,35 +5079,35 @@ function send6(res, status2, payload) {
4159
5079
  }
4160
5080
  function createServer(port2) {
4161
5081
  const server = http2.createServer(async (req, res) => {
4162
- const method = req.method ?? "GET";
5082
+ const method2 = req.method ?? "GET";
4163
5083
  const url = new URL2(req.url ?? "/", `http://localhost:${port2}`);
4164
- if (method === "GET" && url.pathname === "/ping") {
4165
- return send6(res, 200, { pong: true, pid: process.pid });
5084
+ if (method2 === "GET" && url.pathname === "/ping") {
5085
+ return send7(res, 200, { pong: true, pid: process.pid });
4166
5086
  }
4167
5087
  if (url.pathname.startsWith("/__preview/")) return control(req, res, url);
4168
5088
  const previewPort = target(req, port2);
4169
5089
  if (previewPort) return proxy(req, res, previewPort);
4170
- if (method === "OPTIONS") return send6(res, 204, {});
5090
+ if (method2 === "OPTIONS") return send7(res, 204, {});
4171
5091
  const expected = getToken();
4172
5092
  const auth = req.headers["authorization"];
4173
5093
  const presented = typeof auth === "string" && auth.startsWith("Bearer ") ? auth.slice(7) : void 0;
4174
5094
  if (!expected || presented !== expected) {
4175
- return send6(res, 401, { error: "Unauthorized" });
5095
+ return send7(res, 401, { error: "Unauthorized" });
4176
5096
  }
4177
5097
  const route = routes.find(
4178
- (r) => r.method === method && r.pattern.test(url.pathname)
5098
+ (r) => r.method === method2 && r.pattern.test(url.pathname)
4179
5099
  );
4180
- if (!route) return send6(res, 404, { error: "Not found" });
5100
+ if (!route) return send7(res, 404, { error: "Not found" });
4181
5101
  const match = route.pattern.exec(url.pathname);
4182
5102
  const params = {};
4183
5103
  route.keys.forEach((k, i) => params[k] = decodeURIComponent(match[i + 1]));
4184
- const body = method === "GET" ? null : await readBody(req);
5104
+ const body = method2 === "GET" ? null : await readBody(req);
4185
5105
  try {
4186
5106
  const result = await route.handler({ req, res, url, params, body, port: port2 });
4187
- if (!res.headersSent) send6(res, 200, result);
5107
+ if (!res.headersSent) send7(res, 200, result);
4188
5108
  } catch (e) {
4189
5109
  log.error("handler error", e.message);
4190
- send6(res, 500, fail("nonzero", e.message));
5110
+ send7(res, 500, fail("nonzero", e.message));
4191
5111
  }
4192
5112
  });
4193
5113
  const wss = new WebSocketServer({ noServer: true });
@@ -4257,6 +5177,8 @@ var init_server = __esm({
4257
5177
  init_config();
4258
5178
  init_logger();
4259
5179
  init_sessions();
5180
+ init_acp();
5181
+ init_handoff();
4260
5182
  init_push();
4261
5183
  init_registry();
4262
5184
  init_projects();
@@ -4296,24 +5218,24 @@ var init_server = __esm({
4296
5218
  const reader = params.agent === "opencode" ? image : params.agent === "zcode" ? image2 : null;
4297
5219
  sendBytes(res, reader ? await reader(params.session, params.part) : null);
4298
5220
  });
4299
- UPLOADS_DIR = path18.join(os9.tmpdir(), "sakura-uploads");
5221
+ UPLOADS_DIR = path20.join(os11.tmpdir(), "sakura-uploads");
4300
5222
  add3("GET", "/uploads/:dir/:file", ({ res, params }) => {
4301
- const file = path18.resolve(UPLOADS_DIR, params.dir, params.file);
4302
- const ext = path18.extname(file).slice(1).toLowerCase();
5223
+ const file2 = path20.resolve(UPLOADS_DIR, params.dir, params.file);
5224
+ const ext = path20.extname(file2).slice(1).toLowerCase();
4303
5225
  const mime = Object.entries(EXT_BY_MIME).find(([, e]) => e === ext)?.[0];
4304
- const ok2 = file.startsWith(UPLOADS_DIR + path18.sep) && mime && fs20.existsSync(file);
4305
- sendBytes(res, ok2 ? { mediaType: mime, data: fs20.readFileSync(file) } : null);
5226
+ const ok2 = file2.startsWith(UPLOADS_DIR + path20.sep) && mime && fs22.existsSync(file2);
5227
+ sendBytes(res, ok2 ? { mediaType: mime, data: fs22.readFileSync(file2) } : null);
4306
5228
  });
4307
5229
  add3("GET", "/sessions", async ({ url }) => {
4308
5230
  const archived = url.searchParams.get("archived") === "true";
4309
5231
  const all2 = url.searchParams.get("all") === "true";
4310
5232
  const list4 = await list({ archived, all: all2 });
4311
- return { sessions: list4 };
5233
+ return { sessions: await tagSessions(list4) };
4312
5234
  });
4313
5235
  add3("GET", "/sessions/:id/messages", async ({ params, url }) => {
4314
5236
  const agent = url.searchParams.get("agent") || void 0;
4315
- const messages7 = await messages6(params.id, agent);
4316
- return { messages: messages7 };
5237
+ const messages8 = await messages7(params.id, agent);
5238
+ return { messages: messages8 };
4317
5239
  });
4318
5240
  add3("POST", "/sessions/:id/send", async ({ params, body }) => {
4319
5241
  const agent = body?.agent || await detectAgent(params.id);
@@ -4324,8 +5246,8 @@ var init_server = __esm({
4324
5246
  const imagePaths = incoming.length ? saveImages(params.id, incoming) : [];
4325
5247
  if (imagePaths.length) log.info(`send: attached ${imagePaths.length} image(s) to ${agent} prompt`);
4326
5248
  const model = body?.model ? String(body.model) : void 0;
4327
- const run5 = runOptions(body);
4328
- const r = await runTurn(params.id, agent, message, imagePaths, model, run5);
5249
+ const run6 = runOptions(body);
5250
+ const r = await runTurn(params.id, agent, message, imagePaths, model, run6);
4329
5251
  return { ok: r.ok, error: r.error };
4330
5252
  });
4331
5253
  add3("GET", "/sessions/:id/status", async ({ params, url }) => {
@@ -4371,7 +5293,7 @@ var init_server = __esm({
4371
5293
  case "logs": {
4372
5294
  let logs2 = "";
4373
5295
  try {
4374
- const lines2 = fs20.readFileSync(LOG_PATH, "utf8").split("\n");
5296
+ const lines2 = fs22.readFileSync(LOG_PATH, "utf8").split("\n");
4375
5297
  logs2 = lines2.slice(-200).join("\n");
4376
5298
  } catch {
4377
5299
  }
@@ -4428,13 +5350,37 @@ var init_server = __esm({
4428
5350
  if (!prompt) return fail("bad_request", "prompt required");
4429
5351
  const agent = body?.agent || "claude";
4430
5352
  const model = body?.model ? String(body.model) : void 0;
4431
- const run5 = runOptions(body);
5353
+ const run6 = runOptions(body);
4432
5354
  try {
4433
- const s = await prepareSession(params.id, agent, !!body?.worktree);
4434
- void runTurn(s.sessionId, agent, prompt, void 0, model, run5).catch(
4435
- (e) => log.warn(`project session ${s.sessionId} failed: ${e.message}`)
4436
- );
4437
- return ok({ ...s, agent });
5355
+ const s = await prepareSession(params.id, agent, !!body?.worktree, body?.acp ? String(body.acp) : void 0);
5356
+ return ok({ ...s, sessionId: await startChat(agent, s.sessionId, s.cwd, prompt, model, run6), agent });
5357
+ } catch (e) {
5358
+ return fail("bad_request", e.message);
5359
+ }
5360
+ });
5361
+ add3("POST", "/sakura/projects/:id/handoff", async ({ params, body }) => {
5362
+ const from = (Array.isArray(body?.from) ? body.from : []).filter((x) => x?.id && x?.agent).map((x) => ({ id: String(x.id), agent: x.agent }));
5363
+ if (!from.length) return fail("bad_request", "pick at least one conversation");
5364
+ const agent = body?.agent || "claude";
5365
+ const model = body?.model ? String(body.model) : void 0;
5366
+ try {
5367
+ const prompt = await handoffPrompt(from, body?.prompt ? String(body.prompt) : void 0);
5368
+ const s = await prepareSession(params.id, agent, false, body?.acp ? String(body.acp) : void 0);
5369
+ const sessionId = await startChat(agent, s.sessionId, s.cwd, prompt, model, runOptions(body));
5370
+ rename(sessionId, await handoffTitle(from));
5371
+ return ok({ ...s, sessionId, agent });
5372
+ } catch (e) {
5373
+ return fail("bad_request", e.message);
5374
+ }
5375
+ });
5376
+ add3("POST", "/sakura/chats", async ({ body }) => {
5377
+ const prompt = String(body?.prompt ?? "").trim();
5378
+ if (!prompt) return fail("bad_request", "prompt required");
5379
+ const agent = body?.agent || "claude";
5380
+ const model = body?.model ? String(body.model) : void 0;
5381
+ try {
5382
+ const s = await prepareScratch(agent, body?.acp ? String(body.acp) : void 0);
5383
+ return ok({ ...s, sessionId: await startChat(agent, s.sessionId, s.cwd, prompt, model, runOptions(body)), agent });
4438
5384
  } catch (e) {
4439
5385
  return fail("bad_request", e.message);
4440
5386
  }
@@ -4446,7 +5392,11 @@ var init_server = __esm({
4446
5392
  return ok(await chatContext(id, agent));
4447
5393
  });
4448
5394
  add3("GET", "/sakura/preview/ports", async ({ port: port2 }) => ok(await ports(port2)));
4449
- add3("GET", "/sakura/sim/devices", async () => ok({ devices: await devices(), touch: canTouch() }));
5395
+ add3("GET", "/sakura/sim/devices", async () => {
5396
+ ensureAxe().catch(() => {
5397
+ });
5398
+ return ok({ devices: await devices(), touch: canTouch() });
5399
+ });
4450
5400
  add3("POST", "/sakura/sim/:udid/boot", async ({ params }) => {
4451
5401
  await boot(params.udid);
4452
5402
  return ok();
@@ -4483,9 +5433,22 @@ var init_server = __esm({
4483
5433
  });
4484
5434
  add3("GET", "/sakura/models", async ({ url }) => {
4485
5435
  const agent = url.searchParams.get("agent") || "claude";
5436
+ if (agent === "acp") return ok(models(url.searchParams.get("acp") ?? ""));
4486
5437
  return ok(await listModels(agent));
4487
5438
  });
4488
- add3("GET", "/sakura/machine", () => ok({ name: loadConfig().machineName || os9.hostname() }));
5439
+ add3("GET", "/sakura/acp/registry", async ({ url }) => {
5440
+ if (url.searchParams.get("refresh") === "1") await registry(true);
5441
+ return ok(await catalog());
5442
+ });
5443
+ add3("POST", "/sakura/acp/agents/:id", async ({ params, body }) => {
5444
+ try {
5445
+ return ok(await setEnabled(params.id, body?.enabled !== false));
5446
+ } catch (e) {
5447
+ return fail("bad_request", e.message);
5448
+ }
5449
+ });
5450
+ add3("GET", "/sakura/agents", () => ok(runnableAgents()));
5451
+ add3("GET", "/sakura/machine", () => ok({ name: loadConfig().machineName || os11.hostname() }));
4489
5452
  add3("GET", "/sakura/mentions", ({ url }) => ok(mentions(url.searchParams.get("cwd") ?? void 0)));
4490
5453
  add3("POST", "/sakura/push-token", ({ body }) => {
4491
5454
  let b = body;
@@ -4531,8 +5494,8 @@ var init_server = __esm({
4531
5494
  const agent = body?.agent || await detectAgent(params.id);
4532
5495
  if (!agent) return fail("nonzero", "unknown agent for session");
4533
5496
  const model = body?.model ? String(body.model) : void 0;
4534
- const run5 = runOptions(body);
4535
- const r = await runTurn(params.id, agent, String(body?.prompt ?? ""), void 0, model, run5);
5497
+ const run6 = runOptions(body);
5498
+ const r = await runTurn(params.id, agent, String(body?.prompt ?? ""), void 0, model, run6);
4536
5499
  return r.ok ? ok({ ok: true }) : fail("nonzero", r.error ?? "chat failed");
4537
5500
  });
4538
5501
  add3(
@@ -4619,7 +5582,7 @@ var init_server = __esm({
4619
5582
  const p = url.searchParams.get("path");
4620
5583
  if (!p) return fail("nonzero", "path required");
4621
5584
  try {
4622
- return ok(read2(p));
5585
+ return ok(read3(p));
4623
5586
  } catch (e) {
4624
5587
  return fail("nonzero", e.message);
4625
5588
  }
@@ -4627,7 +5590,7 @@ var init_server = __esm({
4627
5590
  add3("POST", "/sakura/fs/write", ({ body }) => {
4628
5591
  if (!body?.path) return fail("nonzero", "path required");
4629
5592
  try {
4630
- return ok(write3(body.path, String(body.content ?? "")));
5593
+ return ok(write4(body.path, String(body.content ?? "")));
4631
5594
  } catch (e) {
4632
5595
  return fail("nonzero", e.message);
4633
5596
  }
@@ -4640,7 +5603,7 @@ var init_server = __esm({
4640
5603
  return fail("nonzero", e.message);
4641
5604
  }
4642
5605
  });
4643
- add3("GET", "/tailscale/health", () => installed());
5606
+ add3("GET", "/tailscale/health", () => installed2());
4644
5607
  add3("GET", "/tailscale/status", ({ port: port2 }) => status(port2));
4645
5608
  add3("POST", "/tailscale/up", () => up());
4646
5609
  add3("POST", "/tailscale/down", () => down());
@@ -4652,24 +5615,24 @@ var init_server = __esm({
4652
5615
 
4653
5616
  // src/daemon/tsnet.ts
4654
5617
  import crypto from "crypto";
4655
- import fs21 from "fs";
4656
- import path19 from "path";
5618
+ import fs23 from "fs";
5619
+ import path21 from "path";
4657
5620
  import { fileURLToPath } from "url";
4658
- import { spawn as spawn11 } from "child_process";
5621
+ import { spawn as spawn12 } from "child_process";
4659
5622
  function resolveBinary() {
4660
5623
  const envBin = process.env.SAKURA_TSNET_BIN;
4661
- if (envBin && fs21.existsSync(envBin)) return envBin;
4662
- const here = path19.dirname(fileURLToPath(import.meta.url));
5624
+ if (envBin && fs23.existsSync(envBin)) return envBin;
5625
+ const here = path21.dirname(fileURLToPath(import.meta.url));
4663
5626
  const name = process.platform === "win32" ? "sakura-tsnet.exe" : "sakura-tsnet";
4664
5627
  const candidates = [
4665
- path19.join(here, "..", "bin", name),
5628
+ path21.join(here, "..", "bin", name),
4666
5629
  // package/bin (postinstall download / build-sidecar.sh)
4667
- path19.join(here, "bin", name),
4668
- path19.join(process.cwd(), "bin", name),
4669
- path19.join(SAKURA_DIR, name)
5630
+ path21.join(here, "bin", name),
5631
+ path21.join(process.cwd(), "bin", name),
5632
+ path21.join(SAKURA_DIR, name)
4670
5633
  // user-dropped
4671
5634
  ];
4672
- return candidates.find((p) => fs21.existsSync(p)) ?? null;
5635
+ return candidates.find((p) => fs23.existsSync(p)) ?? null;
4673
5636
  }
4674
5637
  function startTsnet(port2) {
4675
5638
  const cfg = loadConfig();
@@ -4685,22 +5648,22 @@ function startTsnet(port2) {
4685
5648
  }
4686
5649
  stopping = false;
4687
5650
  resetStateIfKeyChanged(ts.authKey);
4688
- const fresh = !fs21.existsSync(path19.join(STATE_DIR, "tailscaled.state")) && !fs21.existsSync(JOINED_MARK);
5651
+ const fresh = !fs23.existsSync(path21.join(STATE_DIR, "tailscaled.state")) && !fs23.existsSync(JOINED_MARK);
4689
5652
  spawnSidecar(bin, ts.controlUrl, ts.authKey, ts.hostname || cfg.machineName, port2, fresh);
4690
5653
  }
4691
5654
  function resetStateIfKeyChanged(authKey) {
4692
5655
  const hash = crypto.createHash("sha256").update(authKey).digest("hex");
4693
5656
  let prev = null;
4694
5657
  try {
4695
- prev = fs21.readFileSync(KEY_MARK, "utf8").trim();
5658
+ prev = fs23.readFileSync(KEY_MARK, "utf8").trim();
4696
5659
  } catch {
4697
5660
  }
4698
5661
  if (prev && prev !== hash) {
4699
5662
  log.info("tailnet key changed \u2014 re-registering this Mac on the new key");
4700
- fs21.rmSync(STATE_DIR, { recursive: true, force: true });
5663
+ fs23.rmSync(STATE_DIR, { recursive: true, force: true });
4701
5664
  }
4702
- fs21.mkdirSync(STATE_DIR, { recursive: true });
4703
- fs21.writeFileSync(KEY_MARK, hash);
5665
+ fs23.mkdirSync(STATE_DIR, { recursive: true });
5666
+ fs23.writeFileSync(KEY_MARK, hash);
4704
5667
  }
4705
5668
  function spawnSidecar(bin, controlUrl, authKey, hostname2, port2, forceLogin) {
4706
5669
  const env = {
@@ -4713,8 +5676,8 @@ function spawnSidecar(bin, controlUrl, authKey, hostname2, port2, forceLogin) {
4713
5676
  SAKURA_TS_PORT: String(port2)
4714
5677
  };
4715
5678
  if (forceLogin) env.TSNET_FORCE_LOGIN = "1";
4716
- log.info(`starting embedded Tailscale sidecar (${path19.basename(bin)})${forceLogin ? " with a forced login" : ""}`);
4717
- const c = spawn11(bin, [], { stdio: ["ignore", "pipe", "pipe"], env });
5679
+ log.info(`starting embedded Tailscale sidecar (${path21.basename(bin)})${forceLogin ? " with a forced login" : ""}`);
5680
+ const c = spawn12(bin, [], { stdio: ["ignore", "pipe", "pipe"], env });
4718
5681
  child = c;
4719
5682
  let joinFailed = false;
4720
5683
  const pipe = (buf) => buf.toString().split("\n").filter(Boolean).forEach((line) => {
@@ -4722,7 +5685,7 @@ function spawnSidecar(bin, controlUrl, authKey, hostname2, port2, forceLogin) {
4722
5685
  if (line.includes("failed to join tailnet")) joinFailed = true;
4723
5686
  if (line.includes("on tailnet as")) {
4724
5687
  try {
4725
- fs21.writeFileSync(JOINED_MARK, (/* @__PURE__ */ new Date()).toISOString());
5688
+ fs23.writeFileSync(JOINED_MARK, (/* @__PURE__ */ new Date()).toISOString());
4726
5689
  } catch {
4727
5690
  }
4728
5691
  }
@@ -4732,7 +5695,7 @@ function spawnSidecar(bin, controlUrl, authKey, hostname2, port2, forceLogin) {
4732
5695
  c.on("exit", (code) => {
4733
5696
  child = null;
4734
5697
  if (stopping) return;
4735
- const force = forceLogin || joinFailed && !fs21.existsSync(JOINED_MARK);
5698
+ const force = forceLogin || joinFailed && !fs23.existsSync(JOINED_MARK);
4736
5699
  log.warn(`tsnet sidecar exited (code ${code}); restarting in 5s`);
4737
5700
  restartTimer = setTimeout(() => {
4738
5701
  if (!stopping) spawnSidecar(bin, controlUrl, authKey, hostname2, port2, force);
@@ -4753,7 +5716,7 @@ function stopTsnet() {
4753
5716
  child = null;
4754
5717
  }
4755
5718
  try {
4756
- fs21.rmSync(TSNET_PATH, { force: true });
5719
+ fs23.rmSync(TSNET_PATH, { force: true });
4757
5720
  } catch {
4758
5721
  }
4759
5722
  }
@@ -4766,15 +5729,15 @@ var init_tsnet = __esm({
4766
5729
  child = null;
4767
5730
  stopping = false;
4768
5731
  restartTimer = null;
4769
- STATE_DIR = path19.join(SAKURA_DIR, "tsnet-state");
4770
- KEY_MARK = path19.join(STATE_DIR, "joined-with");
4771
- JOINED_MARK = path19.join(STATE_DIR, "joined");
5732
+ STATE_DIR = path21.join(SAKURA_DIR, "tsnet-state");
5733
+ KEY_MARK = path21.join(STATE_DIR, "joined-with");
5734
+ JOINED_MARK = path21.join(STATE_DIR, "joined");
4772
5735
  }
4773
5736
  });
4774
5737
 
4775
5738
  // src/daemon/manager.ts
4776
- import fs22 from "fs";
4777
- import { spawn as spawn12 } from "child_process";
5739
+ import fs24 from "fs";
5740
+ import { spawn as spawn13 } from "child_process";
4778
5741
  async function ensureTailnetProvisioned() {
4779
5742
  const serverToken = getServerToken();
4780
5743
  if (!serverToken) return;
@@ -4796,7 +5759,7 @@ async function ensureTailnetProvisioned() {
4796
5759
  }
4797
5760
  function readDaemonInfo() {
4798
5761
  try {
4799
- return JSON.parse(fs22.readFileSync(DAEMON_PATH, "utf8"));
5762
+ return JSON.parse(fs24.readFileSync(DAEMON_PATH, "utf8"));
4800
5763
  } catch {
4801
5764
  return null;
4802
5765
  }
@@ -4813,8 +5776,8 @@ function running() {
4813
5776
  const info2 = readDaemonInfo();
4814
5777
  if (info2 && pidAlive(info2.pid)) return info2;
4815
5778
  if (info2) {
4816
- fs22.rmSync(DAEMON_PATH, { force: true });
4817
- fs22.rmSync(PID_PATH, { force: true });
5779
+ fs24.rmSync(DAEMON_PATH, { force: true });
5780
+ fs24.rmSync(PID_PATH, { force: true });
4818
5781
  }
4819
5782
  return null;
4820
5783
  }
@@ -4837,8 +5800,8 @@ async function runServer(version) {
4837
5800
  url: `http://${host}:${port2}`,
4838
5801
  startedAt: Date.now()
4839
5802
  };
4840
- fs22.writeFileSync(DAEMON_PATH, JSON.stringify(info2, null, 2));
4841
- fs22.writeFileSync(PID_PATH, String(process.pid));
5803
+ fs24.writeFileSync(DAEMON_PATH, JSON.stringify(info2, null, 2));
5804
+ fs24.writeFileSync(PID_PATH, String(process.pid));
4842
5805
  await ensureTailnetProvisioned();
4843
5806
  startTsnet(port2);
4844
5807
  const tailnet = await discoverBaseUrl(port2).catch(() => null);
@@ -4849,8 +5812,8 @@ async function runServer(version) {
4849
5812
  log.info("shutting down");
4850
5813
  stopTsnet();
4851
5814
  server.close();
4852
- fs22.rmSync(DAEMON_PATH, { force: true });
4853
- fs22.rmSync(PID_PATH, { force: true });
5815
+ fs24.rmSync(DAEMON_PATH, { force: true });
5816
+ fs24.rmSync(PID_PATH, { force: true });
4854
5817
  process.exit(0);
4855
5818
  };
4856
5819
  process.on("SIGINT", shutdown);
@@ -4861,9 +5824,9 @@ function start() {
4861
5824
  if (existing) return existing;
4862
5825
  ensureSakuraDirs();
4863
5826
  const entry = process.argv[1] ?? "";
4864
- const out = fs22.openSync(LOG_PATH, "a");
4865
- const err = fs22.openSync(LOG_PATH, "a");
4866
- const child2 = spawn12(process.execPath, [entry, "__run-daemon"], {
5827
+ const out = fs24.openSync(LOG_PATH, "a");
5828
+ const err = fs24.openSync(LOG_PATH, "a");
5829
+ const child2 = spawn13(process.execPath, [entry, "__run-daemon"], {
4867
5830
  detached: true,
4868
5831
  stdio: ["ignore", out, err],
4869
5832
  env: process.env
@@ -4884,8 +5847,8 @@ function stop() {
4884
5847
  process.kill(info2.pid, "SIGTERM");
4885
5848
  } catch {
4886
5849
  }
4887
- fs22.rmSync(DAEMON_PATH, { force: true });
4888
- fs22.rmSync(PID_PATH, { force: true });
5850
+ fs24.rmSync(DAEMON_PATH, { force: true });
5851
+ fs24.rmSync(PID_PATH, { force: true });
4889
5852
  return true;
4890
5853
  }
4891
5854
  function restart() {
@@ -4895,7 +5858,7 @@ function restart() {
4895
5858
  }
4896
5859
  function logs(lines2 = 50) {
4897
5860
  try {
4898
- const all2 = fs22.readFileSync(LOG_PATH, "utf8").split("\n");
5861
+ const all2 = fs24.readFileSync(LOG_PATH, "utf8").split("\n");
4899
5862
  return all2.slice(-lines2).join("\n");
4900
5863
  } catch {
4901
5864
  return "";
@@ -4915,18 +5878,18 @@ var init_manager = __esm({
4915
5878
  });
4916
5879
 
4917
5880
  // src/pairing.ts
4918
- import os10 from "os";
5881
+ import os12 from "os";
4919
5882
  import qrcode from "qrcode-terminal";
4920
- import fs23 from "fs";
5883
+ import fs25 from "fs";
4921
5884
  function recentTsnetLog(max = 6) {
4922
5885
  let text = "";
4923
5886
  try {
4924
- const fd = fs23.openSync(LOG_PATH, "r");
4925
- const size = fs23.fstatSync(fd).size;
5887
+ const fd = fs25.openSync(LOG_PATH, "r");
5888
+ const size = fs25.fstatSync(fd).size;
4926
5889
  const len = Math.min(size, 64 * 1024);
4927
5890
  const buf = Buffer.alloc(len);
4928
- fs23.readSync(fd, buf, 0, len, size - len);
4929
- fs23.closeSync(fd);
5891
+ fs25.readSync(fd, buf, 0, len, size - len);
5892
+ fs25.closeSync(fd);
4930
5893
  text = buf.toString("utf8");
4931
5894
  } catch {
4932
5895
  return [];
@@ -4998,7 +5961,7 @@ function renderQr(deepLink) {
4998
5961
  });
4999
5962
  }
5000
5963
  function localIp() {
5001
- const nets = os10.networkInterfaces();
5964
+ const nets = os12.networkInterfaces();
5002
5965
  for (const name of Object.keys(nets)) {
5003
5966
  for (const net2 of nets[name] ?? []) {
5004
5967
  if (net2.family === "IPv4" && !net2.internal) return net2.address;
@@ -5087,7 +6050,7 @@ var init_pair = __esm({
5087
6050
  import { Command } from "commander";
5088
6051
 
5089
6052
  // src/version.ts
5090
- var VERSION = "0.0.16";
6053
+ var VERSION = "0.0.17";
5091
6054
 
5092
6055
  // src/index.ts
5093
6056
  init_config();
@@ -5137,9 +6100,9 @@ function registerAuth(program) {
5137
6100
  });
5138
6101
  program.command("whoami").description("Show the current login + token status").option("--json", "output as JSON").action((opts) => {
5139
6102
  const auth = loadAuth();
5140
- const has = !!getToken();
5141
- if (opts.json) return printJson({ loggedIn: has, login: auth.login, machineName: auth.machineName });
5142
- if (!has) return warn("Not signed in. Run `sakuraai login`.");
6103
+ const has2 = !!getToken();
6104
+ if (opts.json) return printJson({ loggedIn: has2, login: auth.login, machineName: auth.machineName });
6105
+ if (!has2) return warn("Not signed in. Run `sakuraai login`.");
5143
6106
  info(`Signed in as ${auth.login ?? "unknown"} on "${auth.machineName ?? "unknown"}".`);
5144
6107
  });
5145
6108
  }
@@ -5205,7 +6168,7 @@ function registerRuntime(program, version) {
5205
6168
  // src/commands/session.ts
5206
6169
  init_sessions();
5207
6170
  init_output();
5208
- import fs24 from "fs";
6171
+ import fs26 from "fs";
5209
6172
  function resolveSessionId(arg) {
5210
6173
  const id = arg || process.env.SAKURA_SESSION_ID;
5211
6174
  if (!id) die("Provide a sessionId (positional or via SAKURA_SESSION_ID).");
@@ -5214,7 +6177,7 @@ function resolveSessionId(arg) {
5214
6177
  async function resolvePrompt(positional, opts) {
5215
6178
  if (positional) return positional;
5216
6179
  if (opts.prompt) return opts.prompt;
5217
- if (opts.promptFile) return fs24.readFileSync(opts.promptFile, "utf8");
6180
+ if (opts.promptFile) return fs26.readFileSync(opts.promptFile, "utf8");
5218
6181
  if (!process.stdin.isTTY) {
5219
6182
  const chunks = [];
5220
6183
  for await (const c of process.stdin) chunks.push(c);
@@ -5245,7 +6208,7 @@ function registerSession(program) {
5245
6208
  const id = resolveSessionId(sessionId);
5246
6209
  const meta = await show(id);
5247
6210
  if (!meta) die(`Session not found: ${id}`);
5248
- const msgs = await messages6(id, meta.agent);
6211
+ const msgs = await messages7(id, meta.agent);
5249
6212
  const enriched = { ...meta, historyCount: msgs.length };
5250
6213
  if (opts.json) return printJson(enriched);
5251
6214
  info(`ID: ${meta.id}`);
@@ -5529,25 +6492,25 @@ init_pair();
5529
6492
 
5530
6493
  // src/commands/welcome.ts
5531
6494
  init_config();
5532
- import fs25 from "fs";
5533
- import path20 from "path";
6495
+ import fs27 from "fs";
6496
+ import path22 from "path";
5534
6497
  import { fileURLToPath as fileURLToPath2 } from "url";
5535
- import { spawn as spawn13 } from "child_process";
5536
- var WELCOMED_MARKER = path20.join(SAKURA_DIR, ".welcomed");
6498
+ import { spawn as spawn14 } from "child_process";
6499
+ var WELCOMED_MARKER = path22.join(SAKURA_DIR, ".welcomed");
5537
6500
  function resolveBinary2() {
5538
6501
  const envBin = process.env.SAKURA_ONBOARD_BIN;
5539
- if (envBin && fs25.existsSync(envBin)) return envBin;
5540
- const here = path20.dirname(fileURLToPath2(import.meta.url));
6502
+ if (envBin && fs27.existsSync(envBin)) return envBin;
6503
+ const here = path22.dirname(fileURLToPath2(import.meta.url));
5541
6504
  const name = process.platform === "win32" ? "sakura-onboard.exe" : "sakura-onboard";
5542
6505
  const candidates = [
5543
- path20.join(here, "..", "bin", name),
6506
+ path22.join(here, "..", "bin", name),
5544
6507
  // package/bin (postinstall download)
5545
- path20.join(here, "bin", name),
5546
- path20.join(process.cwd(), "bin", name),
5547
- path20.join(SAKURA_DIR, name)
6508
+ path22.join(here, "bin", name),
6509
+ path22.join(process.cwd(), "bin", name),
6510
+ path22.join(SAKURA_DIR, name)
5548
6511
  // user-dropped
5549
6512
  ];
5550
- return candidates.find((p) => fs25.existsSync(p)) ?? null;
6513
+ return candidates.find((p) => fs27.existsSync(p)) ?? null;
5551
6514
  }
5552
6515
  function showWelcome() {
5553
6516
  return new Promise((resolve) => {
@@ -5556,7 +6519,7 @@ function showWelcome() {
5556
6519
  printFallback();
5557
6520
  return resolve();
5558
6521
  }
5559
- const child2 = spawn13(bin, [], { stdio: "inherit" });
6522
+ const child2 = spawn14(bin, [], { stdio: "inherit" });
5560
6523
  child2.on("error", () => {
5561
6524
  printFallback();
5562
6525
  resolve();
@@ -5565,10 +6528,10 @@ function showWelcome() {
5565
6528
  });
5566
6529
  }
5567
6530
  async function maybeFirstRunWelcome() {
5568
- if (fs25.existsSync(WELCOMED_MARKER)) return;
6531
+ if (fs27.existsSync(WELCOMED_MARKER)) return;
5569
6532
  if (!process.stdout.isTTY || !process.stdin.isTTY) return;
5570
6533
  try {
5571
- fs25.writeFileSync(WELCOMED_MARKER, (/* @__PURE__ */ new Date()).toISOString());
6534
+ fs27.writeFileSync(WELCOMED_MARKER, (/* @__PURE__ */ new Date()).toISOString());
5572
6535
  } catch {
5573
6536
  }
5574
6537
  await showWelcome();
@@ -5606,9 +6569,9 @@ function registerWelcome(program) {
5606
6569
  }
5607
6570
 
5608
6571
  // src/commands/app.ts
5609
- import fs26 from "fs";
5610
- import os11 from "os";
5611
- import path21 from "path";
6572
+ import fs28 from "fs";
6573
+ import os13 from "os";
6574
+ import path23 from "path";
5612
6575
  import { execFileSync as execFileSync4 } from "child_process";
5613
6576
  init_output();
5614
6577
  var APP_PATH = "/Applications/Sakura.app";
@@ -5619,13 +6582,13 @@ function dmgUrl() {
5619
6582
  async function download(url, dest) {
5620
6583
  const res = await fetch(url, { redirect: "follow" });
5621
6584
  if (!res.ok) throw new Error(`download failed: HTTP ${res.status} for ${url}`);
5622
- fs26.writeFileSync(dest, Buffer.from(await res.arrayBuffer()));
6585
+ fs28.writeFileSync(dest, Buffer.from(await res.arrayBuffer()));
5623
6586
  }
5624
- async function install() {
6587
+ async function install2() {
5625
6588
  if (process.platform !== "darwin") die("The Sakura menu bar app is macOS only.");
5626
- const tmp = fs26.mkdtempSync(path21.join(os11.tmpdir(), "sakura-app-"));
5627
- const dmg = path21.join(tmp, "Sakura.dmg");
5628
- const mount = path21.join(tmp, "mnt");
6589
+ const tmp = fs28.mkdtempSync(path23.join(os13.tmpdir(), "sakura-app-"));
6590
+ const dmg = path23.join(tmp, "Sakura.dmg");
6591
+ const mount = path23.join(tmp, "mnt");
5629
6592
  info(`Downloading Sakura.app ${VERSION}\u2026`);
5630
6593
  try {
5631
6594
  await download(dmgUrl(), dmg);
@@ -5633,27 +6596,27 @@ async function install() {
5633
6596
  die(`${e.message}
5634
6597
  Build it yourself instead: ./mac/scripts/build-dmg.sh in the Sakura repo.`);
5635
6598
  }
5636
- fs26.mkdirSync(mount);
6599
+ fs28.mkdirSync(mount);
5637
6600
  execFileSync4("hdiutil", ["attach", dmg, "-nobrowse", "-quiet", "-mountpoint", mount]);
5638
6601
  try {
5639
6602
  try {
5640
6603
  execFileSync4("osascript", ["-e", 'tell application id "mom.sakura.mac" to quit']);
5641
6604
  } catch {
5642
6605
  }
5643
- fs26.rmSync(APP_PATH, { recursive: true, force: true });
5644
- execFileSync4("ditto", [path21.join(mount, "Sakura.app"), APP_PATH]);
6606
+ fs28.rmSync(APP_PATH, { recursive: true, force: true });
6607
+ execFileSync4("ditto", [path23.join(mount, "Sakura.app"), APP_PATH]);
5645
6608
  } finally {
5646
6609
  execFileSync4("hdiutil", ["detach", mount, "-quiet"]);
5647
- fs26.rmSync(tmp, { recursive: true, force: true });
6610
+ fs28.rmSync(tmp, { recursive: true, force: true });
5648
6611
  }
5649
6612
  execFileSync4("open", [APP_PATH]);
5650
6613
  success("Sakura is in your menu bar (look for the blossom).");
5651
6614
  }
5652
6615
  function registerApp(program) {
5653
6616
  const app = program.command("app").description("The optional Sakura menu bar app for macOS");
5654
- app.command("install").description("Download Sakura.app into /Applications and open it").action(install);
6617
+ app.command("install").description("Download Sakura.app into /Applications and open it").action(install2);
5655
6618
  app.command("open").description("Open the Sakura menu bar app").action(() => {
5656
- if (!fs26.existsSync(APP_PATH)) die("Sakura.app is not installed. Run `sakuraai app install`.");
6619
+ if (!fs28.existsSync(APP_PATH)) die("Sakura.app is not installed. Run `sakuraai app install`.");
5657
6620
  execFileSync4("open", [APP_PATH]);
5658
6621
  });
5659
6622
  }