@openclaw/opencode-provider 0.0.0 → 2026.8.1-beta.2

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,409 @@
1
+ import { isRecord, normalizeBoundedOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
2
+ import process from "node:process";
3
+ import { spawn } from "node:child_process";
4
+ import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
5
+ import { materializeWindowsSpawnProgram, resolveWindowsSpawnProgram } from "openclaw/plugin-sdk/windows-spawn";
6
+ //#region extensions/opencode/session-catalog.ts
7
+ const LOCAL_HOST_ID = "gateway";
8
+ const DEFAULT_PAGE_LIMIT = 20;
9
+ const MAX_PAGE_LIMIT = 100;
10
+ const MAX_SEARCH_LENGTH = 500;
11
+ const MAX_CURSOR_LENGTH = 128;
12
+ const MAX_CLI_LIST_SESSIONS = 1e4;
13
+ const MAX_CLI_OUTPUT_BYTES = 32 * 1024 * 1024;
14
+ const MAX_TRANSCRIPT_ITEM_BYTES = 512 * 1024;
15
+ const MAX_TRANSCRIPT_PAGE_BYTES = 20 * 1024 * 1024;
16
+ const CLI_TIMEOUT_MS = 3e4;
17
+ const OPENCODE_QUERY_CACHE_TTL_MS = 32e3;
18
+ const OPENCODE_QUERY_CACHE_MAX_ENTRIES = 32;
19
+ const SESSION_ID_PATTERN = /^(?!-)[A-Za-z0-9._:-]{1,256}$/u;
20
+ const SAFE_ENV_KEYS = [
21
+ "APPDATA",
22
+ "COMSPEC",
23
+ "HOME",
24
+ "LANG",
25
+ "LC_ALL",
26
+ "LOCALAPPDATA",
27
+ "OPENCODE_DB",
28
+ "PATH",
29
+ "Path",
30
+ "PATHEXT",
31
+ "SYSTEMROOT",
32
+ "TEMP",
33
+ "TMP",
34
+ "TMPDIR",
35
+ "USERPROFILE",
36
+ "WINDIR",
37
+ "XDG_CACHE_HOME",
38
+ "XDG_CONFIG_HOME",
39
+ "XDG_DATA_HOME",
40
+ "XDG_STATE_HOME"
41
+ ];
42
+ const openCodeConfigIdentities = /* @__PURE__ */ new WeakMap();
43
+ const openCodeQueryCache = /* @__PURE__ */ new Map();
44
+ let nextOpenCodeConfigIdentity = 1;
45
+ function openCodeQueryCacheKey(query, configIdentity) {
46
+ let identity = openCodeConfigIdentities.get(configIdentity);
47
+ if (identity === void 0) {
48
+ identity = nextOpenCodeConfigIdentity++;
49
+ openCodeConfigIdentities.set(configIdentity, identity);
50
+ }
51
+ const environment = SAFE_ENV_KEYS.map((key) => `${key}=${process.env[key] ?? ""}`).join("\0");
52
+ return `${String(identity)}\0${environment}\0${query}`;
53
+ }
54
+ function boundedLimit(value, fallback = DEFAULT_PAGE_LIMIT) {
55
+ if (value === void 0) return fallback;
56
+ if (!Number.isInteger(value) || Number(value) < 1 || Number(value) > MAX_PAGE_LIMIT) throw new Error(`limit must be an integer between 1 and ${String(MAX_PAGE_LIMIT)}`);
57
+ return Number(value);
58
+ }
59
+ function encodeCursor(offset) {
60
+ return Buffer.from(JSON.stringify({ offset }), "utf8").toString("base64url");
61
+ }
62
+ function optionalRawCursor(value) {
63
+ if (value === void 0) return;
64
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_CURSOR_LENGTH) throw new Error("cursor is invalid");
65
+ return value;
66
+ }
67
+ function decodeCursor(value) {
68
+ const cursor = optionalRawCursor(value);
69
+ if (cursor === void 0) return 0;
70
+ try {
71
+ const bytes = Buffer.from(cursor, "base64url");
72
+ if (bytes.toString("base64url") !== cursor) throw new Error("non-canonical base64url");
73
+ const parsed = JSON.parse(bytes.toString("utf8"));
74
+ if (!isRecord(parsed) || !Number.isSafeInteger(parsed.offset) || Number(parsed.offset) < 0) throw new Error("invalid offset");
75
+ const offset = Number(parsed.offset);
76
+ if (encodeCursor(offset) !== cursor) throw new Error("non-canonical cursor payload");
77
+ return offset;
78
+ } catch (error) {
79
+ throw new Error("cursor is invalid", { cause: error });
80
+ }
81
+ }
82
+ function isExactOpenCodeSessionCursor(value) {
83
+ if (typeof value !== "string") return false;
84
+ try {
85
+ decodeCursor(value);
86
+ return true;
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
91
+ function truncateUtf8(text, maxBytes) {
92
+ if (Buffer.byteLength(text, "utf8") <= maxBytes) return text;
93
+ let low = 0;
94
+ let high = text.length;
95
+ while (low < high) {
96
+ const middle = Math.ceil((low + high) / 2);
97
+ if (Buffer.byteLength(text.slice(0, middle), "utf8") <= maxBytes - 3) low = middle;
98
+ else high = middle - 1;
99
+ }
100
+ const end = low > 0 && /[\uD800-\uDBFF]/u.test(text.charAt(low - 1)) ? low - 1 : low;
101
+ return `${text.slice(0, end)}…`;
102
+ }
103
+ function transcriptPage(items, limit, offset) {
104
+ const end = Math.max(0, items.length - offset);
105
+ const start = Math.max(0, end - limit);
106
+ const page = [];
107
+ let pageBytes = 2;
108
+ for (let index = end - 1; index >= start; index -= 1) {
109
+ const item = items[index];
110
+ if (!item) continue;
111
+ const bounded = {
112
+ ...item,
113
+ text: truncateUtf8(item.text ?? "", MAX_TRANSCRIPT_ITEM_BYTES)
114
+ };
115
+ const itemBytes = Buffer.byteLength(JSON.stringify(bounded), "utf8") + 1;
116
+ if (page.length > 0 && pageBytes + itemBytes > MAX_TRANSCRIPT_PAGE_BYTES) break;
117
+ page.unshift(bounded);
118
+ pageBytes += itemBytes;
119
+ }
120
+ const consumed = offset + page.length;
121
+ return {
122
+ items: page,
123
+ ...consumed < items.length ? { nextCursor: encodeCursor(consumed) } : {}
124
+ };
125
+ }
126
+ function parseListParams(value) {
127
+ if (value === void 0 || value === null) return { limit: DEFAULT_PAGE_LIMIT };
128
+ if (!isRecord(value)) throw new Error("OpenCode session list parameters must be an object");
129
+ const unknown = Object.keys(value).find((key) => ![
130
+ "searchTerm",
131
+ "limit",
132
+ "cursor"
133
+ ].includes(key));
134
+ if (unknown) throw new Error(`unknown OpenCode session list parameter: ${unknown}`);
135
+ const searchTerm = normalizeBoundedOptionalString(value.searchTerm, MAX_SEARCH_LENGTH);
136
+ if (value.searchTerm !== void 0 && !searchTerm) throw new Error("searchTerm is invalid");
137
+ const cursor = optionalRawCursor(value.cursor);
138
+ return {
139
+ limit: boundedLimit(value.limit),
140
+ ...searchTerm ? { searchTerm } : {},
141
+ ...cursor ? { cursor } : {}
142
+ };
143
+ }
144
+ function parseReadParams(value) {
145
+ if (!isRecord(value)) throw new Error("OpenCode session read parameters must be an object");
146
+ const unknown = Object.keys(value).find((key) => ![
147
+ "threadId",
148
+ "limit",
149
+ "cursor"
150
+ ].includes(key));
151
+ if (unknown) throw new Error(`unknown OpenCode session read parameter: ${unknown}`);
152
+ const threadId = normalizeBoundedOptionalString(value.threadId, 256);
153
+ if (!threadId || !SESSION_ID_PATTERN.test(threadId)) throw new Error("threadId is invalid");
154
+ const cursor = optionalRawCursor(value.cursor);
155
+ return {
156
+ threadId,
157
+ limit: boundedLimit(value.limit),
158
+ ...cursor ? { cursor } : {}
159
+ };
160
+ }
161
+ function resolveSpawnInvocation(args) {
162
+ return materializeWindowsSpawnProgram(resolveWindowsSpawnProgram({
163
+ command: "opencode",
164
+ platform: process.platform,
165
+ env: process.env,
166
+ execPath: process.execPath,
167
+ packageName: "opencode-ai"
168
+ }), args);
169
+ }
170
+ async function runOpenCode(args) {
171
+ const invocation = resolveSpawnInvocation(args);
172
+ const env = {
173
+ OPENCODE_PURE: "1",
174
+ NO_COLOR: "1"
175
+ };
176
+ for (const key of SAFE_ENV_KEYS) if (process.env[key] !== void 0) env[key] = process.env[key];
177
+ const child = spawn(invocation.command, invocation.argv, {
178
+ env,
179
+ shell: invocation.shell,
180
+ windowsHide: invocation.windowsHide,
181
+ stdio: [
182
+ "ignore",
183
+ "pipe",
184
+ "pipe"
185
+ ]
186
+ });
187
+ const stdout = [];
188
+ const stderr = [];
189
+ let bytes = 0;
190
+ let overflow = false;
191
+ const timeout = setTimeout(() => child.kill("SIGKILL"), CLI_TIMEOUT_MS);
192
+ timeout.unref?.();
193
+ let outputError;
194
+ const failFromOutputError = (source, error) => {
195
+ const message = error instanceof Error ? error.message : String(error);
196
+ outputError ??= new Error(`OpenCode ${source} stream failed: ${message}`, { cause: error });
197
+ child.kill("SIGKILL");
198
+ };
199
+ const collect = (target, chunk) => {
200
+ bytes += chunk.length;
201
+ if (bytes > MAX_CLI_OUTPUT_BYTES) {
202
+ overflow = true;
203
+ child.kill("SIGKILL");
204
+ return;
205
+ }
206
+ target.push(chunk);
207
+ };
208
+ child.stdout.once("error", (error) => failFromOutputError("stdout", error));
209
+ child.stderr.once("error", (error) => failFromOutputError("stderr", error));
210
+ child.stdout.on("data", (chunk) => collect(stdout, chunk));
211
+ child.stderr.on("data", (chunk) => collect(stderr, chunk));
212
+ const exitCode = await new Promise((resolve, reject) => {
213
+ child.on("error", reject);
214
+ child.on("close", resolve);
215
+ }).finally(() => clearTimeout(timeout));
216
+ if (overflow) throw new Error("OpenCode session output exceeded the safety limit");
217
+ if (outputError) throw outputError;
218
+ if (exitCode !== 0) {
219
+ const detail = Buffer.concat(stderr).toString("utf8").trim();
220
+ throw new Error(detail || `OpenCode exited with code ${String(exitCode)}`);
221
+ }
222
+ return Buffer.concat(stdout).toString("utf8");
223
+ }
224
+ async function queryOpenCodeDatabase(query) {
225
+ const output = await runOpenCode([
226
+ "--pure",
227
+ "db",
228
+ query,
229
+ "--format",
230
+ "json"
231
+ ]);
232
+ return output.trim() ? JSON.parse(output) : [];
233
+ }
234
+ async function queryCachedOpenCodeSessions(query, options) {
235
+ const key = openCodeQueryCacheKey(query, options.configIdentity ?? process.env);
236
+ const cached = openCodeQueryCache.get(key);
237
+ if (options.forceRefresh !== true && cached && cached.expiresAt > Date.now()) {
238
+ openCodeQueryCache.delete(key);
239
+ openCodeQueryCache.set(key, cached);
240
+ return await cached.result;
241
+ }
242
+ if (cached) openCodeQueryCache.delete(key);
243
+ const result = queryOpenCodeDatabase(query);
244
+ const entry = {
245
+ expiresAt: Date.now() + OPENCODE_QUERY_CACHE_TTL_MS,
246
+ result
247
+ };
248
+ openCodeQueryCache.set(key, entry);
249
+ while (openCodeQueryCache.size > OPENCODE_QUERY_CACHE_MAX_ENTRIES) {
250
+ const oldest = openCodeQueryCache.keys().next();
251
+ if (oldest.done) break;
252
+ openCodeQueryCache.delete(oldest.value);
253
+ }
254
+ try {
255
+ const value = await result;
256
+ entry.resolved = true;
257
+ return value;
258
+ } catch (error) {
259
+ if (openCodeQueryCache.get(key) === entry) if (cached?.resolved) openCodeQueryCache.set(key, cached);
260
+ else openCodeQueryCache.delete(key);
261
+ throw error;
262
+ }
263
+ }
264
+ async function exportOpenCodeSession(threadId) {
265
+ const output = await runOpenCode([
266
+ "--pure",
267
+ "export",
268
+ threadId
269
+ ]);
270
+ return JSON.parse(output);
271
+ }
272
+ function parseOpenCodeSession(value) {
273
+ if (!isRecord(value)) return;
274
+ const threadId = normalizeBoundedOptionalString(value.id, 256);
275
+ if (!threadId || !SESSION_ID_PATTERN.test(threadId)) return;
276
+ const name = normalizeBoundedOptionalString(value.title, 1e3);
277
+ const cwd = normalizeBoundedOptionalString(value.directory, 4096);
278
+ const createdAt = typeof value.created === "number" && Number.isFinite(value.created) ? value.created : void 0;
279
+ const updatedAt = typeof value.updated === "number" && Number.isFinite(value.updated) ? value.updated : void 0;
280
+ return {
281
+ threadId,
282
+ ...name ? { name } : {},
283
+ ...cwd ? { cwd } : {},
284
+ status: "stored",
285
+ ...createdAt !== void 0 ? { createdAt } : {},
286
+ ...updatedAt !== void 0 ? {
287
+ updatedAt,
288
+ recencyAt: updatedAt
289
+ } : {},
290
+ source: "opencode-cli",
291
+ modelProvider: "opencode",
292
+ archived: false,
293
+ canContinue: true,
294
+ canArchive: false
295
+ };
296
+ }
297
+ async function listLocalOpenCodeSessionPage(value, options = {}) {
298
+ const params = parseListParams(value);
299
+ const offset = decodeCursor(params.cursor);
300
+ const requestedCount = params.searchTerm ? MAX_CLI_LIST_SESSIONS : Math.min(MAX_CLI_LIST_SESSIONS, offset + params.limit + 1);
301
+ const parsed = await queryCachedOpenCodeSessions([
302
+ "SELECT id, title, time_created AS created, time_updated AS updated,",
303
+ "project_id AS projectId, directory FROM session",
304
+ "WHERE parent_id IS NULL AND time_archived IS NULL",
305
+ `ORDER BY time_updated DESC, id DESC LIMIT ${String(requestedCount)}`
306
+ ].join(" "), options);
307
+ if (!Array.isArray(parsed) || parsed.length > MAX_CLI_LIST_SESSIONS) throw new Error("OpenCode returned an invalid session list");
308
+ const needle = params.searchTerm?.toLocaleLowerCase();
309
+ const sessions = parsed.flatMap((entry) => {
310
+ const session = parseOpenCodeSession(entry);
311
+ return session ? [session] : [];
312
+ }).filter((session) => {
313
+ if (!needle) return true;
314
+ return [
315
+ session.threadId,
316
+ session.name,
317
+ session.cwd
318
+ ].some((field) => field?.toLocaleLowerCase().includes(needle));
319
+ });
320
+ const page = sessions.slice(offset, offset + params.limit);
321
+ return {
322
+ sessions: page,
323
+ ...offset + page.length < sessions.length ? { nextCursor: encodeCursor(offset + page.length) } : {}
324
+ };
325
+ }
326
+ function jsonText(value, maxLength = 2e4) {
327
+ try {
328
+ const text = JSON.stringify(value);
329
+ return text.length > maxLength ? `${truncateUtf16Safe(text, maxLength)}…` : text;
330
+ } catch {
331
+ return;
332
+ }
333
+ }
334
+ function timestampFromInfo(info) {
335
+ if (!isRecord(info.time) || typeof info.time.created !== "number") return;
336
+ const date = new Date(info.time.created);
337
+ return Number.isNaN(date.getTime()) ? void 0 : date.toISOString();
338
+ }
339
+ function openCodeTranscriptItems(value) {
340
+ if (!isRecord(value) || !Array.isArray(value.messages)) throw new Error("OpenCode returned an invalid session export");
341
+ return value.messages.flatMap((message) => {
342
+ if (!isRecord(message) || !isRecord(message.info) || !Array.isArray(message.parts)) return [];
343
+ const info = message.info;
344
+ const role = info.role;
345
+ const messageId = normalizeBoundedOptionalString(info.id, 256);
346
+ const timestamp = timestampFromInfo(info);
347
+ const modelId = role === "assistant" ? normalizeBoundedOptionalString(info.modelID, 256) : isRecord(info.model) ? normalizeBoundedOptionalString(info.model.modelID, 256) : void 0;
348
+ const providerId = role === "assistant" ? normalizeBoundedOptionalString(info.providerID, 256) : isRecord(info.model) ? normalizeBoundedOptionalString(info.model.providerID, 256) : void 0;
349
+ const model = providerId && modelId ? `${providerId}/${modelId}` : modelId;
350
+ return message.parts.flatMap((part, partIndex) => {
351
+ if (!isRecord(part)) return [];
352
+ const id = normalizeBoundedOptionalString(part.id, 256) ?? (messageId ? `${messageId}:${String(partIndex)}` : void 0);
353
+ const common = {
354
+ ...id ? { id } : {},
355
+ ...timestamp ? { timestamp } : {},
356
+ ...model ? { model } : {}
357
+ };
358
+ if (part.type === "text" && typeof part.text === "string") return [{
359
+ ...common,
360
+ type: role === "user" ? "userMessage" : "agentMessage",
361
+ text: part.text
362
+ }];
363
+ if (part.type === "reasoning" && typeof part.text === "string") return [{
364
+ ...common,
365
+ type: "reasoning",
366
+ text: part.text
367
+ }];
368
+ if (part.type === "tool") {
369
+ const tool = normalizeBoundedOptionalString(part.tool, 256) ?? "tool";
370
+ const state = isRecord(part.state) ? part.state : void 0;
371
+ const callText = state && "input" in state ? jsonText(state.input) : void 0;
372
+ const resultText = state?.status === "completed" && typeof state.output === "string" ? state.output : state?.status === "error" && typeof state.error === "string" ? state.error : void 0;
373
+ return [{
374
+ ...common,
375
+ type: "toolCall",
376
+ text: callText ? `${tool}\n${callText}` : tool
377
+ }, ...resultText ? [{
378
+ ...common,
379
+ ...id ? { id: `${id}:result` } : {},
380
+ type: "toolResult",
381
+ text: resultText
382
+ }] : []];
383
+ }
384
+ if (part.type === "file") {
385
+ const filename = normalizeBoundedOptionalString(part.filename, 1e3);
386
+ const mime = normalizeBoundedOptionalString(part.mime, 256);
387
+ return [{
388
+ ...common,
389
+ type: "other",
390
+ text: `[Attachment${filename ? `: ${filename}` : ""}${mime ? ` (${mime})` : ""}]`
391
+ }];
392
+ }
393
+ return [];
394
+ });
395
+ });
396
+ }
397
+ async function readLocalOpenCodeTranscriptPage(value) {
398
+ const params = parseReadParams(value);
399
+ const offset = decodeCursor(params.cursor);
400
+ const page = transcriptPage(openCodeTranscriptItems(await exportOpenCodeSession(params.threadId)), params.limit, offset);
401
+ return {
402
+ hostId: LOCAL_HOST_ID,
403
+ label: "Local OpenCode",
404
+ threadId: params.threadId,
405
+ ...page
406
+ };
407
+ }
408
+ //#endregion
409
+ export { exportOpenCodeSession, isExactOpenCodeSessionCursor, listLocalOpenCodeSessionPage, queryOpenCodeDatabase, readLocalOpenCodeTranscriptPage };
@@ -0,0 +1,232 @@
1
+ import { OPENCODE_SESSION_ID_PATTERN } from "./session-catalog-shared.js";
2
+ import { exportOpenCodeSession, queryOpenCodeDatabase } from "./session-catalog.js";
3
+ import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
4
+ import { isExternalUserText, normalizeUserText } from "openclaw/plugin-sdk/session-catalog";
5
+ //#region extensions/opencode/session-upstream-activity.ts
6
+ const OPENCODE_EXPORT_CONCURRENCY = 4;
7
+ const OPENCODE_REPLAY_LOOKBACK_USER_MESSAGES = 50;
8
+ const OPENCODE_SHELL_SENTINEL = "The following tool was executed by the user";
9
+ async function mapConcurrent(values, limit, mapper) {
10
+ const results = [];
11
+ results.length = values.length;
12
+ let nextIndex = 0;
13
+ const workers = Array.from({ length: Math.min(limit, values.length) }, async () => {
14
+ while (nextIndex < values.length) {
15
+ const index = nextIndex++;
16
+ results[index] = await mapper(values[index]);
17
+ }
18
+ });
19
+ await Promise.all(workers);
20
+ return results;
21
+ }
22
+ function sqlString(value) {
23
+ return `'${value.replaceAll("'", "''")}'`;
24
+ }
25
+ function readProbeThreadId(probe) {
26
+ if (probe.hostId !== "gateway" || probe.upstreamKind !== "opencode-cli" || !isRecord(probe.upstreamRef) || probe.upstreamRef.threadId !== probe.threadId || !OPENCODE_SESSION_ID_PATTERN.test(probe.threadId)) return;
27
+ return probe.threadId;
28
+ }
29
+ function readMarker(probe) {
30
+ if (!isRecord(probe.marker)) return;
31
+ return Number.isSafeInteger(probe.marker.seq) && Number(probe.marker.seq) >= 0 && (probe.marker.lastHumanMessageId === null || typeof probe.marker.lastHumanMessageId === "string") ? {
32
+ seq: Number(probe.marker.seq),
33
+ lastHumanMessageId: probe.marker.lastHumanMessageId
34
+ } : void 0;
35
+ }
36
+ async function readIndicators(threadIds) {
37
+ if (threadIds.length === 0) return /* @__PURE__ */ new Map();
38
+ const value = await queryOpenCodeDatabase([
39
+ "SELECT s.id AS id, es.seq AS seq",
40
+ "FROM session AS s",
41
+ "LEFT JOIN event_sequence AS es ON es.aggregate_id = s.id",
42
+ `WHERE s.id IN (${threadIds.map(sqlString).join(", ")})`
43
+ ].join(" "));
44
+ if (!Array.isArray(value)) throw new Error("OpenCode returned invalid upstream indicators");
45
+ const indicators = /* @__PURE__ */ new Map();
46
+ for (const row of value) {
47
+ const seq = isRecord(row) && row.seq === null ? 0 : isRecord(row) ? row.seq : void 0;
48
+ if (!isRecord(row) || typeof row.id !== "string" || !OPENCODE_SESSION_ID_PATTERN.test(row.id) || !Number.isSafeInteger(seq) || Number(seq) < 0) throw new Error("OpenCode returned invalid upstream indicators");
49
+ indicators.set(row.id, {
50
+ threadId: row.id,
51
+ seq: Number(seq)
52
+ });
53
+ }
54
+ return indicators;
55
+ }
56
+ function readExportPart(value) {
57
+ if (!isRecord(value) || typeof value.type !== "string") return;
58
+ const sourceText = isRecord(value.source) && isRecord(value.source.text) && typeof value.source.text.value === "string" && typeof value.source.text.start === "number" && Number.isFinite(value.source.text.start) && typeof value.source.text.end === "number" && Number.isFinite(value.source.text.end) ? {
59
+ value: value.source.text.value,
60
+ start: value.source.text.start,
61
+ end: value.source.text.end
62
+ } : void 0;
63
+ return {
64
+ type: value.type,
65
+ ...typeof value.text === "string" ? { text: value.text } : {},
66
+ ...typeof value.synthetic === "boolean" ? { synthetic: value.synthetic } : {},
67
+ ...typeof value.ignored === "boolean" ? { ignored: value.ignored } : {},
68
+ ...isRecord(value.metadata) ? { metadata: value.metadata } : {},
69
+ ...typeof value.mime === "string" ? { mime: value.mime } : {},
70
+ ...typeof value.filename === "string" ? { filename: value.filename } : {},
71
+ ...sourceText ? { sourceText } : {}
72
+ };
73
+ }
74
+ function visibleTextPart(part, sourceRanges) {
75
+ if (part.type !== "text" || part.text === void 0 || part.synthetic === true || part.ignored === true || part.metadata?.compaction_continue === true) return;
76
+ let text = part.text;
77
+ for (const source of sourceRanges) if (Number.isInteger(source.start) && Number.isInteger(source.end) && source.start >= 0 && source.end >= source.start && source.end <= text.length && text.slice(source.start, source.end) === source.value) text = text.slice(0, source.start) + text.slice(source.end);
78
+ return text;
79
+ }
80
+ function messageSourceRanges(message) {
81
+ return message.parts.flatMap((part) => part.sourceText ? [part.sourceText] : []).toSorted((left, right) => right.start - left.start);
82
+ }
83
+ function visibleTextParts(message) {
84
+ const sourceRanges = messageSourceRanges(message);
85
+ return message.parts.flatMap((part) => {
86
+ const text = visibleTextPart(part, sourceRanges);
87
+ return text === void 0 ? [] : [text];
88
+ });
89
+ }
90
+ function readExportMessages(value) {
91
+ if (!isRecord(value) || !Array.isArray(value.messages)) throw new Error("OpenCode returned an invalid session export");
92
+ return value.messages.flatMap((message) => {
93
+ if (!isRecord(message) || !isRecord(message.info) || !Array.isArray(message.parts)) return [];
94
+ const id = message.info.id;
95
+ const role = message.info.role;
96
+ if (typeof id !== "string" || typeof role !== "string") return [];
97
+ const createdAt = isRecord(message.info.time) && typeof message.info.time.created === "number" && Number.isFinite(message.info.time.created) ? message.info.time.created : void 0;
98
+ return [{
99
+ id,
100
+ role,
101
+ parts: message.parts.flatMap((part) => {
102
+ const parsed = readExportPart(part);
103
+ return parsed ? [parsed] : [];
104
+ }),
105
+ ...createdAt === void 0 ? {} : { createdAt }
106
+ }];
107
+ }).toSorted((left, right) => (left.createdAt ?? Number.NEGATIVE_INFINITY) - (right.createdAt ?? Number.NEGATIVE_INFINITY) || left.id.localeCompare(right.id));
108
+ }
109
+ function normalizedMessageText(message) {
110
+ if (message.role !== "user") return;
111
+ const sourceRanges = messageSourceRanges(message);
112
+ const texts = message.parts.flatMap((part) => {
113
+ const visibleText = visibleTextPart(part, sourceRanges);
114
+ if (visibleText !== void 0) return [visibleText];
115
+ if (part.type === "file" && part.mime !== void 0 && (part.mime.startsWith("image/") || part.mime === "application/pdf")) return [`[Attached ${part.mime}: ${part.filename ?? "file"}]`];
116
+ return [];
117
+ });
118
+ return texts.length > 0 ? normalizeUserText(texts.join("\n")) : void 0;
119
+ }
120
+ function directHumanText(message) {
121
+ if (message.role !== "user" || message.parts.some((part) => part.type === "compaction") || message.parts.some((part) => part.metadata?.compaction_continue === true)) return;
122
+ const texts = visibleTextParts(message);
123
+ if (texts.length === 0) return;
124
+ const text = normalizeUserText(texts.join("\n"));
125
+ return !text || text === OPENCODE_SHELL_SENTINEL ? void 0 : text;
126
+ }
127
+ function latestMessageId(current, candidate) {
128
+ return current === null || candidate > current ? candidate : current;
129
+ }
130
+ function latestBaselineHumanMessageId(messages) {
131
+ let latest = null;
132
+ for (const message of messages) if (directHumanText(message) !== void 0) latest = latestMessageId(latest, message.id);
133
+ return latest;
134
+ }
135
+ function classifyExport(params) {
136
+ let humanTurns = 0;
137
+ let occurredAt;
138
+ let lastHumanMessageId = params.marker.lastHumanMessageId;
139
+ let latestExternalMessageId;
140
+ const earlierUserTexts = [];
141
+ for (const message of params.messages) {
142
+ const text = directHumanText(message);
143
+ const replay = text !== void 0 && earlierUserTexts.slice(-50).includes(text);
144
+ const newerThanMarker = params.marker.lastHumanMessageId === null || message.id > params.marker.lastHumanMessageId;
145
+ if (text !== void 0 && message.createdAt !== void 0 && newerThanMarker) lastHumanMessageId = latestMessageId(lastHumanMessageId, message.id);
146
+ if (text !== void 0 && !replay && message.createdAt !== void 0 && newerThanMarker && isExternalUserText(params.probe, text)) {
147
+ humanTurns += 1;
148
+ occurredAt = Math.max(occurredAt ?? 0, message.createdAt);
149
+ latestExternalMessageId = message.id;
150
+ }
151
+ if (message.role === "user") {
152
+ earlierUserTexts.push(normalizedMessageText(message));
153
+ if (earlierUserTexts.length > OPENCODE_REPLAY_LOOKBACK_USER_MESSAGES) earlierUserTexts.shift();
154
+ }
155
+ }
156
+ const nextMarker = {
157
+ seq: params.seq,
158
+ lastHumanMessageId
159
+ };
160
+ return {
161
+ kind: "activity",
162
+ sessionKey: params.probe.sessionKey,
163
+ humanTurns,
164
+ nextMarker,
165
+ ...humanTurns > 0 ? {
166
+ occurredAt: occurredAt ?? Date.now(),
167
+ dedupeId: latestExternalMessageId ?? String(params.seq)
168
+ } : {}
169
+ };
170
+ }
171
+ async function linkContinuedOpenCodeSession(sessionKey, threadId) {
172
+ try {
173
+ const indicator = (await readIndicators([threadId])).get(threadId);
174
+ if (!indicator) return { sessionKey };
175
+ const messages = readExportMessages(await exportOpenCodeSession(threadId));
176
+ return {
177
+ sessionKey,
178
+ upstream: {
179
+ kind: "opencode-cli",
180
+ ref: { threadId },
181
+ marker: {
182
+ seq: indicator.seq,
183
+ lastHumanMessageId: latestBaselineHumanMessageId(messages)
184
+ }
185
+ }
186
+ };
187
+ } catch {
188
+ return { sessionKey };
189
+ }
190
+ }
191
+ async function classifyChangedProbe(probe, indicator) {
192
+ const marker = readMarker(probe);
193
+ if (!marker || indicator.seq === marker.seq) return;
194
+ if (indicator.seq < marker.seq) return {
195
+ kind: "activity",
196
+ sessionKey: probe.sessionKey,
197
+ humanTurns: 0,
198
+ nextMarker: {
199
+ seq: indicator.seq,
200
+ lastHumanMessageId: marker.lastHumanMessageId
201
+ }
202
+ };
203
+ return classifyExport({
204
+ probe,
205
+ marker,
206
+ seq: indicator.seq,
207
+ messages: readExportMessages(await exportOpenCodeSession(probe.threadId))
208
+ });
209
+ }
210
+ async function checkOpenCodeUpstreamActivity(probes) {
211
+ const eligible = probes.flatMap((probe) => readProbeThreadId(probe) ? [probe] : []);
212
+ let indicators;
213
+ try {
214
+ indicators = await readIndicators([...new Set(eligible.map((probe) => probe.threadId))]);
215
+ } catch {
216
+ return [];
217
+ }
218
+ return (await mapConcurrent(eligible, OPENCODE_EXPORT_CONCURRENCY, async (probe) => {
219
+ const indicator = indicators.get(probe.threadId);
220
+ if (!indicator) return {
221
+ kind: "missing",
222
+ sessionKey: probe.sessionKey
223
+ };
224
+ try {
225
+ return await classifyChangedProbe(probe, indicator);
226
+ } catch {
227
+ return;
228
+ }
229
+ })).filter((outcome) => outcome !== void 0);
230
+ }
231
+ //#endregion
232
+ export { checkOpenCodeUpstreamActivity, linkContinuedOpenCodeSession };