tryharness 0.7.31 → 0.7.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,245 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { spawn } from "node:child_process";
4
+ import { randomBytes } from "node:crypto";
5
+ import { run } from "./commands.mjs";
6
+ import { listJsonl } from "./files.mjs";
7
+ import { parseSessionFile } from "./parsers.mjs";
8
+ import { historyRoots } from "./paths.mjs";
9
+
10
+ export function createSessionIndex({
11
+ store,
12
+ detected,
13
+ installedAgents,
14
+ state,
15
+ saveStatus,
16
+ log,
17
+ }) {
18
+ const opencodeExecutable =
19
+ detected.find((entry) => entry.agent === "opencode")?.path || null;
20
+ let opencodeProcess = null;
21
+ let opencodeBase = null;
22
+ let opencodeStarting = null;
23
+ let opencodeAuthorization = null;
24
+ function ensureOpencodeHelper() {
25
+ if (!opencodeExecutable) return Promise.resolve(null);
26
+ if (opencodeProcess && opencodeBase && opencodeAuthorization) {
27
+ return Promise.resolve({
28
+ base: opencodeBase,
29
+ authorization: opencodeAuthorization,
30
+ });
31
+ }
32
+ if (opencodeStarting) return opencodeStarting;
33
+ opencodeStarting = new Promise((resolve) => {
34
+ const username = "tryharness";
35
+ const password = randomBytes(32).toString("base64url");
36
+ const authorization =
37
+ "Basic " + Buffer.from(`${username}:${password}`).toString("base64");
38
+ const child = spawn(
39
+ opencodeExecutable,
40
+ ["serve", "--port", "0", "--hostname", "127.0.0.1", "--pure"],
41
+ {
42
+ stdio: ["ignore", "pipe", "pipe"],
43
+ env: {
44
+ ...process.env,
45
+ OPENCODE_SERVER_USERNAME: username,
46
+ OPENCODE_SERVER_PASSWORD: password,
47
+ },
48
+ }
49
+ );
50
+ opencodeProcess = child;
51
+ let output = "";
52
+ let settled = false;
53
+ const finish = (value) => {
54
+ if (settled) return;
55
+ settled = true;
56
+ clearTimeout(timer);
57
+ opencodeStarting = null;
58
+ resolve(value);
59
+ };
60
+ const inspect = (chunk) => {
61
+ output = (output + String(chunk)).slice(-4_000);
62
+ const match = output.match(
63
+ /opencode server listening on (http:\/\/127\.0\.0\.1:\d+)/
64
+ );
65
+ if (!match) return;
66
+ opencodeBase = match[1];
67
+ opencodeAuthorization = authorization;
68
+ finish({ base: opencodeBase, authorization });
69
+ };
70
+ child.stdout.on("data", inspect);
71
+ child.stderr.on("data", inspect);
72
+ child.on("error", (error) => {
73
+ log(`opencode helper failed: ${error.message}`);
74
+ finish(null);
75
+ });
76
+ child.on("exit", (code) => {
77
+ if (code && code !== 0) log(`opencode helper exited with code ${code}`);
78
+ if (opencodeProcess === child) {
79
+ opencodeProcess = null;
80
+ opencodeBase = null;
81
+ opencodeAuthorization = null;
82
+ }
83
+ finish(null);
84
+ });
85
+ const timer = setTimeout(() => {
86
+ log("opencode helper did not become ready in 5 seconds");
87
+ try {
88
+ child.kill();
89
+ } catch {}
90
+ finish(null);
91
+ }, 5_000);
92
+ });
93
+ return opencodeStarting;
94
+ }
95
+
96
+ let syncRunning = false;
97
+ let syncAgain = false;
98
+ let targetedOpencode = [];
99
+ async function indexFile(agent, item) {
100
+ const sessionId = path.basename(item.file);
101
+ if (!store.needsIndex(agent, sessionId, item.mtime, item.size))
102
+ return false;
103
+ const parsed = await parseSessionFile(agent, item.file);
104
+ store.indexParsed({
105
+ agent,
106
+ sessionId,
107
+ source: item.file,
108
+ parsed,
109
+ mtime: item.mtime,
110
+ size: item.size,
111
+ });
112
+ return true;
113
+ }
114
+
115
+ async function readOpencodeSession(sessionId, cwd) {
116
+ const query = cwd ? `?directory=${encodeURIComponent(cwd)}` : "";
117
+ try {
118
+ const helper = await ensureOpencodeHelper();
119
+ if (!helper) return false;
120
+ const headers = { authorization: helper.authorization };
121
+ const infoResponse = await fetch(
122
+ `${helper.base}/session/${encodeURIComponent(sessionId)}${query}`,
123
+ { headers, signal: AbortSignal.timeout(5_000) }
124
+ );
125
+ if (!infoResponse.ok) return false;
126
+ const info = await infoResponse.json();
127
+ const updated = info?.updated ?? info?.time?.updated;
128
+ const parsedMtime =
129
+ typeof updated === "number"
130
+ ? updated
131
+ : typeof updated === "string"
132
+ ? Date.parse(updated)
133
+ : NaN;
134
+ const mtime = Number.isFinite(parsedMtime) ? parsedMtime : Date.now();
135
+ if (!store.needsIndex("opencode", sessionId, mtime, 0)) return false;
136
+ const messagesResponse = await fetch(
137
+ `${helper.base}/session/${encodeURIComponent(sessionId)}/message${query}`,
138
+ { headers, signal: AbortSignal.timeout(15_000) }
139
+ );
140
+ if (!messagesResponse.ok) return false;
141
+ const messages = await messagesResponse.json();
142
+ const raw = JSON.stringify({ info, messages });
143
+ store.indexRaw({
144
+ agent: "opencode",
145
+ sessionId,
146
+ source: `opencode:${sessionId}`,
147
+ raw,
148
+ cwd: cwd || info?.directory,
149
+ mtime,
150
+ size: 0,
151
+ });
152
+ return true;
153
+ } catch {
154
+ return false;
155
+ }
156
+ }
157
+
158
+ async function sync(agentFilter = null) {
159
+ if (syncRunning) {
160
+ syncAgain = true;
161
+ return;
162
+ }
163
+ syncRunning = true;
164
+ state.indexing = true;
165
+ saveStatus();
166
+ try {
167
+ for (const agent of ["claude-code", "codex", "pi"]) {
168
+ if (
169
+ !installedAgents.includes(agent) ||
170
+ (agentFilter && agentFilter !== agent)
171
+ )
172
+ continue;
173
+ const files = historyRoots(agent)
174
+ .flatMap(listJsonl)
175
+ .sort((a, b) => b.mtime - a.mtime);
176
+ for (const item of files) {
177
+ try {
178
+ await indexFile(agent, item);
179
+ } catch (error) {
180
+ log(`index ${agent} ${item.file}: ${error.message}`);
181
+ }
182
+ await new Promise((resolve) => setImmediate(resolve));
183
+ }
184
+ }
185
+ if (
186
+ installedAgents.includes("opencode") &&
187
+ (!agentFilter || agentFilter === "opencode")
188
+ ) {
189
+ const requested = targetedOpencode.splice(0);
190
+ if (requested.length) {
191
+ for (const item of requested)
192
+ await readOpencodeSession(item.sessionId, item.cwd);
193
+ } else {
194
+ const listed = run(
195
+ "opencode",
196
+ ["session", "list", "--format", "json"],
197
+ { timeout: 20_000, maxBuffer: 20_000_000 }
198
+ );
199
+ if (listed.ok) {
200
+ let rows = [];
201
+ try {
202
+ rows = JSON.parse(listed.stdout);
203
+ } catch {}
204
+ for (const row of Array.isArray(rows) ? rows : [])
205
+ if (row?.id) await readOpencodeSession(row.id, row.directory);
206
+ }
207
+ }
208
+ }
209
+ state.lastIndexedAt = new Date().toISOString();
210
+ state.lastError = null;
211
+ } catch (error) {
212
+ state.lastError = error.message;
213
+ log(`sync failed: ${error.stack || error.message}`);
214
+ } finally {
215
+ state.indexing = false;
216
+ syncRunning = false;
217
+ saveStatus();
218
+ if (syncAgain) {
219
+ syncAgain = false;
220
+ setImmediate(() => void sync());
221
+ }
222
+ }
223
+ }
224
+
225
+ function sourceRaw(agent, sessionId) {
226
+ const row = store.findSource(agent, sessionId);
227
+ if (!row?.source || row.source.startsWith("opencode:")) return null;
228
+ // Compatibility fetches are explicit reads. Return the complete source instead of
229
+ // silently changing their meaning to "the last N bytes"; normal 0.4 search/read
230
+ // traffic is served from the normalized SQLite transcript and never ships raw logs.
231
+ try {
232
+ return {
233
+ raw: fs.readFileSync(row.source, "utf8"),
234
+ cwd: row.cwd || undefined,
235
+ };
236
+ } catch {
237
+ return null;
238
+ }
239
+ }
240
+
241
+ const target = (request) => targetedOpencode.push(request);
242
+ const stop = () => opencodeProcess?.kill();
243
+
244
+ return { sync, sourceRaw, target, stop };
245
+ }