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

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.
@@ -1,22 +1,18 @@
1
+ import { OPENCODE_SESSION_ID_PATTERN } from "./session-catalog-shared.js";
1
2
  import { isRecord, normalizeBoundedOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
2
3
  import process from "node:process";
3
- import { spawn } from "node:child_process";
4
+ import { sessionCatalogPaging } from "openclaw/plugin-sdk/session-catalog";
5
+ import { runCommandBuffered } from "openclaw/plugin-sdk/process-runtime";
4
6
  import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
5
7
  import { materializeWindowsSpawnProgram, resolveWindowsSpawnProgram } from "openclaw/plugin-sdk/windows-spawn";
6
8
  //#region extensions/opencode/session-catalog.ts
7
9
  const LOCAL_HOST_ID = "gateway";
8
- const DEFAULT_PAGE_LIMIT = 20;
9
- const MAX_PAGE_LIMIT = 100;
10
10
  const MAX_SEARCH_LENGTH = 500;
11
- const MAX_CURSOR_LENGTH = 128;
12
11
  const MAX_CLI_LIST_SESSIONS = 1e4;
13
12
  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
13
  const CLI_TIMEOUT_MS = 3e4;
17
14
  const OPENCODE_QUERY_CACHE_TTL_MS = 32e3;
18
15
  const OPENCODE_QUERY_CACHE_MAX_ENTRIES = 32;
19
- const SESSION_ID_PATTERN = /^(?!-)[A-Za-z0-9._:-]{1,256}$/u;
20
16
  const SAFE_ENV_KEYS = [
21
17
  "APPDATA",
22
18
  "COMSPEC",
@@ -51,175 +47,48 @@ function openCodeQueryCacheKey(query, configIdentity) {
51
47
  const environment = SAFE_ENV_KEYS.map((key) => `${key}=${process.env[key] ?? ""}`).join("\0");
52
48
  return `${String(identity)}\0${environment}\0${query}`;
53
49
  }
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({
50
+ const isExactOpenCodeSessionCursor = sessionCatalogPaging.isExactCursor;
51
+ const OPENCODE_PARAMETER_MESSAGES = {
52
+ listNotObject: "OpenCode session list parameters must be an object",
53
+ unknownListParameter: (key) => `unknown OpenCode session list parameter: ${key}`,
54
+ invalidSearchTerm: "searchTerm is invalid",
55
+ readNotObject: "OpenCode session read parameters must be an object",
56
+ unknownReadParameter: (key) => `unknown OpenCode session read parameter: ${key}`,
57
+ invalidThreadId: "threadId is invalid"
58
+ };
59
+ async function runOpenCode(args) {
60
+ const invocation = materializeWindowsSpawnProgram(resolveWindowsSpawnProgram({
163
61
  command: "opencode",
164
62
  platform: process.platform,
165
63
  env: process.env,
166
64
  execPath: process.execPath,
167
65
  packageName: "opencode-ai"
168
66
  }), args);
169
- }
170
- async function runOpenCode(args) {
171
- const invocation = resolveSpawnInvocation(args);
172
67
  const env = {
173
68
  OPENCODE_PURE: "1",
174
69
  NO_COLOR: "1"
175
70
  };
176
71
  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, {
72
+ const result = await runCommandBuffered([invocation.command, ...invocation.argv], {
73
+ baseEnv: {},
178
74
  env,
179
- shell: invocation.shell,
180
- windowsHide: invocation.windowsHide,
181
- stdio: [
182
- "ignore",
183
- "pipe",
184
- "pipe"
185
- ]
75
+ input: "",
76
+ maxCombinedOutputBytes: MAX_CLI_OUTPUT_BYTES,
77
+ maxOutputBytes: MAX_CLI_OUTPUT_BYTES,
78
+ terminateOnOutputError: true,
79
+ timeoutMs: CLI_TIMEOUT_MS
186
80
  });
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)}`);
81
+ if (result.termination === "output-limit") throw new Error("OpenCode session output exceeded the safety limit");
82
+ if (result.errorStream) {
83
+ const message = result.error?.message ?? "unknown error";
84
+ throw new Error(`OpenCode ${result.errorStream} stream failed: ${message}`, { cause: result.error });
221
85
  }
222
- return Buffer.concat(stdout).toString("utf8");
86
+ if (result.termination === "error" && result.error) throw result.error;
87
+ if (result.code !== 0) {
88
+ const detail = result.stderr.toString("utf8").trim();
89
+ throw new Error(detail || `OpenCode exited with code ${String(result.code)}`);
90
+ }
91
+ return result.stdout.toString("utf8");
223
92
  }
224
93
  async function queryOpenCodeDatabase(query) {
225
94
  const output = await runOpenCode([
@@ -272,7 +141,7 @@ async function exportOpenCodeSession(threadId) {
272
141
  function parseOpenCodeSession(value) {
273
142
  if (!isRecord(value)) return;
274
143
  const threadId = normalizeBoundedOptionalString(value.id, 256);
275
- if (!threadId || !SESSION_ID_PATTERN.test(threadId)) return;
144
+ if (!threadId || !OPENCODE_SESSION_ID_PATTERN.test(threadId)) return;
276
145
  const name = normalizeBoundedOptionalString(value.title, 1e3);
277
146
  const cwd = normalizeBoundedOptionalString(value.directory, 4096);
278
147
  const createdAt = typeof value.created === "number" && Number.isFinite(value.created) ? value.created : void 0;
@@ -295,8 +164,11 @@ function parseOpenCodeSession(value) {
295
164
  };
296
165
  }
297
166
  async function listLocalOpenCodeSessionPage(value, options = {}) {
298
- const params = parseListParams(value);
299
- const offset = decodeCursor(params.cursor);
167
+ const params = sessionCatalogPaging.parseListParams(value, {
168
+ searchMaxLength: MAX_SEARCH_LENGTH,
169
+ messages: OPENCODE_PARAMETER_MESSAGES
170
+ });
171
+ const offset = sessionCatalogPaging.decodeCursor(params.cursor);
300
172
  const requestedCount = params.searchTerm ? MAX_CLI_LIST_SESSIONS : Math.min(MAX_CLI_LIST_SESSIONS, offset + params.limit + 1);
301
173
  const parsed = await queryCachedOpenCodeSessions([
302
174
  "SELECT id, title, time_created AS created, time_updated AS updated,",
@@ -320,9 +192,17 @@ async function listLocalOpenCodeSessionPage(value, options = {}) {
320
192
  const page = sessions.slice(offset, offset + params.limit);
321
193
  return {
322
194
  sessions: page,
323
- ...offset + page.length < sessions.length ? { nextCursor: encodeCursor(offset + page.length) } : {}
195
+ ...offset + page.length < sessions.length ? { nextCursor: sessionCatalogPaging.encodeCursor(offset + page.length) } : {}
324
196
  };
325
197
  }
198
+ async function requireLocalOpenCodeSession(threadId) {
199
+ const session = (await listLocalOpenCodeSessionPage({
200
+ searchTerm: threadId,
201
+ limit: 100
202
+ })).sessions.find((candidate) => candidate.threadId === threadId);
203
+ if (!session) throw new Error("OpenCode session is unavailable");
204
+ return session;
205
+ }
326
206
  function jsonText(value, maxLength = 2e4) {
327
207
  try {
328
208
  const text = JSON.stringify(value);
@@ -395,9 +275,14 @@ function openCodeTranscriptItems(value) {
395
275
  });
396
276
  }
397
277
  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);
278
+ const params = sessionCatalogPaging.parseReadParams(value, {
279
+ threadIdMaxLength: 256,
280
+ threadIdPattern: OPENCODE_SESSION_ID_PATTERN,
281
+ messages: OPENCODE_PARAMETER_MESSAGES
282
+ });
283
+ const offset = sessionCatalogPaging.decodeCursor(params.cursor);
284
+ const items = openCodeTranscriptItems(await exportOpenCodeSession(params.threadId));
285
+ const page = sessionCatalogPaging.boundTranscriptPage(items, params.limit, offset);
401
286
  return {
402
287
  hostId: LOCAL_HOST_ID,
403
288
  label: "Local OpenCode",
@@ -406,4 +291,4 @@ async function readLocalOpenCodeTranscriptPage(value) {
406
291
  };
407
292
  }
408
293
  //#endregion
409
- export { exportOpenCodeSession, isExactOpenCodeSessionCursor, listLocalOpenCodeSessionPage, queryOpenCodeDatabase, readLocalOpenCodeTranscriptPage };
294
+ export { exportOpenCodeSession, isExactOpenCodeSessionCursor, listLocalOpenCodeSessionPage, queryOpenCodeDatabase, readLocalOpenCodeTranscriptPage, requireLocalOpenCodeSession };
@@ -2,23 +2,11 @@ import { OPENCODE_SESSION_ID_PATTERN } from "./session-catalog-shared.js";
2
2
  import { exportOpenCodeSession, queryOpenCodeDatabase } from "./session-catalog.js";
3
3
  import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
4
4
  import { isExternalUserText, normalizeUserText } from "openclaw/plugin-sdk/session-catalog";
5
+ import { runTasksWithConcurrency } from "openclaw/plugin-sdk/concurrency-runtime";
5
6
  //#region extensions/opencode/session-upstream-activity.ts
6
7
  const OPENCODE_EXPORT_CONCURRENCY = 4;
7
8
  const OPENCODE_REPLAY_LOOKBACK_USER_MESSAGES = 50;
8
9
  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
10
  function sqlString(value) {
23
11
  return `'${value.replaceAll("'", "''")}'`;
24
12
  }
@@ -215,18 +203,23 @@ async function checkOpenCodeUpstreamActivity(probes) {
215
203
  } catch {
216
204
  return [];
217
205
  }
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);
206
+ const { results: outcomes } = await runTasksWithConcurrency({
207
+ tasks: eligible.map((probe) => async () => {
208
+ const indicator = indicators.get(probe.threadId);
209
+ if (!indicator) return {
210
+ kind: "missing",
211
+ sessionKey: probe.sessionKey
212
+ };
213
+ try {
214
+ return await classifyChangedProbe(probe, indicator);
215
+ } catch {
216
+ return;
217
+ }
218
+ }),
219
+ limit: OPENCODE_EXPORT_CONCURRENCY,
220
+ throwOnError: true
221
+ });
222
+ return outcomes.filter((outcome) => outcome !== void 0);
230
223
  }
231
224
  //#endregion
232
225
  export { checkOpenCodeUpstreamActivity, linkContinuedOpenCodeSession };