t3code-session-manager 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/.claude-plugin/marketplace.json +21 -0
  2. package/.claude-plugin/plugin.json +19 -0
  3. package/CHANGELOG.md +138 -0
  4. package/LICENSE +21 -0
  5. package/README.md +660 -2
  6. package/README.pt.md +616 -0
  7. package/bin/entry.d.mts +2 -0
  8. package/bin/entry.mjs +19 -0
  9. package/bin/t3sm.mjs +44 -0
  10. package/commands/import.md +30 -0
  11. package/commands/organize.md +36 -0
  12. package/commands/status.md +24 -0
  13. package/commands/sync.md +26 -0
  14. package/dist/apply/apply.js +993 -0
  15. package/dist/apply/claudeWriter.js +168 -0
  16. package/dist/apply/copyTranscript.js +116 -0
  17. package/dist/apply/importer.js +697 -0
  18. package/dist/apply/materialize.js +335 -0
  19. package/dist/apply/waves.js +108 -0
  20. package/dist/assistant/core.js +295 -0
  21. package/dist/assistant/deps.js +256 -0
  22. package/dist/assistant/i18n.js +38 -0
  23. package/dist/assistant/messages.en.js +494 -0
  24. package/dist/assistant/messages.pt.js +495 -0
  25. package/dist/assistant/runner.js +64 -0
  26. package/dist/assistant/steps.js +1362 -0
  27. package/dist/build.json +1 -0
  28. package/dist/cli/applyScreen.js +158 -0
  29. package/dist/cli/commands/accounts.js +254 -0
  30. package/dist/cli/commands/apply.js +199 -0
  31. package/dist/cli/commands/changelog.js +61 -0
  32. package/dist/cli/commands/doctor.js +105 -0
  33. package/dist/cli/commands/help.js +158 -0
  34. package/dist/cli/commands/merge.js +224 -0
  35. package/dist/cli/commands/organize.js +872 -0
  36. package/dist/cli/commands/plan.js +161 -0
  37. package/dist/cli/commands/projects.js +430 -0
  38. package/dist/cli/commands/quarantine.js +203 -0
  39. package/dist/cli/commands/recover.js +230 -0
  40. package/dist/cli/commands/rollback.js +281 -0
  41. package/dist/cli/commands/scan.js +117 -0
  42. package/dist/cli/commands/schedule.js +288 -0
  43. package/dist/cli/commands/start.js +45 -0
  44. package/dist/cli/commands/status.js +615 -0
  45. package/dist/cli/commands/sync.js +336 -0
  46. package/dist/cli/commands/update.js +398 -0
  47. package/dist/cli/errors.js +53 -0
  48. package/dist/cli/failures.js +91 -0
  49. package/dist/cli/flags.js +53 -0
  50. package/dist/cli/help.en.js +549 -0
  51. package/dist/cli/help.pt.js +566 -0
  52. package/dist/cli/helpText.js +211 -0
  53. package/dist/cli/helpTopics.js +58 -0
  54. package/dist/cli/locked.js +12 -0
  55. package/dist/cli/main.js +155 -0
  56. package/dist/cli/screen.js +3 -0
  57. package/dist/cli/ui.js +111 -0
  58. package/dist/cli/words.js +2 -0
  59. package/dist/core/activity.js +16 -0
  60. package/dist/core/changelog.js +47 -0
  61. package/dist/core/config.js +530 -0
  62. package/dist/core/fsutil.js +171 -0
  63. package/dist/core/glob.js +34 -0
  64. package/dist/core/history.js +32 -0
  65. package/dist/core/journal.js +274 -0
  66. package/dist/core/lock.js +337 -0
  67. package/dist/core/mask.js +31 -0
  68. package/dist/core/paths.js +68 -0
  69. package/dist/core/pid.js +101 -0
  70. package/dist/core/run.js +4 -0
  71. package/dist/core/semver.js +18 -0
  72. package/dist/core/sysroot.js +29 -0
  73. package/dist/core/types.js +229 -0
  74. package/dist/core/uuid.js +29 -0
  75. package/dist/core/version.js +72 -0
  76. package/dist/help/convert.md +20 -0
  77. package/dist/help/convert.pt.md +21 -0
  78. package/dist/help/cwd-unreadable.md +22 -0
  79. package/dist/help/cwd-unreadable.pt.md +22 -0
  80. package/dist/help/decisions.md +20 -0
  81. package/dist/help/decisions.pt.md +20 -0
  82. package/dist/help/errors.md +20 -0
  83. package/dist/help/errors.pt.md +22 -0
  84. package/dist/help/held.md +20 -0
  85. package/dist/help/held.pt.md +20 -0
  86. package/dist/help/history.md +27 -0
  87. package/dist/help/history.pt.md +29 -0
  88. package/dist/help/instance-unavailable.md +18 -0
  89. package/dist/help/instance-unavailable.pt.md +19 -0
  90. package/dist/help/not-imported.md +19 -0
  91. package/dist/help/not-imported.pt.md +19 -0
  92. package/dist/help/orphaned.md +19 -0
  93. package/dist/help/orphaned.pt.md +19 -0
  94. package/dist/help/project-mismatch.md +15 -0
  95. package/dist/help/project-mismatch.pt.md +15 -0
  96. package/dist/help/t3-native.md +22 -0
  97. package/dist/help/t3-native.pt.md +22 -0
  98. package/dist/help/updates.md +26 -0
  99. package/dist/help/updates.pt.md +28 -0
  100. package/dist/help/watcher.md +24 -0
  101. package/dist/help/watcher.pt.md +25 -0
  102. package/dist/i18n/cli.js +41 -0
  103. package/dist/i18n/lang.js +55 -0
  104. package/dist/i18n/messages.en.js +1140 -0
  105. package/dist/i18n/messages.pt.js +1149 -0
  106. package/dist/i18n/words.js +12 -0
  107. package/dist/ops/accounts.js +170 -0
  108. package/dist/ops/autoUpdate.js +223 -0
  109. package/dist/ops/discoverAccounts.js +343 -0
  110. package/dist/ops/doctor.js +811 -0
  111. package/dist/ops/elevated.js +47 -0
  112. package/dist/ops/errorCodes.js +39 -0
  113. package/dist/ops/follow.js +558 -0
  114. package/dist/ops/merge.js +830 -0
  115. package/dist/ops/notify.js +249 -0
  116. package/dist/ops/plugin.js +92 -0
  117. package/dist/ops/projects.js +113 -0
  118. package/dist/ops/quarantine.js +415 -0
  119. package/dist/ops/rollback.js +868 -0
  120. package/dist/ops/schedule.js +464 -0
  121. package/dist/ops/successor.js +51 -0
  122. package/dist/ops/sync.js +859 -0
  123. package/dist/ops/syncStatus.js +290 -0
  124. package/dist/ops/update.js +273 -0
  125. package/dist/ops/updater.js +641 -0
  126. package/dist/ops/watch.js +676 -0
  127. package/dist/ops/watcherControl.js +212 -0
  128. package/dist/ops/watcherHealth.js +75 -0
  129. package/dist/organize/apply.js +495 -0
  130. package/dist/organize/history.js +192 -0
  131. package/dist/organize/plan.js +283 -0
  132. package/dist/organize/rename.js +58 -0
  133. package/dist/organize/sessions.js +100 -0
  134. package/dist/organize/titles.js +70 -0
  135. package/dist/organize/types.js +73 -0
  136. package/dist/plan/categories.js +104 -0
  137. package/dist/plan/dedupe.js +137 -0
  138. package/dist/plan/folders.js +82 -0
  139. package/dist/plan/names.js +93 -0
  140. package/dist/plan/ownership.js +316 -0
  141. package/dist/plan/planner.js +669 -0
  142. package/dist/plan/rehome.js +101 -0
  143. package/dist/plan/report.js +407 -0
  144. package/dist/sources/cache.js +89 -0
  145. package/dist/sources/claude.js +297 -0
  146. package/dist/sources/codex.js +496 -0
  147. package/dist/sources/flatten.js +23 -0
  148. package/dist/sources/jsonl.js +169 -0
  149. package/dist/sources/native.js +233 -0
  150. package/dist/sources/opencode.js +483 -0
  151. package/dist/sources/pi.js +133 -0
  152. package/dist/sources/registry.js +67 -0
  153. package/dist/sources/types.js +80 -0
  154. package/dist/t3/api.js +492 -0
  155. package/dist/t3/auth.js +248 -0
  156. package/dist/t3/compat.js +62 -0
  157. package/dist/t3/decode.js +408 -0
  158. package/dist/t3/errors.js +185 -0
  159. package/dist/t3/rpc.js +185 -0
  160. package/dist/t3/runtime.js +80 -0
  161. package/dist/ui/caps.js +56 -0
  162. package/dist/ui/components.js +202 -0
  163. package/dist/ui/layout.js +205 -0
  164. package/dist/ui/list.js +423 -0
  165. package/dist/ui/locale.js +73 -0
  166. package/dist/ui/organizePreview.js +72 -0
  167. package/dist/ui/progress.js +237 -0
  168. package/dist/ui/style.js +32 -0
  169. package/dist/ui/terminal.js +126 -0
  170. package/dist/ui/text.js +186 -0
  171. package/package.json +58 -4
  172. package/skills/t3code-sessions/SKILL.md +183 -0
