@openclaw/opencode-provider 2026.8.1-beta.2 → 2026.8.1-beta.3
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.
- package/dist/session-catalog-plugin.js +168 -327
- package/dist/session-catalog-shared.js +1 -2
- package/dist/session-catalog.js +55 -170
- package/package.json +4 -4
- package/dist/session-catalog-terminal.js +0 -104
|
@@ -1,41 +1,19 @@
|
|
|
1
|
-
import { OPENCODE_LOCAL_SESSION_HOST_ID, OPENCODE_NODE_INVOKE_TIMEOUT_MS, OPENCODE_SESSIONS_CAPABILITY, OPENCODE_SESSIONS_LIST_COMMAND, OPENCODE_SESSION_ID_PATTERN, OPENCODE_SESSION_READ_COMMAND, OPENCODE_TERMINAL_RESUME_COMMAND
|
|
2
|
-
import { isExactOpenCodeSessionCursor, listLocalOpenCodeSessionPage, readLocalOpenCodeTranscriptPage } from "./session-catalog.js";
|
|
3
|
-
import { createOpenCodeTerminalNodeHostCommand, openOpenCodeCatalogTerminal } from "./session-catalog-terminal.js";
|
|
1
|
+
import { OPENCODE_LOCAL_SESSION_HOST_ID, OPENCODE_NODE_INVOKE_TIMEOUT_MS, OPENCODE_SESSIONS_CAPABILITY, OPENCODE_SESSIONS_LIST_COMMAND, OPENCODE_SESSION_ID_PATTERN, OPENCODE_SESSION_READ_COMMAND, OPENCODE_TERMINAL_RESUME_COMMAND } from "./session-catalog-shared.js";
|
|
2
|
+
import { isExactOpenCodeSessionCursor, listLocalOpenCodeSessionPage, readLocalOpenCodeTranscriptPage, requireLocalOpenCodeSession } from "./session-catalog.js";
|
|
4
3
|
import { checkOpenCodeUpstreamActivity, linkContinuedOpenCodeSession } from "./session-upstream-activity.js";
|
|
5
4
|
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
6
5
|
import { accessSync, constants, statSync } from "node:fs";
|
|
7
6
|
import path from "node:path";
|
|
8
7
|
import process from "node:process";
|
|
9
8
|
import { resolveAcpSessionAvailability } from "openclaw/plugin-sdk/acp-runtime";
|
|
10
|
-
import {
|
|
9
|
+
import { resolveSessionAgentIds } from "openclaw/plugin-sdk/agent-runtime";
|
|
11
10
|
import { resolveNodeHostExecutable } from "openclaw/plugin-sdk/node-host";
|
|
12
|
-
import {
|
|
11
|
+
import { createSessionCatalogFamily, createSessionCatalogNodeHostBindings, importSessionCatalogHistory, listAdoptedSessionCatalogSessions, sessionCatalogAdoptedSessionKey } from "openclaw/plugin-sdk/session-catalog";
|
|
13
12
|
//#region extensions/opencode/session-catalog-plugin.ts
|
|
14
13
|
const MAX_HOSTS = 100;
|
|
15
|
-
const TRANSCRIPT_ITEM_TYPES = /* @__PURE__ */ new Set([
|
|
16
|
-
"userMessage",
|
|
17
|
-
"agentMessage",
|
|
18
|
-
"reasoning",
|
|
19
|
-
"toolCall",
|
|
20
|
-
"toolResult",
|
|
21
|
-
"other"
|
|
22
|
-
]);
|
|
23
14
|
const ACPX_BACKEND_ID = "acpx";
|
|
24
15
|
const OPENCODE_ACP_AGENT_ID = "opencode";
|
|
25
16
|
const OPENCODE_ADOPTED_SESSION_KEY_PREFIX = "plugin:opencode:catalog-adopt:";
|
|
26
|
-
const continueAdoption = createSessionCatalogAdoptionCoordinator();
|
|
27
|
-
function isOptionalString(value) {
|
|
28
|
-
return value === void 0 || typeof value === "string";
|
|
29
|
-
}
|
|
30
|
-
function isOptionalNumber(value) {
|
|
31
|
-
return value === void 0 || typeof value === "number";
|
|
32
|
-
}
|
|
33
|
-
function isNodeSession(value) {
|
|
34
|
-
return isRecord(value) && typeof value.threadId === "string" && OPENCODE_SESSION_ID_PATTERN.test(value.threadId) && typeof value.status === "string" && value.status.length > 0 && typeof value.archived === "boolean" && typeof value.canContinue === "boolean" && typeof value.canArchive === "boolean" && isOptionalString(value.name) && isOptionalString(value.cwd) && isOptionalString(value.source) && isOptionalString(value.modelProvider) && isOptionalString(value.cliVersion) && isOptionalString(value.gitBranch) && isOptionalString(value.sessionKey) && isOptionalNumber(value.createdAt) && isOptionalNumber(value.updatedAt) && isOptionalNumber(value.recencyAt);
|
|
35
|
-
}
|
|
36
|
-
function isNodeTranscriptItem(value) {
|
|
37
|
-
return isRecord(value) && typeof value.type === "string" && TRANSCRIPT_ITEM_TYPES.has(value.type) && isOptionalString(value.id) && isOptionalString(value.text) && isOptionalString(value.timestamp) && isOptionalString(value.model) && (value.truncated === void 0 || typeof value.truncated === "boolean");
|
|
38
|
-
}
|
|
39
17
|
function executableOnPath(command, env) {
|
|
40
18
|
const pathValue = env.PATH ?? env.Path ?? "";
|
|
41
19
|
const delimiter = process.platform === "win32" ? ";" : path.delimiter;
|
|
@@ -72,229 +50,14 @@ function openCodeUsesProcessHomeFallback(env) {
|
|
|
72
50
|
return !env.OPENCODE_DB?.trim() && !path.isAbsolute(env.XDG_DATA_HOME?.trim() ?? "");
|
|
73
51
|
}
|
|
74
52
|
function assertOpenCodeLocalAccess(hostId, allowProcessHomeFallback) {
|
|
75
|
-
if (hostId === "gateway" && allowProcessHomeFallback === false && openCodeUsesProcessHomeFallback(process.env)) throw new
|
|
76
|
-
}
|
|
77
|
-
function createOpenCodeSessionNodeHostCommands(api) {
|
|
78
|
-
const available = ({ config, env }) => fullConfigCatalogEnabled(config) && executableOnPath("opencode", env);
|
|
79
|
-
return [
|
|
80
|
-
{
|
|
81
|
-
command: OPENCODE_SESSIONS_LIST_COMMAND,
|
|
82
|
-
cap: OPENCODE_SESSIONS_CAPABILITY,
|
|
83
|
-
dangerous: false,
|
|
84
|
-
isAvailable: available,
|
|
85
|
-
handle: async (paramsJSON) => JSON.stringify(await listLocalOpenCodeSessionPage(parseNodeParams(paramsJSON), { configIdentity: currentOpenCodeCatalogConfig(api) }))
|
|
86
|
-
},
|
|
87
|
-
{
|
|
88
|
-
command: OPENCODE_SESSION_READ_COMMAND,
|
|
89
|
-
cap: OPENCODE_SESSIONS_CAPABILITY,
|
|
90
|
-
dangerous: false,
|
|
91
|
-
isAvailable: available,
|
|
92
|
-
handle: async (paramsJSON) => JSON.stringify(await readLocalOpenCodeTranscriptPage(parseNodeParams(paramsJSON)))
|
|
93
|
-
},
|
|
94
|
-
createOpenCodeTerminalNodeHostCommand(available)
|
|
95
|
-
];
|
|
96
|
-
}
|
|
97
|
-
function createOpenCodeSessionNodeInvokePolicies() {
|
|
98
|
-
return [{
|
|
99
|
-
commands: [
|
|
100
|
-
OPENCODE_SESSIONS_LIST_COMMAND,
|
|
101
|
-
OPENCODE_SESSION_READ_COMMAND,
|
|
102
|
-
OPENCODE_TERMINAL_RESUME_COMMAND
|
|
103
|
-
],
|
|
104
|
-
defaultPlatforms: [
|
|
105
|
-
"macos",
|
|
106
|
-
"linux",
|
|
107
|
-
"windows"
|
|
108
|
-
],
|
|
109
|
-
handle: (context) => context.command === "opencode.terminal.resume.v1" ? { ok: true } : context.invokeNode()
|
|
110
|
-
}];
|
|
111
|
-
}
|
|
112
|
-
function nodeLabel(node) {
|
|
113
|
-
return node.displayName?.trim() || node.remoteIp?.trim() || node.nodeId;
|
|
114
|
-
}
|
|
115
|
-
function unwrapNodePayload(value) {
|
|
116
|
-
return isRecord(value) && typeof value.payloadJSON === "string" ? JSON.parse(value.payloadJSON) : value;
|
|
117
|
-
}
|
|
118
|
-
function setCatalogCapabilities(page, capabilities) {
|
|
119
|
-
for (const session of page.sessions) {
|
|
120
|
-
session.canContinue = capabilities.canContinue;
|
|
121
|
-
session.canOpenTerminal = capabilities.canOpenTerminal;
|
|
122
|
-
}
|
|
123
|
-
return page;
|
|
124
|
-
}
|
|
125
|
-
function projectOpenCodeAdoptedSessions(page, adopted) {
|
|
126
|
-
return {
|
|
127
|
-
...page,
|
|
128
|
-
sessions: page.sessions.map((session) => {
|
|
129
|
-
const sessionKey = adopted.get(sessionCatalogAdoptedSourceKey(OPENCODE_LOCAL_SESSION_HOST_ID, session.threadId));
|
|
130
|
-
return sessionKey ? {
|
|
131
|
-
...session,
|
|
132
|
-
sessionKey
|
|
133
|
-
} : session;
|
|
134
|
-
})
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
|
-
async function listOpenCodeNodeHost(runtime, query, node) {
|
|
138
|
-
const hostId = `node:${node.nodeId}`;
|
|
139
|
-
const common = {
|
|
140
|
-
hostId,
|
|
141
|
-
label: nodeLabel(node),
|
|
142
|
-
kind: "node",
|
|
143
|
-
connected: node.connected === true,
|
|
144
|
-
nodeId: node.nodeId
|
|
145
|
-
};
|
|
146
|
-
if (node.connected !== true) return {
|
|
147
|
-
...common,
|
|
148
|
-
sessions: [],
|
|
149
|
-
error: {
|
|
150
|
-
code: "NODE_OFFLINE",
|
|
151
|
-
message: "Paired node is offline"
|
|
152
|
-
}
|
|
153
|
-
};
|
|
154
|
-
try {
|
|
155
|
-
const cursor = query.cursors?.[hostId];
|
|
156
|
-
if (cursor !== void 0 && !isExactOpenCodeSessionCursor(cursor)) throw new Error("cursor is invalid");
|
|
157
|
-
const page = parseNodeSessionPage(unwrapNodePayload(await runtime.nodes.invoke({
|
|
158
|
-
nodeId: node.nodeId,
|
|
159
|
-
command: OPENCODE_SESSIONS_LIST_COMMAND,
|
|
160
|
-
params: {
|
|
161
|
-
...query.limitPerHost ? { limit: query.limitPerHost } : {},
|
|
162
|
-
...query.search ? { searchTerm: query.search } : {},
|
|
163
|
-
...cursor !== void 0 ? { cursor } : {}
|
|
164
|
-
},
|
|
165
|
-
timeoutMs: OPENCODE_NODE_INVOKE_TIMEOUT_MS,
|
|
166
|
-
scopes: ["operator.write"]
|
|
167
|
-
})));
|
|
168
|
-
const canOpenTerminal = (node.invocableCommands ?? node.commands)?.includes(OPENCODE_TERMINAL_RESUME_COMMAND) === true;
|
|
169
|
-
return {
|
|
170
|
-
...common,
|
|
171
|
-
...setCatalogCapabilities(page, {
|
|
172
|
-
canContinue: false,
|
|
173
|
-
canOpenTerminal
|
|
174
|
-
})
|
|
175
|
-
};
|
|
176
|
-
} catch {
|
|
177
|
-
return {
|
|
178
|
-
...common,
|
|
179
|
-
sessions: [],
|
|
180
|
-
error: {
|
|
181
|
-
code: "NODE_INVOKE_FAILED",
|
|
182
|
-
message: "Paired node OpenCode sessions are unavailable"
|
|
183
|
-
}
|
|
184
|
-
};
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
function parseNodeSessionPage(value) {
|
|
188
|
-
if (!isRecord(value) || !Array.isArray(value.sessions) || value.sessions.length > 100) throw new Error("OpenCode node returned an invalid session page");
|
|
189
|
-
if (!value.sessions.every(isNodeSession)) throw new Error("OpenCode node returned an invalid session page");
|
|
190
|
-
const sessions = value.sessions;
|
|
191
|
-
const nextCursor = value.nextCursor;
|
|
192
|
-
if (nextCursor !== void 0 && !isExactOpenCodeSessionCursor(nextCursor)) throw new Error("OpenCode node returned an invalid cursor");
|
|
193
|
-
return {
|
|
194
|
-
sessions,
|
|
195
|
-
...nextCursor !== void 0 ? { nextCursor } : {}
|
|
196
|
-
};
|
|
197
|
-
}
|
|
198
|
-
function parseNodeTranscriptPage(value, threadId) {
|
|
199
|
-
if (!isRecord(value) || value.threadId !== threadId || !Array.isArray(value.items) || value.items.length > 100 || !value.items.every(isNodeTranscriptItem)) throw new Error("OpenCode node returned an invalid transcript page");
|
|
200
|
-
const nextCursor = value.nextCursor;
|
|
201
|
-
if (nextCursor !== void 0 && !isExactOpenCodeSessionCursor(nextCursor)) throw new Error("OpenCode node returned an invalid cursor");
|
|
202
|
-
return {
|
|
203
|
-
hostId: OPENCODE_LOCAL_SESSION_HOST_ID,
|
|
204
|
-
threadId,
|
|
205
|
-
items: value.items,
|
|
206
|
-
...nextCursor !== void 0 ? { nextCursor } : {}
|
|
207
|
-
};
|
|
208
|
-
}
|
|
209
|
-
async function listOpenCodeHosts(api, query) {
|
|
210
|
-
const runtime = api.runtime;
|
|
211
|
-
const config = currentOpenCodeCatalogConfig(api);
|
|
212
|
-
const canContinue = resolveAcpSessionAvailability({
|
|
213
|
-
config,
|
|
214
|
-
backendId: ACPX_BACKEND_ID,
|
|
215
|
-
agentId: OPENCODE_ACP_AGENT_ID
|
|
216
|
-
}).available;
|
|
217
|
-
const adopted = query.sessionEntries ? listAdoptedOpenCodeSessions(api, query.sessionEntries) : /* @__PURE__ */ new Map();
|
|
218
|
-
const requested = query.hostIds ? new Set(query.hostIds) : void 0;
|
|
219
|
-
const hosts = [];
|
|
220
|
-
if ((!requested || requested.has("gateway")) && (query.allowProcessHomeFallback !== false || !openCodeUsesProcessHomeFallback(process.env)) && resolveNodeHostExecutable("opencode", {
|
|
221
|
-
env: process.env,
|
|
222
|
-
pathEnv: process.env.PATH ?? "",
|
|
223
|
-
strategy: "fallback"
|
|
224
|
-
})) try {
|
|
225
|
-
hosts.push({
|
|
226
|
-
hostId: OPENCODE_LOCAL_SESSION_HOST_ID,
|
|
227
|
-
label: "Local OpenCode",
|
|
228
|
-
kind: "gateway",
|
|
229
|
-
connected: true,
|
|
230
|
-
...await listLocalOpenCodeSessionPage({
|
|
231
|
-
limit: query.limitPerHost,
|
|
232
|
-
...query.search ? { searchTerm: query.search } : {},
|
|
233
|
-
cursor: query.cursors?.[OPENCODE_LOCAL_SESSION_HOST_ID]
|
|
234
|
-
}, { configIdentity: config }).then((page) => projectOpenCodeAdoptedSessions(setCatalogCapabilities(page, {
|
|
235
|
-
canContinue,
|
|
236
|
-
canOpenTerminal: true
|
|
237
|
-
}), adopted))
|
|
238
|
-
});
|
|
239
|
-
} catch {
|
|
240
|
-
hosts.push({
|
|
241
|
-
hostId: OPENCODE_LOCAL_SESSION_HOST_ID,
|
|
242
|
-
label: "Local OpenCode",
|
|
243
|
-
kind: "gateway",
|
|
244
|
-
connected: true,
|
|
245
|
-
sessions: [],
|
|
246
|
-
error: {
|
|
247
|
-
code: "LOCAL_READ_FAILED",
|
|
248
|
-
message: "Local OpenCode sessions are unavailable"
|
|
249
|
-
}
|
|
250
|
-
});
|
|
251
|
-
}
|
|
252
|
-
let nodes;
|
|
253
|
-
try {
|
|
254
|
-
nodes = (await (query.listNodes?.() ?? runtime.nodes.list())).nodes;
|
|
255
|
-
} catch {
|
|
256
|
-
return hosts;
|
|
257
|
-
}
|
|
258
|
-
const eligible = nodes.filter((node) => node.commands?.includes("opencode.sessions.list.v1") && (!requested || requested.has(`node:${node.nodeId}`))).toSorted((left, right) => nodeLabel(left).localeCompare(nodeLabel(right))).slice(0, MAX_HOSTS - hosts.length);
|
|
259
|
-
const nodeHosts = await Promise.all(eligible.map((node) => listOpenCodeNodeHost(runtime, query, node)));
|
|
260
|
-
return [...hosts, ...nodeHosts];
|
|
261
|
-
}
|
|
262
|
-
async function readOpenCodeTranscript(runtime, request) {
|
|
263
|
-
const cursor = request.cursor;
|
|
264
|
-
if (cursor !== void 0 && !isExactOpenCodeSessionCursor(cursor)) throw new Error("cursor is invalid");
|
|
265
|
-
if (request.hostId === "gateway") {
|
|
266
|
-
assertOpenCodeLocalAccess(request.hostId, request.allowProcessHomeFallback);
|
|
267
|
-
return await readLocalOpenCodeTranscriptPage({
|
|
268
|
-
threadId: request.threadId,
|
|
269
|
-
...request.limit ? { limit: request.limit } : {},
|
|
270
|
-
...cursor !== void 0 ? { cursor } : {}
|
|
271
|
-
});
|
|
272
|
-
}
|
|
273
|
-
if (!request.hostId.startsWith("node:")) throw new Error("hostId is invalid");
|
|
274
|
-
const nodeId = request.hostId.slice(5);
|
|
275
|
-
const node = (await runtime.nodes.list()).nodes.find((candidate) => candidate.nodeId === nodeId && candidate.connected === true && candidate.commands?.includes("opencode.sessions.read.v1"));
|
|
276
|
-
if (!node) throw new Error("paired-node OpenCode session host is unavailable");
|
|
277
|
-
return {
|
|
278
|
-
...parseNodeTranscriptPage(unwrapNodePayload(await runtime.nodes.invoke({
|
|
279
|
-
nodeId,
|
|
280
|
-
command: OPENCODE_SESSION_READ_COMMAND,
|
|
281
|
-
params: {
|
|
282
|
-
threadId: request.threadId,
|
|
283
|
-
...request.limit ? { limit: request.limit } : {},
|
|
284
|
-
...cursor !== void 0 ? { cursor } : {}
|
|
285
|
-
},
|
|
286
|
-
timeoutMs: OPENCODE_NODE_INVOKE_TIMEOUT_MS,
|
|
287
|
-
scopes: ["operator.write"]
|
|
288
|
-
})), request.threadId),
|
|
289
|
-
hostId: request.hostId,
|
|
290
|
-
label: nodeLabel(node)
|
|
291
|
-
};
|
|
53
|
+
if (hostId === "gateway" && allowProcessHomeFallback === false && openCodeUsesProcessHomeFallback(process.env)) throw new Error("local OpenCode sessions are unavailable in isolated state");
|
|
292
54
|
}
|
|
293
55
|
function currentOpenCodeCatalogConfig(api) {
|
|
294
56
|
return api.runtime.config?.current?.() ?? api.config ?? {};
|
|
295
57
|
}
|
|
296
|
-
function listAdoptedOpenCodeSessions(api, sessionEntries) {
|
|
58
|
+
function listAdoptedOpenCodeSessions(api, agentId, sessionEntries) {
|
|
297
59
|
return listAdoptedSessionCatalogSessions({
|
|
60
|
+
...agentId ? { agentId } : {},
|
|
298
61
|
config: currentOpenCodeCatalogConfig(api),
|
|
299
62
|
pluginId: api.id,
|
|
300
63
|
runtime: api.runtime,
|
|
@@ -309,99 +72,177 @@ function listAdoptedOpenCodeSessions(api, sessionEntries) {
|
|
|
309
72
|
}
|
|
310
73
|
});
|
|
311
74
|
}
|
|
312
|
-
async function
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
});
|
|
320
|
-
if (!
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
}
|
|
340
|
-
if (!currentAvailability.available) throw new OpenCodeCatalogParamsError(currentAvailability.message);
|
|
341
|
-
const marker = { sourceThreadId: threadId };
|
|
342
|
-
return { sessionKey: (await api.runtime.agent.session.createSessionEntry({
|
|
343
|
-
cfg: config,
|
|
344
|
-
key: sessionCatalogAdoptedSessionKey(OPENCODE_ADOPTED_SESSION_KEY_PREFIX, threadId),
|
|
345
|
-
agentId: resolveDefaultAgentId(config),
|
|
346
|
-
recoverMatchingInitialEntry: true,
|
|
347
|
-
...record.name ? { label: record.name } : {},
|
|
348
|
-
...record.cwd ? { spawnedCwd: record.cwd } : {},
|
|
349
|
-
initialEntry: {
|
|
350
|
-
acpBackendId: ACPX_BACKEND_ID,
|
|
351
|
-
acpSessionBinding: {
|
|
352
|
-
acpAgentId: OPENCODE_ACP_AGENT_ID,
|
|
353
|
-
agentSessionId: threadId
|
|
354
|
-
},
|
|
355
|
-
pluginExtensions: { opencode: { sessionCatalog: marker } }
|
|
356
|
-
},
|
|
357
|
-
afterCreate: async (entry) => {
|
|
358
|
-
await importSessionCatalogHistory({
|
|
359
|
-
catalogId: "opencode",
|
|
360
|
-
threadId,
|
|
361
|
-
read: async ({ cursor, limit }) => await readOpenCodeTranscript(api.runtime, {
|
|
362
|
-
hostId,
|
|
363
|
-
threadId,
|
|
364
|
-
limit,
|
|
365
|
-
...cursor ? { cursor } : {}
|
|
366
|
-
}),
|
|
367
|
-
sessionId: entry.sessionId,
|
|
368
|
-
sessionKey: entry.key,
|
|
369
|
-
agentId: entry.agentId,
|
|
370
|
-
...record.cwd ? { cwd: record.cwd } : {},
|
|
371
|
-
config
|
|
372
|
-
});
|
|
373
|
-
return { pluginExtensions: { opencode: { sessionCatalog: marker } } };
|
|
374
|
-
}
|
|
375
|
-
})).key };
|
|
75
|
+
async function loadContinuableOpenCodeSession(api, threadId) {
|
|
76
|
+
const session = (await listLocalOpenCodeSessionPage({
|
|
77
|
+
searchTerm: threadId,
|
|
78
|
+
limit: 100
|
|
79
|
+
}, {
|
|
80
|
+
configIdentity: currentOpenCodeCatalogConfig(api),
|
|
81
|
+
forceRefresh: true
|
|
82
|
+
}).catch(() => void 0))?.sessions.find((candidate) => candidate.threadId === threadId);
|
|
83
|
+
if (!session) throw new Error("OpenCode session is unavailable");
|
|
84
|
+
return session;
|
|
85
|
+
}
|
|
86
|
+
async function createAdoptedOpenCodeSession(params) {
|
|
87
|
+
const config = currentOpenCodeCatalogConfig(params.api);
|
|
88
|
+
const marker = { sourceThreadId: params.threadId };
|
|
89
|
+
return { sessionKey: (await params.api.runtime.agent.session.createSessionEntry({
|
|
90
|
+
cfg: config,
|
|
91
|
+
key: sessionCatalogAdoptedSessionKey(OPENCODE_ADOPTED_SESSION_KEY_PREFIX, params.threadId),
|
|
92
|
+
agentId: params.agentId,
|
|
93
|
+
recoverMatchingInitialEntry: true,
|
|
94
|
+
...params.session.name ? { label: params.session.name } : {},
|
|
95
|
+
...params.session.cwd ? { spawnedCwd: params.session.cwd } : {},
|
|
96
|
+
initialEntry: {
|
|
97
|
+
acpBackendId: ACPX_BACKEND_ID,
|
|
98
|
+
acpSessionBinding: {
|
|
99
|
+
acpAgentId: OPENCODE_ACP_AGENT_ID,
|
|
100
|
+
agentSessionId: params.threadId
|
|
101
|
+
},
|
|
102
|
+
pluginExtensions: { opencode: { sessionCatalog: marker } }
|
|
376
103
|
},
|
|
377
|
-
|
|
104
|
+
afterCreate: async (entry) => {
|
|
105
|
+
await importSessionCatalogHistory({
|
|
106
|
+
catalogId: "opencode",
|
|
107
|
+
threadId: params.threadId,
|
|
108
|
+
read: async ({ cursor, limit }) => await readLocalOpenCodeTranscriptPage({
|
|
109
|
+
threadId: params.threadId,
|
|
110
|
+
limit,
|
|
111
|
+
...cursor ? { cursor } : {}
|
|
112
|
+
}),
|
|
113
|
+
sessionId: entry.sessionId,
|
|
114
|
+
sessionKey: entry.key,
|
|
115
|
+
agentId: entry.agentId,
|
|
116
|
+
...params.session.cwd ? { cwd: params.session.cwd } : {},
|
|
117
|
+
config
|
|
118
|
+
});
|
|
119
|
+
return { pluginExtensions: { opencode: { sessionCatalog: marker } } };
|
|
120
|
+
}
|
|
121
|
+
})).key };
|
|
122
|
+
}
|
|
123
|
+
function createOpenCodeNodeHostBindings(api) {
|
|
124
|
+
const available = ({ config, env }) => fullConfigCatalogEnabled(config) && executableOnPath("opencode", env);
|
|
125
|
+
return createSessionCatalogNodeHostBindings({
|
|
126
|
+
capability: OPENCODE_SESSIONS_CAPABILITY,
|
|
127
|
+
listCommand: OPENCODE_SESSIONS_LIST_COMMAND,
|
|
128
|
+
readCommand: OPENCODE_SESSION_READ_COMMAND,
|
|
129
|
+
terminalCommand: OPENCODE_TERMINAL_RESUME_COMMAND,
|
|
130
|
+
sessionIdPattern: OPENCODE_SESSION_ID_PATTERN,
|
|
131
|
+
executable: "opencode",
|
|
132
|
+
args: (threadId) => ["--session", threadId],
|
|
133
|
+
listAvailable: available,
|
|
134
|
+
terminalAvailable: available,
|
|
135
|
+
parseParams: parseNodeParams,
|
|
136
|
+
list: async (params) => await listLocalOpenCodeSessionPage(params, { configIdentity: currentOpenCodeCatalogConfig(api) }),
|
|
137
|
+
read: readLocalOpenCodeTranscriptPage,
|
|
138
|
+
requireSession: requireLocalOpenCodeSession,
|
|
139
|
+
terminalIoRequiredMessage: "OpenCode terminal command requires duplex transport",
|
|
140
|
+
terminalUnavailableMessage: "OpenCode CLI is unavailable",
|
|
141
|
+
invalidThreadIdMessage: "INVALID_REQUEST: threadId is invalid"
|
|
378
142
|
});
|
|
379
143
|
}
|
|
380
144
|
function registerOpenCodeSessionCatalog(api) {
|
|
381
145
|
if (!isOpenCodeSessionCatalogEnabled(api.pluginConfig)) return;
|
|
146
|
+
const provider = createSessionCatalogFamily({
|
|
147
|
+
runtime: api.runtime,
|
|
148
|
+
local: {
|
|
149
|
+
hostId: OPENCODE_LOCAL_SESSION_HOST_ID,
|
|
150
|
+
label: "Local OpenCode",
|
|
151
|
+
available: (query) => (query.allowProcessHomeFallback !== false || !openCodeUsesProcessHomeFallback(process.env)) && resolveNodeHostExecutable("opencode", {
|
|
152
|
+
env: process.env,
|
|
153
|
+
pathEnv: process.env.PATH ?? "",
|
|
154
|
+
strategy: "fallback"
|
|
155
|
+
}) !== void 0,
|
|
156
|
+
list: async (query) => await listLocalOpenCodeSessionPage({
|
|
157
|
+
limit: query.limitPerHost,
|
|
158
|
+
...query.search ? { searchTerm: query.search } : {},
|
|
159
|
+
cursor: query.cursors?.[OPENCODE_LOCAL_SESSION_HOST_ID]
|
|
160
|
+
}, { configIdentity: currentOpenCodeCatalogConfig(api) }),
|
|
161
|
+
read: async (request) => await readLocalOpenCodeTranscriptPage({
|
|
162
|
+
threadId: request.threadId,
|
|
163
|
+
...request.limit ? { limit: request.limit } : {},
|
|
164
|
+
...request.cursor !== void 0 ? { cursor: request.cursor } : {}
|
|
165
|
+
}),
|
|
166
|
+
assertAccess: assertOpenCodeLocalAccess
|
|
167
|
+
},
|
|
168
|
+
node: {
|
|
169
|
+
listCommand: OPENCODE_SESSIONS_LIST_COMMAND,
|
|
170
|
+
readCommand: OPENCODE_SESSION_READ_COMMAND,
|
|
171
|
+
terminalCommand: OPENCODE_TERMINAL_RESUME_COMMAND,
|
|
172
|
+
timeoutMs: OPENCODE_NODE_INVOKE_TIMEOUT_MS,
|
|
173
|
+
maxHosts: MAX_HOSTS,
|
|
174
|
+
maxPageLimit: 100,
|
|
175
|
+
sessionIdPattern: OPENCODE_SESSION_ID_PATTERN
|
|
176
|
+
},
|
|
177
|
+
capabilities: {
|
|
178
|
+
local: () => ({
|
|
179
|
+
canContinue: resolveAcpSessionAvailability({
|
|
180
|
+
config: currentOpenCodeCatalogConfig(api),
|
|
181
|
+
backendId: ACPX_BACKEND_ID,
|
|
182
|
+
agentId: OPENCODE_ACP_AGENT_ID
|
|
183
|
+
}).available,
|
|
184
|
+
canOpenTerminal: true
|
|
185
|
+
}),
|
|
186
|
+
node: (node) => {
|
|
187
|
+
return {
|
|
188
|
+
canContinue: false,
|
|
189
|
+
canOpenTerminal: (node.invocableCommands ?? node.commands)?.includes(OPENCODE_TERMINAL_RESUME_COMMAND) === true
|
|
190
|
+
};
|
|
191
|
+
},
|
|
192
|
+
project: (session, capabilities) => ({
|
|
193
|
+
...session,
|
|
194
|
+
...capabilities
|
|
195
|
+
})
|
|
196
|
+
},
|
|
197
|
+
messages: {
|
|
198
|
+
invalidNodeCursor: "OpenCode node returned an invalid cursor",
|
|
199
|
+
invalidNodeSessionPage: "OpenCode node returned an invalid session page",
|
|
200
|
+
invalidNodeTranscriptPage: "OpenCode node returned an invalid transcript page",
|
|
201
|
+
invalidHostId: "OpenCode session catalog hostId is invalid",
|
|
202
|
+
localReadFailed: "Local OpenCode sessions are unavailable",
|
|
203
|
+
nodeInvokeFailed: "Paired node OpenCode sessions are unavailable",
|
|
204
|
+
nodeReadUnavailable: "paired-node OpenCode session host is unavailable",
|
|
205
|
+
nodeTerminalUnavailable: "paired-node OpenCode terminal is unavailable",
|
|
206
|
+
sessionUnavailable: "OpenCode session is unavailable"
|
|
207
|
+
},
|
|
208
|
+
continuation: {
|
|
209
|
+
resolveAgentId: (agentId) => resolveSessionAgentIds({
|
|
210
|
+
config: api.config,
|
|
211
|
+
agentId
|
|
212
|
+
}).sessionAgentId,
|
|
213
|
+
availability: () => resolveAcpSessionAvailability({
|
|
214
|
+
config: currentOpenCodeCatalogConfig(api),
|
|
215
|
+
backendId: ACPX_BACKEND_ID,
|
|
216
|
+
agentId: OPENCODE_ACP_AGENT_ID
|
|
217
|
+
}),
|
|
218
|
+
listAdopted: (agentId, sessionEntries) => listAdoptedOpenCodeSessions(api, agentId, sessionEntries),
|
|
219
|
+
loadSession: async (threadId) => await loadContinuableOpenCodeSession(api, threadId),
|
|
220
|
+
validateSession: () => void 0,
|
|
221
|
+
create: async (params) => await createAdoptedOpenCodeSession({
|
|
222
|
+
api,
|
|
223
|
+
...params
|
|
224
|
+
}),
|
|
225
|
+
complete: async (continued, threadId) => await linkContinuedOpenCodeSession(continued.sessionKey, threadId),
|
|
226
|
+
nodeReadOnlyMessage: "paired-node OpenCode session rows are view-only"
|
|
227
|
+
},
|
|
228
|
+
terminal: {
|
|
229
|
+
executable: "opencode",
|
|
230
|
+
args: (threadId) => ["--session", threadId],
|
|
231
|
+
title: (threadId) => `opencode --session ${threadId.slice(0, 12)}…`,
|
|
232
|
+
requireLocalSession: requireLocalOpenCodeSession,
|
|
233
|
+
unavailableMessage: "OpenCode CLI is unavailable"
|
|
234
|
+
},
|
|
235
|
+
checkUpstreamActivity: (probes, policy) => checkOpenCodeUpstreamActivity(probes.filter((probe) => probe.hostId !== "gateway" || policy?.allowProcessHomeFallback !== false || !openCodeUsesProcessHomeFallback(process.env)))
|
|
236
|
+
}, isExactOpenCodeSessionCursor);
|
|
382
237
|
api.registerSessionCatalog({
|
|
383
238
|
id: "opencode",
|
|
384
239
|
label: "OpenCode",
|
|
385
240
|
supportsProcessHomeIsolation: true,
|
|
386
|
-
|
|
387
|
-
read: async (request) => await readOpenCodeTranscript(api.runtime, request),
|
|
388
|
-
continueSession: async (request) => {
|
|
389
|
-
assertOpenCodeLocalAccess(request.hostId, request.allowProcessHomeFallback);
|
|
390
|
-
return await continueOpenCodeSession(api, request.hostId, request.threadId);
|
|
391
|
-
},
|
|
392
|
-
checkUpstreamActivity: (probes, policy) => checkOpenCodeUpstreamActivity(probes.filter((probe) => probe.hostId !== "gateway" || policy?.allowProcessHomeFallback !== false || !openCodeUsesProcessHomeFallback(process.env))),
|
|
393
|
-
openTerminal: async (request) => {
|
|
394
|
-
assertOpenCodeLocalAccess(request.hostId, request.allowProcessHomeFallback);
|
|
395
|
-
return await openOpenCodeCatalogTerminal({
|
|
396
|
-
runtime: api.runtime,
|
|
397
|
-
...request,
|
|
398
|
-
parseNodeSessionPage,
|
|
399
|
-
unwrapNodePayload
|
|
400
|
-
});
|
|
401
|
-
}
|
|
241
|
+
...provider
|
|
402
242
|
});
|
|
403
|
-
|
|
404
|
-
for (const
|
|
243
|
+
const nodeHost = createOpenCodeNodeHostBindings(api);
|
|
244
|
+
for (const command of nodeHost.commands) api.registerNodeHostCommand(command);
|
|
245
|
+
for (const policy of nodeHost.policies) api.registerNodeInvokePolicy(policy);
|
|
405
246
|
}
|
|
406
247
|
//#endregion
|
|
407
248
|
export { registerOpenCodeSessionCatalog };
|
|
@@ -7,6 +7,5 @@ const OPENCODE_LOCAL_SESSION_HOST_ID = "gateway";
|
|
|
7
7
|
const OPENCODE_SESSION_CATALOG_MAX_PAGE_LIMIT = 100;
|
|
8
8
|
const OPENCODE_NODE_INVOKE_TIMEOUT_MS = 35e3;
|
|
9
9
|
const OPENCODE_SESSION_ID_PATTERN = /^(?!-)[A-Za-z0-9._:-]{1,256}$/u;
|
|
10
|
-
var OpenCodeCatalogParamsError = class extends Error {};
|
|
11
10
|
//#endregion
|
|
12
|
-
export { OPENCODE_LOCAL_SESSION_HOST_ID, OPENCODE_NODE_INVOKE_TIMEOUT_MS, OPENCODE_SESSIONS_CAPABILITY, OPENCODE_SESSIONS_LIST_COMMAND, OPENCODE_SESSION_CATALOG_MAX_PAGE_LIMIT, OPENCODE_SESSION_ID_PATTERN, OPENCODE_SESSION_READ_COMMAND, OPENCODE_TERMINAL_RESUME_COMMAND
|
|
11
|
+
export { OPENCODE_LOCAL_SESSION_HOST_ID, OPENCODE_NODE_INVOKE_TIMEOUT_MS, OPENCODE_SESSIONS_CAPABILITY, OPENCODE_SESSIONS_LIST_COMMAND, OPENCODE_SESSION_CATALOG_MAX_PAGE_LIMIT, OPENCODE_SESSION_ID_PATTERN, OPENCODE_SESSION_READ_COMMAND, OPENCODE_TERMINAL_RESUME_COMMAND };
|
package/dist/session-catalog.js
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
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
|
|
72
|
+
const result = await runCommandBuffered([invocation.command, ...invocation.argv], {
|
|
73
|
+
baseEnv: {},
|
|
178
74
|
env,
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
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
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
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
|
-
|
|
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 || !
|
|
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
|
-
|
|
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
|
-
|
|
400
|
-
|
|
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 };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openclaw/opencode-provider",
|
|
3
|
-
"version": "2026.8.1-beta.
|
|
3
|
+
"version": "2026.8.1-beta.3",
|
|
4
4
|
"description": "OpenClaw OpenCode Zen provider plugin",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -18,10 +18,10 @@
|
|
|
18
18
|
"minHostVersion": ">=2026.7.2"
|
|
19
19
|
},
|
|
20
20
|
"compat": {
|
|
21
|
-
"pluginApi": ">=2026.8.1-beta.
|
|
21
|
+
"pluginApi": ">=2026.8.1-beta.3"
|
|
22
22
|
},
|
|
23
23
|
"build": {
|
|
24
|
-
"openclawVersion": "2026.8.1-beta.
|
|
24
|
+
"openclawVersion": "2026.8.1-beta.3",
|
|
25
25
|
"bundledDist": false
|
|
26
26
|
},
|
|
27
27
|
"release": {
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"README.md"
|
|
39
39
|
],
|
|
40
40
|
"peerDependencies": {
|
|
41
|
-
"openclaw": ">=2026.8.1-beta.
|
|
41
|
+
"openclaw": ">=2026.8.1-beta.3"
|
|
42
42
|
},
|
|
43
43
|
"peerDependenciesMeta": {
|
|
44
44
|
"openclaw": {
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
import { OPENCODE_NODE_INVOKE_TIMEOUT_MS, OPENCODE_SESSIONS_CAPABILITY, OPENCODE_SESSIONS_LIST_COMMAND, OPENCODE_SESSION_ID_PATTERN, OPENCODE_TERMINAL_RESUME_COMMAND } from "./session-catalog-shared.js";
|
|
2
|
-
import { listLocalOpenCodeSessionPage } from "./session-catalog.js";
|
|
3
|
-
import { decodeNodePtyResumeParams, resolveNodeHostExecutable, runNodePtyCommand } from "openclaw/plugin-sdk/node-host";
|
|
4
|
-
//#region extensions/opencode/session-catalog-terminal.ts
|
|
5
|
-
function validateOpenCodeThreadId(value) {
|
|
6
|
-
if (typeof value !== "string" || !OPENCODE_SESSION_ID_PATTERN.test(value)) throw new Error("INVALID_REQUEST: threadId is invalid");
|
|
7
|
-
return value;
|
|
8
|
-
}
|
|
9
|
-
async function requireLocalOpenCodeSession(threadId) {
|
|
10
|
-
const record = (await listLocalOpenCodeSessionPage({
|
|
11
|
-
searchTerm: threadId,
|
|
12
|
-
limit: 100
|
|
13
|
-
})).sessions.find((session) => session.threadId === threadId);
|
|
14
|
-
if (!record) throw new Error("OpenCode session is unavailable");
|
|
15
|
-
return record;
|
|
16
|
-
}
|
|
17
|
-
function createOpenCodeTerminalNodeHostCommand(isAvailable) {
|
|
18
|
-
return {
|
|
19
|
-
command: OPENCODE_TERMINAL_RESUME_COMMAND,
|
|
20
|
-
cap: OPENCODE_SESSIONS_CAPABILITY,
|
|
21
|
-
dangerous: false,
|
|
22
|
-
duplex: true,
|
|
23
|
-
isAvailable,
|
|
24
|
-
handle: async (paramsJSON, io) => {
|
|
25
|
-
if (!io) throw new Error("OpenCode terminal command requires duplex transport");
|
|
26
|
-
const params = decodeNodePtyResumeParams(paramsJSON, validateOpenCodeThreadId);
|
|
27
|
-
const record = await requireLocalOpenCodeSession(params.threadId);
|
|
28
|
-
const resolution = resolveNodeHostExecutable("opencode", {
|
|
29
|
-
env: process.env,
|
|
30
|
-
pathEnv: process.env.PATH ?? process.env.Path ?? "",
|
|
31
|
-
strategy: "direct"
|
|
32
|
-
});
|
|
33
|
-
if (!resolution) throw new Error("OpenCode CLI is unavailable");
|
|
34
|
-
return JSON.stringify(await runNodePtyCommand({
|
|
35
|
-
file: resolution.executable,
|
|
36
|
-
args: ["--session", params.threadId],
|
|
37
|
-
cwd: record.cwd,
|
|
38
|
-
cols: params.cols,
|
|
39
|
-
rows: params.rows
|
|
40
|
-
}, io));
|
|
41
|
-
}
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
async function resolveNodeOpenCodeSession(params) {
|
|
45
|
-
const raw = await params.runtime.nodes.invoke({
|
|
46
|
-
nodeId: params.nodeId,
|
|
47
|
-
command: OPENCODE_SESSIONS_LIST_COMMAND,
|
|
48
|
-
params: {
|
|
49
|
-
searchTerm: params.threadId,
|
|
50
|
-
limit: 100
|
|
51
|
-
},
|
|
52
|
-
timeoutMs: OPENCODE_NODE_INVOKE_TIMEOUT_MS,
|
|
53
|
-
scopes: ["operator.write"]
|
|
54
|
-
});
|
|
55
|
-
const record = params.parseNodeSessionPage(params.unwrapNodePayload(raw)).sessions.find((session) => session.threadId === params.threadId);
|
|
56
|
-
if (!record) throw new Error("OpenCode session is unavailable");
|
|
57
|
-
return record;
|
|
58
|
-
}
|
|
59
|
-
async function openOpenCodeCatalogTerminal(params) {
|
|
60
|
-
const title = `opencode --session ${params.threadId.slice(0, 12)}…`;
|
|
61
|
-
if (params.hostId === "gateway") {
|
|
62
|
-
const record = await requireLocalOpenCodeSession(params.threadId);
|
|
63
|
-
const resolution = resolveNodeHostExecutable("opencode", {
|
|
64
|
-
env: process.env,
|
|
65
|
-
pathEnv: process.env.PATH ?? "",
|
|
66
|
-
strategy: "fallback"
|
|
67
|
-
});
|
|
68
|
-
if (!resolution) throw new Error("OpenCode CLI is unavailable");
|
|
69
|
-
return {
|
|
70
|
-
kind: "local",
|
|
71
|
-
argv: [
|
|
72
|
-
resolution.executable,
|
|
73
|
-
"--session",
|
|
74
|
-
params.threadId
|
|
75
|
-
],
|
|
76
|
-
...record.cwd ? { cwd: record.cwd } : {},
|
|
77
|
-
...resolution.pathEnv ? { pathEnv: resolution.pathEnv } : {},
|
|
78
|
-
title
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
if (!params.hostId.startsWith("node:")) throw new Error("hostId is invalid");
|
|
82
|
-
const nodeId = params.hostId.slice(5);
|
|
83
|
-
if (!(await params.runtime.nodes.list()).nodes.find((candidate) => {
|
|
84
|
-
const commands = candidate.invocableCommands ?? candidate.commands;
|
|
85
|
-
return candidate.nodeId === nodeId && candidate.connected === true && commands?.includes("opencode.sessions.list.v1") === true && commands.includes("opencode.terminal.resume.v1");
|
|
86
|
-
})) throw new Error("paired-node OpenCode terminal is unavailable");
|
|
87
|
-
const record = await resolveNodeOpenCodeSession({
|
|
88
|
-
runtime: params.runtime,
|
|
89
|
-
nodeId,
|
|
90
|
-
threadId: params.threadId,
|
|
91
|
-
parseNodeSessionPage: params.parseNodeSessionPage,
|
|
92
|
-
unwrapNodePayload: params.unwrapNodePayload
|
|
93
|
-
});
|
|
94
|
-
return {
|
|
95
|
-
kind: "node",
|
|
96
|
-
nodeId,
|
|
97
|
-
command: OPENCODE_TERMINAL_RESUME_COMMAND,
|
|
98
|
-
paramsJSON: JSON.stringify({ threadId: params.threadId }),
|
|
99
|
-
...record.cwd ? { cwd: record.cwd } : {},
|
|
100
|
-
title
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
//#endregion
|
|
104
|
-
export { createOpenCodeTerminalNodeHostCommand, openOpenCodeCatalogTerminal };
|