sakuraai 0.0.17 → 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 +228 -24
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -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 = [];
@@ -1093,12 +1148,17 @@ function send2(sessionId, message, onData, images, model, cwd) {
1093
1148
  (code) => resolve({
1094
1149
  ok: code === 0,
1095
1150
  output: out.trim(),
1096
- error: code === 0 ? void 0 : err.trim() || `exited ${code}`
1151
+ error: code === 0 ? void 0 : codexError(err) || `exited ${code}`
1097
1152
  })
1098
1153
  );
1099
1154
  });
1100
1155
  }
1101
- 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;
1102
1162
  var init_codex = __esm({
1103
1163
  "src/runtime/codex.ts"() {
1104
1164
  "use strict";
@@ -1108,6 +1168,7 @@ var init_codex = __esm({
1108
1168
  INDEX_PATH = path4.join(CODEX_DIR, "session_index.jsonl");
1109
1169
  SESSIONS_DIR = path4.join(CODEX_DIR, "sessions");
1110
1170
  MAC_APP_BIN = "/Applications/Codex.app/Contents/Resources/codex";
1171
+ archivedInCodex = /* @__PURE__ */ new Set();
1111
1172
  }
1112
1173
  });
1113
1174
 
@@ -1245,6 +1306,134 @@ var init_sqlite_transcript = __esm({
1245
1306
  }
1246
1307
  });
1247
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
+
1248
1437
  // src/runtime/opencode.ts
1249
1438
  import path5 from "path";
1250
1439
  import fs6 from "fs";
@@ -1283,10 +1472,12 @@ async function listSessions3() {
1283
1472
  const host = hostname();
1284
1473
  const now = nowSecs();
1285
1474
  try {
1475
+ const v2 = hasV2(db) ? listSessionsV2(db, host) : [];
1476
+ const seen = new Set(v2.map((x) => x.id));
1286
1477
  const rows = db.prepare(
1287
1478
  "SELECT id, title, time_updated, directory FROM session WHERE time_archived IS NULL ORDER BY time_updated DESC"
1288
1479
  ).all();
1289
- return rows.map((r) => {
1480
+ const v1 = rows.filter((r) => !seen.has(r.id)).map((r) => {
1290
1481
  const mtime = Math.floor(r.time_updated / 1e3);
1291
1482
  const age = Math.max(0, now - mtime);
1292
1483
  return {
@@ -1300,6 +1491,7 @@ async function listSessions3() {
1300
1491
  cwd: r.directory || void 0
1301
1492
  };
1302
1493
  });
1494
+ return [...v2, ...v1].sort((a, b) => b.mtime - a.mtime);
1303
1495
  } finally {
1304
1496
  db.close();
1305
1497
  }
@@ -1308,7 +1500,7 @@ async function messages3(sessionId) {
1308
1500
  const db = await open();
1309
1501
  if (!db) return [];
1310
1502
  try {
1311
- return buildMessages(db, "opencode", sessionId);
1503
+ return isV2Session(db, sessionId) ? buildMessagesV2(db, sessionId) : buildMessages(db, "opencode", sessionId);
1312
1504
  } finally {
1313
1505
  db.close();
1314
1506
  }
@@ -1317,7 +1509,7 @@ async function image(sessionId, partId) {
1317
1509
  const db = await open();
1318
1510
  if (!db) return null;
1319
1511
  try {
1320
- return filePartImage(db, sessionId, partId);
1512
+ return isV2Session(db, sessionId) ? imageV2(db, sessionId, partId) : filePartImage(db, sessionId, partId);
1321
1513
  } catch {
1322
1514
  return null;
1323
1515
  } finally {
@@ -1361,6 +1553,7 @@ var init_opencode = __esm({
1361
1553
  "src/runtime/opencode.ts"() {
1362
1554
  "use strict";
1363
1555
  init_sqlite_transcript();
1556
+ init_opencode_v2();
1364
1557
  init_util();
1365
1558
  DB_PATH = path5.join(HOME, ".local", "share", "opencode", "opencode.db");
1366
1559
  MAC_APP_BIN2 = "/Applications/OpenCode.app/Contents/MacOS/opencode-cli";
@@ -2353,7 +2546,7 @@ import path10 from "path";
2353
2546
  async function list(opts = {}) {
2354
2547
  let sessions = [];
2355
2548
  if (!opts.agent || opts.agent === "claude") sessions.push(...listSessions());
2356
- if (!opts.agent || opts.agent === "codex") sessions.push(...listSessions2());
2549
+ if (!opts.agent || opts.agent === "codex") sessions.push(...await listSessions2());
2357
2550
  if (!opts.agent || opts.agent === "opencode")
2358
2551
  sessions.push(...await listSessions3());
2359
2552
  if (!opts.agent || opts.agent === "zcode")
@@ -3825,6 +4018,15 @@ async function claudeModels() {
3825
4018
  return claudeCache?.models ?? CLAUDE_ALIASES;
3826
4019
  }
3827
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
+ }
3828
4030
  function codexModels() {
3829
4031
  const out = [{ id: "", label: "Default" }];
3830
4032
  const seen = /* @__PURE__ */ new Set();
@@ -3841,24 +4043,24 @@ function codexModels() {
3841
4043
  }
3842
4044
  } catch {
3843
4045
  }
3844
- for (const id of CODEX_CURATED) {
3845
- if (!seen.has(id)) {
3846
- seen.add(id);
3847
- 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);
3848
4050
  }
3849
4051
  }
3850
4052
  return out;
3851
4053
  }
3852
- function opencodeModels() {
3853
- const out = [{ id: "", label: "Default" }];
3854
- const allowed = /* @__PURE__ */ new Set(["opencode"]);
4054
+ function opencodeCatalog() {
3855
4055
  try {
3856
- const auth = JSON.parse(
3857
- fs18.readFileSync(path16.join(HOME, ".local", "share", "opencode", "auth.json"), "utf8")
3858
- );
3859
- for (const k of Object.keys(auth)) allowed.add(k);
4056
+ return JSON.parse(fs18.readFileSync(path16.join(HOME, ".cache", "opencode", "models.json"), "utf8"));
3860
4057
  } catch {
4058
+ return {};
3861
4059
  }
4060
+ }
4061
+ function opencodeModels() {
4062
+ const out = [{ id: "", label: "Default" }];
4063
+ const catalog2 = opencodeCatalog();
3862
4064
  try {
3863
4065
  const raw = execFileSync(opencodeBin(), ["models"], { encoding: "utf8", timeout: 15e3 });
3864
4066
  for (const line of raw.split("\n").map((l) => l.trim()).filter(Boolean)) {
@@ -3866,18 +4068,21 @@ function opencodeModels() {
3866
4068
  if (slash < 0) continue;
3867
4069
  const provider = line.slice(0, slash);
3868
4070
  const model = line.slice(slash + 1);
3869
- 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);
3870
4074
  out.push({
3871
4075
  id: line,
3872
4076
  // opencode wants the full provider/model string
3873
- label: model,
4077
+ label: info2?.name ?? model,
3874
4078
  group: OC_PROVIDER_LABELS[provider] ?? provider,
3875
- free: provider === "opencode" || /free/i.test(model)
4079
+ free
3876
4080
  });
3877
4081
  }
3878
4082
  } catch {
3879
4083
  }
3880
- 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))];
3881
4086
  }
3882
4087
  async function listModels(agent) {
3883
4088
  if (agent === "codex") return codexModels();
@@ -3893,7 +4098,7 @@ function zcodeModels() {
3893
4098
  function deepseekModels() {
3894
4099
  return [{ id: "", label: "Default" }];
3895
4100
  }
3896
- var CLAUDE_ALIASES, FAMILY_DESC, claudeCache, shortName, CODEX_CURATED, OC_PROVIDER_LABELS;
4101
+ var CLAUDE_ALIASES, FAMILY_DESC, claudeCache, shortName, OC_PROVIDER_LABELS;
3897
4102
  var init_models = __esm({
3898
4103
  "src/runtime/models.ts"() {
3899
4104
  "use strict";
@@ -3916,7 +4121,6 @@ var init_models = __esm({
3916
4121
  };
3917
4122
  claudeCache = null;
3918
4123
  shortName = (display) => display.replace(/^Claude\s+/i, "");
3919
- CODEX_CURATED = ["gpt-5.5-codex", "gpt-5.5", "gpt-5-codex", "gpt-5"];
3920
4124
  OC_PROVIDER_LABELS = {
3921
4125
  opencode: "OpenCode Zen",
3922
4126
  "opencode-go": "OpenCode Go",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sakuraai",
3
- "version": "0.0.17",
3
+ "version": "0.0.18",
4
4
  "description": "Sakura Agent CLI + local runtime for managing AI coding sessions (Claude Code, Codex, OpenCode, ZCode, DeepSeek) and reaching them privately from the Sakura mobile app over Tailscale",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",