@@ -0,0 +1,483 @@
1
+ // OpenCode source adapter (convert mode): OpenCode keeps every session in one SQLite database,
2
+ // `$XDG_DATA_HOME/opencode/opencode.db` (default `~/.local/share/opencode/opencode.db`, the same path on Windows).
3
+ // T3 Code cannot import it, so its sessions are converted into Claude transcripts (apply/claudeWriter.ts) and imported
4
+ // as Claude threads. Schema and tested version: docs/harnesses.md.
5
+ //
6
+ // The source is NEVER opened, not even read-only: OpenCode runs the db in WAL mode, and a read-only SQLite connection
7
+ // to a WAL db still writes the shared-memory index (`-shm`) and needs `-wal`/`-shm` to exist. Instead (takeSnapshot):
8
+ // 1. the db and its `-wal` are stream-copied, owner-only (0o600, created exclusively), into `<cache>/tmp/`;
9
+ // 2. if the source changed while it was copied, the copy is discarded and retaken (3 attempts, then SourceBusyError);
10
+ // 3. the raw copy is opened (its WAL replays), its schema is checked, and a FRESH database is built next to it with
11
+ // `CREATE TABLE … AS SELECT <only the columns read here>` from session / message / part. Nothing else of
12
+ // OpenCode's db (account tokens, credentials, share secrets, permissions, metadata) ever reaches the kept file;
13
+ // 4. the raw copy and its -wal/-shm/-journal are deleted in `finally`; the fresh one is published no-clobber as
14
+ // `<cache>/opencode-s2-<source identity>.db` (`s2` = snapshot format; older formats are deleted on entry) and
15
+ // opened `readOnly: true` from then on. It carries the indexes every query below needs (no full scans).
16
+ // `<cache>/tmp/` is swept on entry (anything older than 5 minutes or left by a dead process), so a crash never leaves a
17
+ // raw copy behind for long. `<cache>` is `<stateDir>/cache/opencode`, or, for read-only envs (`sync --dry-run`,
18
+ // `doctor`), one OS temp dir per process, removed after discovery or at exit (stale ones are swept too).
19
+ //
20
+ // One snapshot per run: discovery pins its snapshot (source path + identity) and `read()` reuses it, so every session
21
+ // of a run is read from the same consistent state. Without a discovery in the process (apply reads plan.json), the
22
+ // first `read()` takes and pins one. A reused snapshot is touched (mtime = last use), so pruning by age never removes
23
+ // one in use; a reader whose pinned snapshot vanished anyway re-pins once.
24
+ //
25
+ // Convert-mode sessions share one source file: every DiscoveredSession's `file` is the db itself (its size/mtime
26
+ // change whenever any session does). Activity is per session (`session.time_updated`): the `active` flag, the read-time
27
+ // active check and continued-outside-t3 (the planner compares the updatedAt / messageCount journaled at conversion).
28
+ //
29
+ // Errors: HarnessSchemaError on schema drift (availability `{drift}`, discovery error, `read` throws it);
30
+ // SourceBusyError when the db kept changing while copied; SessionActiveError when a session read was updated within
31
+ // ACTIVE_WINDOW_MS. The last two are deferrals, not failures (see SourceAdapter.read).
32
+
33
+ import { createReadStream, rmSync } from "node:fs";
34
+ import { chmod, link, mkdir, open, readdir, rm, stat, unlink, utimes } from "node:fs/promises";
35
+ import { pipeline } from "node:stream/promises";
36
+ import { createHash, randomBytes } from "node:crypto";
37
+ import { homedir, tmpdir } from "node:os";
38
+ import { basename, dirname, join } from "node:path";
39
+
40
+
41
+ import { publishNoClobber, statSafe } from "../core/fsutil.js";
42
+ import { stateDir } from "../core/paths.js";
43
+ import { isActive } from "../core/activity.js";
44
+ import { pidAlive } from "../core/pid.js";
45
+ import {
46
+ HarnessSchemaError, SessionActiveError, SourceBusyError,
47
+ } from "./types.js";
48
+ import { TOOL_TEXT_MAX, clip, toolInput, toolLine } from "./flatten.js";
49
+
50
+ /** Tables and columns read here (OpenCode 1.19.5). Anything missing is schema drift; nothing else is ever copied. */
51
+ export const OPENCODE_REQUIRED = {
52
+ session: ["id", "parent_id", "directory", "title", "time_created", "time_updated"],
53
+ message: ["id", "session_id", "time_created", "data"],
54
+ part: ["id", "message_id", "session_id", "data"],
55
+ };
56
+
57
+ /** Part types the reader knows (rendered or deliberately dropped). Others are counted in discovery's lastErrors. */
58
+ export const KNOWN_PART_TYPES = new Set([
59
+ "text", "tool", "file", "subtask", "reasoning", "step-start", "step-finish", "snapshot", "patch", "compaction", "retry", "agent",
60
+ ]);
61
+
62
+ export { TOOL_TEXT_MAX } from "./flatten.js";
63
+ const COPY_ATTEMPTS = 3;
64
+ /** Leftovers in a snapshot tmp dir (or a read-only temp dir) older than this are removed even if their process lives. */
65
+ export const STALE_TMP_MS = 5 * 60_000;
66
+ const TEMP_PREFIX = "t3sm-opencode-";
67
+ /** Kept snapshot names: `opencode-s2-<16 hex>.db` (s2 = stripped + indexed). */
68
+ const SNAPSHOT_PREFIX = "opencode-s2-";
69
+ const SNAPSHOT_RE = /^opencode-s2-[0-9a-f]{16}\.db$/;
70
+
71
+ /** SQLite could not open the file (SQLITE_CANTOPEN = 14) or it is gone. */
72
+ function vanished(e ) {
73
+ const o = e ;
74
+ return o.code === "ENOENT" || o.errcode === 14 || /unable to open/i.test(o.message ?? "");
75
+ }
76
+
77
+ /** Marks a snapshot as used now (its age is time since last use). Never throws. */
78
+ async function touch(path ) {
79
+ const now = new Date();
80
+ await utimes(path, now, now).catch(() => {});
81
+ }
82
+
83
+ export function openCodeDbPath(env ) {
84
+ const xdg = (env.env ?? process.env)["XDG_DATA_HOME"];
85
+ return join(xdg ? xdg : join(env.home, ".local", "share"), "opencode", "opencode.db");
86
+ }
87
+
88
+ // ---------- snapshot ----------
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+ /** Test hooks for takeSnapshot (fault injection). */
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+ async function signature(db ) {
106
+ const main = await statSafe(db);
107
+ if (!main) return null;
108
+ const wal = await statSafe(`${db}-wal`);
109
+ return `${db}|${main.size}|${main.mtimeMs}|${wal?.size ?? -1}|${wal?.mtimeMs ?? -1}`;
110
+ }
111
+
112
+ let sqlite = null;
113
+ /** node:sqlite is loaded only when an OpenCode db exists (it prints an ExperimentalWarning on Node 22/24). */
114
+ function loadSqlite() {
115
+ sqlite ??= import("node:sqlite");
116
+ return sqlite;
117
+ }
118
+
119
+ /** Removes entries named `<prefix><pid>-…` whose process is gone, and any older than STALE_TMP_MS. Never throws. */
120
+ async function sweep(dir , prefix ) {
121
+ for (const name of await readdir(dir).catch(() => [] )) {
122
+ const m = prefix.exec(name);
123
+ if (!m) continue;
124
+ const p = join(dir, name);
125
+ const st = await stat(p).catch(() => null);
126
+ if (!st) continue;
127
+ if (!pidAlive(Number(m[1])) || Date.now() - st.mtimeMs > STALE_TMP_MS) await rm(p, { recursive: true, force: true }).catch(() => {});
128
+ }
129
+ }
130
+
131
+ /** Copies `src` into a NEW file `dst` (exclusive create, owner-only from the first byte). */
132
+ async function copyPrivate(src , dst ) {
133
+ const fh = await open(dst, "wx", 0o600);
134
+ // The write stream owns the handle from here (closed on finish and on error).
135
+ await pipeline(createReadStream(src), fh.createWriteStream());
136
+ }
137
+
138
+ /** The raw copy -> a fresh db holding only OPENCODE_REQUIRED (schema checked on the raw copy first). */
139
+ async function buildStripped(raw , out ) {
140
+ const { DatabaseSync } = await loadSqlite();
141
+ await (await open(out, "wx", 0o600)).close(); // exists, owner-only, before SQLite writes to it
142
+ // Foreign keys OFF: node:sqlite turns them on, and nothing here may cascade.
143
+ const c = new DatabaseSync(raw, { enableForeignKeyConstraints: false });
144
+ try {
145
+ checkSchema(c);
146
+ c.exec(`ATTACH DATABASE '${out.replaceAll("'", "''")}' AS out`);
147
+ try {
148
+ for (const [table, cols] of Object.entries(OPENCODE_REQUIRED)) {
149
+ c.exec(`CREATE TABLE out.${table} AS SELECT ${cols.join(", ")} FROM main.${table}`);
150
+ }
151
+ // One index per access path of OPENCODE_QUERIES (asserted with EXPLAIN QUERY PLAN in the tests).
152
+ c.exec("CREATE UNIQUE INDEX out.session_id ON session (id)");
153
+ c.exec("CREATE INDEX out.session_created ON session (time_created, id)");
154
+ c.exec("CREATE INDEX out.message_session ON message (session_id, time_created, id)");
155
+ c.exec("CREATE INDEX out.part_message ON part (message_id, id)");
156
+ c.exec("CREATE INDEX out.part_session ON part (session_id, message_id, id)");
157
+ } finally {
158
+ c.exec("DETACH DATABASE out");
159
+ }
160
+ } finally {
161
+ c.close();
162
+ }
163
+ }
164
+
165
+ /**
166
+ * A private, consistent, stripped copy of the db, reused while the source is unchanged (same identity). Throws an
167
+ * ENOENT error when the db does not exist, HarnessSchemaError on drift, SourceBusyError when it kept changing.
168
+ */
169
+ export async function takeSnapshot(db , cacheDir , hooks = {}) {
170
+ await mkdir(cacheDir, { recursive: true, mode: 0o700 });
171
+ await chmod(cacheDir, 0o700).catch(() => {});
172
+ const tmp = join(cacheDir, "tmp");
173
+ await mkdir(tmp, { recursive: true, mode: 0o700 });
174
+ await chmod(tmp, 0o700).catch(() => {});
175
+ await sweep(tmp, /^(?:raw|out)-(\d+)-/);
176
+ // Snapshots of an older format (unindexed `opencode-<hash>.db`) and their old temp files: never reused, deleted.
177
+ for (const f of await readdir(cacheDir).catch(() => [] )) {
178
+ if (/^opencode-[0-9a-f]{16}\.db$/.test(f) || /^opencode-.*\.db\.\d+\.[0-9a-f]+\.tmp$/.test(f)) await rm(join(cacheDir, f), { force: true }).catch(() => {});
179
+ }
180
+ for (let attempt = 0; attempt < COPY_ATTEMPTS; attempt++) {
181
+ const before = await signature(db);
182
+ if (before === null) throw Object.assign(new Error(`${db} not found`), { code: "ENOENT" });
183
+ const name = `${SNAPSHOT_PREFIX}${createHash("sha256").update(before).digest("hex").slice(0, 16)}.db`;
184
+ const dest = join(cacheDir, name);
185
+ if (await statSafe(dest)) { // only ever published complete
186
+ await touch(dest);
187
+ return { path: dest, identity: before };
188
+ }
189
+ const tag = `${process.pid}-${randomBytes(6).toString("hex")}`;
190
+ const raw = join(tmp, `raw-${tag}.db`);
191
+ const out = join(tmp, `out-${tag}.db`);
192
+ try {
193
+ await copyPrivate(db, raw);
194
+ if (await statSafe(`${db}-wal`)) await copyPrivate(`${db}-wal`, `${raw}-wal`);
195
+ if ((await signature(db)) !== before) continue; // written while copying: take it again
196
+ await hooks.afterRawCopy?.();
197
+ await buildStripped(raw, out);
198
+ try {
199
+ await publishNoClobber(out, dest, { link, unlink });
200
+ } catch (e) {
201
+ if ((e ).code !== "EEXIST") throw e; // another t3sm process published the same identity
202
+ }
203
+ // Snapshots of other source states: removed once unused for 5 minutes (mtime = last use, see touch), so a
204
+ // concurrent run's pinned one survives; one still open on Windows stays until next time.
205
+ for (const f of await readdir(cacheDir).catch(() => [] )) {
206
+ if (f === name || !SNAPSHOT_RE.test(f)) continue;
207
+ const st = await stat(join(cacheDir, f)).catch(() => null);
208
+ if (st && Date.now() - st.mtimeMs > STALE_TMP_MS) await rm(join(cacheDir, f), { force: true }).catch(() => {});
209
+ }
210
+ return { path: dest, identity: before };
211
+ } finally {
212
+ await Promise.all([raw, `${raw}-wal`, `${raw}-shm`, `${raw}-journal`, out, `${out}-journal`].map((p) => rm(p, { force: true, maxRetries: 3 })));
213
+ }
214
+ }
215
+ throw new SourceBusyError(`${db} kept changing while it was copied (${COPY_ATTEMPTS} attempts); deferred to the next run`);
216
+ }
217
+
218
+ function checkSchema(db ) {
219
+ for (const [table, cols] of Object.entries(OPENCODE_REQUIRED)) {
220
+ const have = new Set((db.prepare(`PRAGMA table_info(${table})`).all() ).map((c) => c.name));
221
+ if (have.size === 0) throw new HarnessSchemaError("opencode", `opencode: table ${table} is missing (OpenCode schema changed; tested with 1.19.5)`);
222
+ const missing = cols.filter((c) => !have.has(c));
223
+ if (missing.length > 0) throw new HarnessSchemaError("opencode", `opencode: table ${table} lacks column(s) ${missing.join(", ")} (OpenCode schema changed; tested with 1.19.5)`);
224
+ }
225
+ }
226
+
227
+ // ---------- discovery ----------
228
+
229
+
230
+
231
+
232
+
233
+
234
+ // A user message counts as visible when it has a non-empty text part OpenCode did not synthesize (file contents
235
+ // it injects are `synthetic`). Malformed JSON rows are skipped by json_valid instead of failing the query.
236
+ const SESSIONS_SQL = `
237
+ SELECT s.id, s.parent_id, s.directory, s.time_created, s.time_updated,
238
+ (SELECT count(*) FROM message m WHERE m.session_id = s.id) AS messages,
239
+ (SELECT count(*) FROM message m
240
+ WHERE m.session_id = s.id AND json_valid(m.data) AND json_extract(m.data, '$.role') = 'user'
241
+ AND EXISTS (SELECT 1 FROM part p WHERE p.message_id = m.id AND json_valid(p.data)
242
+ AND json_extract(p.data, '$.type') = 'text'
243
+ AND coalesce(json_extract(p.data, '$.synthetic'), 0) = 0 AND coalesce(json_extract(p.data, '$.ignored'), 0) = 0
244
+ AND trim(coalesce(json_extract(p.data, '$.text'), '')) <> '')) AS user_texts
245
+ FROM session s
246
+ ORDER BY s.time_created, s.id`;
247
+
248
+ const PART_TYPES_SQL = "SELECT coalesce(json_extract(data, '$.type'), '?') AS type, count(*) AS n FROM part WHERE json_valid(data) GROUP BY 1 ORDER BY 1";
249
+ const SESSION_BY_ID_SQL = "SELECT id, directory, title, time_created, time_updated FROM session WHERE id = ?";
250
+ const PARTS_OF_SESSION_SQL = "SELECT message_id, data FROM part WHERE session_id = ? ORDER BY message_id, id";
251
+ const MESSAGES_OF_SESSION_SQL = "SELECT id, time_created, data FROM message WHERE session_id = ? ORDER BY time_created, id";
252
+
253
+ /**
254
+ * Every query the adapter runs on a snapshot. `partTypes` deliberately reads all parts (one aggregate per discovery);
255
+ * every other access must be an index lookup (tests run EXPLAIN QUERY PLAN on each).
256
+ */
257
+ export const OPENCODE_QUERIES = {
258
+ sessions: SESSIONS_SQL, partTypes: PART_TYPES_SQL, sessionById: SESSION_BY_ID_SQL,
259
+ partsOfSession: PARTS_OF_SESSION_SQL, messagesOfSession: MESSAGES_OF_SESSION_SQL,
260
+ } ;
261
+
262
+ const iso = (ms ) => new Date(ms).toISOString();
263
+
264
+ // ---------- reading ----------
265
+
266
+
267
+ const str = (v ) => (typeof v === "string" ? v : null);
268
+
269
+ /** One part as text, or null when it carries nothing worth keeping (reasoning, step markers, snapshots, ...). */
270
+ function renderPart(p ) {
271
+ switch (p.type) {
272
+ case "text":
273
+ if (p.synthetic === true || p.ignored === true) return null;
274
+ return str(p.text);
275
+ case "tool": {
276
+ const state = (p.state ?? {}) ;
277
+ const output = state.status === "completed" ? str(state.output) ?? ""
278
+ : state.status === "error" ? `error: ${str(state.error) ?? "unknown"}`
279
+ : `(${str(state.status) ?? "unknown"})`;
280
+ return toolLine(str(p.tool) ?? "unknown", toolInput(state.input), output);
281
+ }
282
+ case "file": {
283
+ const url = str(p.url);
284
+ const name = str(p.filename) ?? (url && !url.startsWith("data:") ? basename(url) : null) ?? str(p.mime) ?? "file";
285
+ return `[attachment: ${name}]`;
286
+ }
287
+ case "subtask":
288
+ return `[subtask ${str(p.agent) ?? "agent"}] ${clip(str(p.description) ?? str(p.prompt) ?? "", TOOL_TEXT_MAX)}`;
289
+ default:
290
+ return null; // reasoning, step-start, step-finish, snapshot, patch, compaction, retry, agent, unknown types
291
+ }
292
+ }
293
+
294
+ function parse(json ) {
295
+ try {
296
+ const v = JSON.parse(json);
297
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? (v ) : null;
298
+ } catch {
299
+ return null;
300
+ }
301
+ }
302
+
303
+ function readTranscript(db , id , now ) {
304
+ const s = db.prepare(SESSION_BY_ID_SQL).get(id)
305
+ ;
306
+ if (!s) throw new Error(`opencode session ${id} not found`);
307
+ if (isActive(s.time_updated, now)) throw new SessionActiveError(`opencode session ${id} was updated ${Math.max(0, Math.round((now - s.time_updated) / 1000))} s ago; it may be in use`);
308
+ const parts = new Map ();
309
+ for (const r of db.prepare(PARTS_OF_SESSION_SQL).all(id) ) {
310
+ const p = parse(r.data);
311
+ const text = p ? renderPart(p) : null;
312
+ if (text === null || text.trim() === "") continue;
313
+ (parts.get(r.message_id) ?? parts.set(r.message_id, []).get(r.message_id) ).push(text);
314
+ }
315
+ const messages = [];
316
+ const rows = db.prepare(MESSAGES_OF_SESSION_SQL).all(id) ;
317
+ for (const m of rows) {
318
+ const role = parse(m.data)?.role;
319
+ if (role !== "user" && role !== "assistant") continue;
320
+ const texts = parts.get(m.id);
321
+ if (!texts) continue; // nothing renderable (a reasoning-only step): no empty bubble
322
+ messages.push({ role, text: texts.join("\n\n"), timestamp: iso(m.time_created) });
323
+ }
324
+ return {
325
+ harness: "opencode", nativeId: s.id, cwd: s.directory ?? "", title: s.title, startedAt: iso(s.time_created), messages,
326
+ activity: { updatedAt: iso(s.time_updated), messageCount: rows.length },
327
+ };
328
+ }
329
+
330
+ // ---------- adapter ----------
331
+
332
+
333
+
334
+
335
+
336
+
337
+
338
+
339
+
340
+
341
+
342
+
343
+
344
+
345
+
346
+
347
+
348
+ export function createOpenCodeAdapter(opts = {}) {
349
+ const snap = opts.snapshot ?? ((db, dir) => takeSnapshot(db, dir));
350
+ const now = opts.now ?? Date.now;
351
+ /** The snapshot this run reads from (pinned by discovery or the first read). */
352
+ let pin = null;
353
+ let lastDir = null;
354
+ /** The per-process temp cache of read-only envs (removed after discovery and at exit). */
355
+ let tempDir = null;
356
+
357
+ const readOnlyDir = async () => {
358
+ if (tempDir) return tempDir;
359
+ await sweep(tmpdir(), new RegExp(`^${TEMP_PREFIX}(\\d+)-`));
360
+ const d = join(tmpdir(), `${TEMP_PREFIX}${process.pid}-${randomBytes(6).toString("hex")}`);
361
+ await mkdir(d, { recursive: true, mode: 0o700 });
362
+ tempDir = d;
363
+ process.once("exit", () => { try { rmSync(d, { recursive: true, force: true }); } catch { /* swept next time */ } });
364
+ return d;
365
+ };
366
+ const dropReadOnlyDir = async () => {
367
+ if (!tempDir) return;
368
+ const d = tempDir;
369
+ tempDir = null;
370
+ if (pin?.dir === d) pin = null;
371
+ await rm(d, { recursive: true, force: true, maxRetries: 3 }).catch(() => {});
372
+ };
373
+ /** Snapshot the env's db and pin it for this run. */
374
+ const pinFor = async (env , db ) => {
375
+ const dir = env.readOnly ? await readOnlyDir() : join(env.stateDir, "cache", "opencode");
376
+ if (!env.readOnly) lastDir = dir;
377
+ const s = await snap(db, dir);
378
+ pin = { ...s, source: db, dir };
379
+ return s;
380
+ };
381
+ const openReadOnly = async (path ) => {
382
+ const { DatabaseSync } = await loadSqlite();
383
+ return new DatabaseSync(path, { readOnly: true });
384
+ };
385
+
386
+ const adapter = {
387
+ id: "opencode",
388
+ mode: "convert",
389
+ lastErrors: [],
390
+ async availability(env ) {
391
+ const db = openCodeDbPath(env);
392
+ if (!(await statSafe(db).catch(() => null))) return "absent";
393
+ try {
394
+ await pinFor(env, db);
395
+ return "ok";
396
+ } catch (e) {
397
+ if (e instanceof HarnessSchemaError) return { drift: e.message };
398
+ if ((e ).code === "ENOENT") return "absent";
399
+ return { unreadable: e instanceof Error ? e.message : String(e) };
400
+ }
401
+ },
402
+ async isAvailable(env ) {
403
+ return (await adapter.availability(env)) === "ok";
404
+ },
405
+ async watchRoots(env ) {
406
+ const db = openCodeDbPath(env);
407
+ return (await statSafe(db)) ? [dirname(db)] : [];
408
+ },
409
+ async *discover(env ) {
410
+ adapter.lastErrors = [];
411
+ const path = openCodeDbPath(env);
412
+ let rows ;
413
+ let file ;
414
+ try {
415
+ file = await statSafe(path);
416
+ if (!file) return;
417
+ // Reuse the pin isAvailable just took for this env (read-only: one temp copy for both), else take one.
418
+ const s = pin && pin.source === path && (env.readOnly ? pin.dir === tempDir : pin.dir === join(env.stateDir, "cache", "opencode")) && (await statSafe(pin.path))
419
+ ? pin : await pinFor(env, path);
420
+ const db = await openReadOnly(s.path);
421
+ try {
422
+ rows = db.prepare(SESSIONS_SQL).all() ;
423
+ const unknown = (db.prepare(PART_TYPES_SQL).all() ).filter((r) => !KNOWN_PART_TYPES.has(r.type));
424
+ if (unknown.length > 0) {
425
+ adapter.lastErrors.push({ path, error: `opencode: ${unknown.reduce((n, r) => n + r.n, 0)} part(s) of unknown type (${unknown.map((r) => r.type).join(", ")}) are left out of conversions` });
426
+ }
427
+ } finally {
428
+ db.close();
429
+ }
430
+ } catch (e) {
431
+ adapter.lastErrors.push({ path, error: e instanceof Error ? `${e.name}: ${e.message}` : String(e) });
432
+ if (env.readOnly) await dropReadOnlyDir();
433
+ return;
434
+ }
435
+ if (env.readOnly) await dropReadOnlyDir(); // read-only discovery leaves nothing behind
436
+ for (const r of rows) {
437
+ if (r.messages === 0) continue; // an opened-and-abandoned session: nothing to convert
438
+ const flags = [];
439
+ if (r.parent_id) flags.push("subagent"); // a subagent's child session belongs to its parent's conversation
440
+ if (!r.directory) flags.push("no-cwd");
441
+ if (r.user_texts === 0) flags.push("only-hidden");
442
+ if (isActive(r.time_updated, env.now())) flags.push("active");
443
+ yield {
444
+ harness: "opencode", accountId: null, nativeId: r.id, cwd: r.directory ? r.directory : null,
445
+ startedAt: iso(r.time_created), updatedAt: iso(r.time_updated),
446
+ messageCount: r.messages, corruptLines: 0, file: { ...file }, flags,
447
+ cwdOffsetBytes: 0, // the converted transcript carries cwd on its first record
448
+ };
449
+ }
450
+ },
451
+ async read(s ) {
452
+ const repin = async () => {
453
+ const dir = pin?.source === s.file.path ? pin.dir : opts.snapshotDir ?? lastDir ?? join(stateDir(process.env, homedir()), "cache", "opencode");
454
+ const taken = await snap(s.file.path, dir);
455
+ pin = { ...taken, source: s.file.path, dir };
456
+ return taken.path;
457
+ };
458
+ let snapPath ;
459
+ if (pin && pin.source === s.file.path) {
460
+ snapPath = pin.path;
461
+ await touch(snapPath); // in use: age = time since last use
462
+ } else snapPath = await repin();
463
+ for (let attempt = 0; ; attempt++) {
464
+ let db ;
465
+ try {
466
+ db = await openReadOnly(snapPath);
467
+ } catch (e) {
468
+ // The pinned snapshot vanished (pruned by a concurrent run, removed by hand): re-pin once, then fail.
469
+ if (attempt === 0 && vanished(e)) { snapPath = await repin(); continue; }
470
+ throw e;
471
+ }
472
+ try {
473
+ return readTranscript(db, s.nativeId, now());
474
+ } finally {
475
+ db.close();
476
+ }
477
+ }
478
+ },
479
+ };
480
+ return adapter;
481
+ }
482
+
483
+ export const opencodeAdapter = createOpenCodeAdapter();
@@ -0,0 +1,133 @@
1
+ import { join, resolve } from "node:path";
2
+ import { createNativeAdapter, } from "./native.js";
3
+ import { entryKind, extractText, isoOrNull, listDir, obj, scanJsonl, str, } from "./jsonl.js";
4
+ import { CWD_SCAN_MAX_BYTES, CWD_SCAN_MAX_RECORDS, } from "./types.js";
5
+
6
+
7
+
8
+ function expandHome(p , home ) {
9
+ if (p === "~") return home;
10
+ if (p.startsWith("~/") || p.startsWith("~\\")) return join(home, p.slice(2));
11
+ return p;
12
+ }
13
+
14
+ /**
15
+ * Pi sessions directory, as T3 resolves it (resolvePiSessionsDir, packages/provider-pi/src/server/usage.ts:164-176):
16
+ * `PI_CODING_AGENT_SESSION_DIR`, else `<PI_CODING_AGENT_DIR>/sessions`, else `~/.pi/agent/sessions`;
17
+ * `~` is expanded and the result resolved.
18
+ */
19
+ export function piSessionsDir(env ) {
20
+ const e = env.env ?? process.env;
21
+ const sessionDir = e.PI_CODING_AGENT_SESSION_DIR?.trim();
22
+ if (sessionDir) return resolve(expandHome(sessionDir, env.home));
23
+ const agentDir = e.PI_CODING_AGENT_DIR?.trim();
24
+ return resolve(agentDir ? expandHome(agentDir, env.home) : join(env.home, ".pi", "agent"), "sessions");
25
+ }
26
+
27
+ /**
28
+ * Pi nests sessions in one directory per cwd, but a custom session directory holds them flat:
29
+ * entries ending in `.jsonl` are transcripts, any other entry is read as a directory whose `.jsonl`
30
+ * children are (T3 AgentSessionScanner.ts:1278-1330, discoverPiTranscripts).
31
+ */
32
+ async function* files(env , onError ) {
33
+ const root = piSessionsDir(env);
34
+ for (const e of await listDir(root)) {
35
+ const p = join(root, e.name);
36
+ const kind = await entryKind(root, e, onError);
37
+ if (e.name.endsWith(".jsonl")) {
38
+ if (kind === "file") yield p;
39
+ continue;
40
+ }
41
+ if (kind !== "dir") continue;
42
+ for (const f of await listDir(p)) {
43
+ if (f.name.endsWith(".jsonl") && (await entryKind(p, f, onError)) === "file") yield join(p, f.name);
44
+ }
45
+ }
46
+ }
47
+
48
+ // 0 other, 1 assistant, 2 user
49
+
50
+ /**
51
+ * Rules copied from T3 (apps/server/src/project/AgentSessionScanner.ts):
52
+ * - session id (`providerSessionId`): the first `type:"session"` record id, trimmed, else the file
53
+ * stem (lines 411-413, 1745). T3 resumes Pi by file path, which we keep in `file.path` (spike S2).
54
+ * - cwd: first record with a non-blank top-level `cwd` or `payload.cwd` (extractCwd, 677-712), within
55
+ * 1 MiB / 1000 records.
56
+ * - messages: only the active branch counts (activePiBranch, 352-372): from the last non-session entry
57
+ * up its `parentId` chain; legacy v1 files whose last entry has no `id` are linear. A message is a
58
+ * `type:"message"` entry with role user or assistant and non-empty text (isPiConversationRecord, 374-383; 511-523).
59
+ */
60
+ export async function scanPiSession(path , readOpts = {}) {
61
+ const r = {
62
+ id: null, cwd: null, startedAt: null, updatedAt: null, messageCount: 0, visibleUserCount: 0,
63
+ corruptLines: 0, cwdOffsetBytes: 0, cwdReadable: false, subagent: false,
64
+ };
65
+ let sawSession = false;
66
+ const entries = [];
67
+ const totals = await scanJsonl(path, readOpts, (o, info) => {
68
+ if (!sawSession && o.type === "session") {
69
+ sawSession = true;
70
+ r.id = str(o.id) || null;
71
+ }
72
+ if (!r.cwd) {
73
+ const payload = obj(o.payload);
74
+ const top = typeof o.cwd === "string" && o.cwd.trim() !== "" ? o.cwd : null;
75
+ const nested = payload && typeof payload.cwd === "string" && payload.cwd.trim() !== "" ? payload.cwd : null;
76
+ const cwd = top ?? nested;
77
+ if (cwd !== null) {
78
+ r.cwd = cwd;
79
+ r.cwdOffsetBytes = info.offset;
80
+ r.cwdReadable = info.offset <= CWD_SCAN_MAX_BYTES && info.recordIndex <= CWD_SCAN_MAX_RECORDS;
81
+ }
82
+ }
83
+ const ts = isoOrNull(o.timestamp);
84
+ if (ts !== null) {
85
+ r.startedAt ??= ts;
86
+ r.updatedAt = ts;
87
+ }
88
+ if (o.type === "session") return;
89
+ const msg = obj(o.message);
90
+ let kind = 0;
91
+ if (o.type === "message" && msg && (msg.role === "user" || msg.role === "assistant") && extractText(msg.content) !== "") {
92
+ kind = msg.role === "user" ? 2 : 1;
93
+ }
94
+ entries.push({
95
+ id: typeof o.id === "string" ? o.id : undefined,
96
+ parentId: typeof o.parentId === "string" && o.parentId !== "" ? o.parentId : undefined,
97
+ kind,
98
+ });
99
+ });
100
+ r.corruptLines = totals.corruptLines;
101
+ if (r.cwd === null) r.cwdOffsetBytes = totals.totalBytes;
102
+
103
+ const leaf = entries.at(-1);
104
+ let branch ;
105
+ if (leaf === undefined) branch = [];
106
+ else if (leaf.id === undefined) branch = entries;
107
+ else {
108
+ const byId = new Map ();
109
+ for (const e of entries) if (e.id !== undefined) byId.set(e.id, e);
110
+ branch = [];
111
+ for (let e = leaf; e !== undefined && branch.length < entries.length;
112
+ e = e.parentId !== undefined ? byId.get(e.parentId) : undefined) branch.push(e);
113
+ }
114
+ for (const e of branch) {
115
+ if (e.kind === 0) continue;
116
+ r.messageCount++;
117
+ if (e.kind === 2) r.visibleUserCount++;
118
+ }
119
+ return r;
120
+ }
121
+
122
+ export function createPiAdapter(opts = {}) {
123
+ return createNativeAdapter({
124
+ id: "pi",
125
+ cacheFile: "pi-discovery.json",
126
+ root: piSessionsDir,
127
+ files,
128
+ scan: scanPiSession,
129
+ stemFallback: true,
130
+ }, opts);
131
+ }
132
+
133
+ export const piAdapter = createPiAdapter();