@openclaw/opencode-provider 0.0.0 → 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/README.md +15 -2
- package/dist/doctor-contract-api.js +170 -0
- package/dist/index.js +742 -0
- package/dist/media-understanding-provider.js +25 -0
- package/dist/onboard.js +20 -0
- package/dist/provider-catalog.js +1218 -0
- package/dist/provider-discovery.js +14 -0
- package/dist/provider-policy-api.js +37 -0
- package/dist/session-catalog-plugin.js +248 -0
- package/dist/session-catalog-shared.js +11 -0
- package/dist/session-catalog.js +294 -0
- package/dist/session-upstream-activity.js +232 -0
- package/dist/stream.js +166 -0
- package/openclaw.plugin.json +685 -0
- package/package.json +43 -8
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { buildStaticOpencodeZenProviderConfig } from "./provider-catalog.js";
|
|
2
|
+
//#region extensions/opencode/provider-discovery.ts
|
|
3
|
+
const opencodeProviderDiscovery = {
|
|
4
|
+
id: "opencode",
|
|
5
|
+
label: "OpenCode Zen",
|
|
6
|
+
docsPath: "/providers/models",
|
|
7
|
+
auth: [],
|
|
8
|
+
staticCatalog: {
|
|
9
|
+
order: "simple",
|
|
10
|
+
run: async () => ({ provider: buildStaticOpencodeZenProviderConfig() })
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
//#endregion
|
|
14
|
+
export { opencodeProviderDiscovery as default };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { resolveClaudeThinkingProfile } from "openclaw/plugin-sdk/provider-model-shared";
|
|
2
|
+
//#region extensions/opencode/provider-policy-api.ts
|
|
3
|
+
const FIXED_REASONING_PROFILE = {
|
|
4
|
+
levels: [{
|
|
5
|
+
id: "off",
|
|
6
|
+
label: "always on"
|
|
7
|
+
}],
|
|
8
|
+
defaultLevel: "off"
|
|
9
|
+
};
|
|
10
|
+
const THINKING_LEVEL_IDS = /* @__PURE__ */ new Set([
|
|
11
|
+
"off",
|
|
12
|
+
"minimal",
|
|
13
|
+
"low",
|
|
14
|
+
"medium",
|
|
15
|
+
"high",
|
|
16
|
+
"xhigh",
|
|
17
|
+
"max"
|
|
18
|
+
]);
|
|
19
|
+
function resolveEffortThinkingProfile(efforts) {
|
|
20
|
+
if (!efforts || efforts.length === 0) return;
|
|
21
|
+
const acceptedLevelIds = ["off", ...efforts.map((effort) => effort === "none" ? "off" : effort)].filter((id) => THINKING_LEVEL_IDS.has(id)).filter((id, index, values) => values.indexOf(id) === index);
|
|
22
|
+
const levels = acceptedLevelIds.map((id) => ({ id }));
|
|
23
|
+
const levelIdSet = new Set(acceptedLevelIds);
|
|
24
|
+
return {
|
|
25
|
+
levels,
|
|
26
|
+
defaultLevel: levelIdSet.has("medium") ? "medium" : levelIdSet.has("high") ? "high" : levelIdSet.has("low") ? "low" : "off"
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function resolveThinkingProfile(params) {
|
|
30
|
+
const modelId = params.modelId.trim().toLowerCase();
|
|
31
|
+
if (modelId.startsWith("claude-")) return resolveClaudeThinkingProfile(modelId);
|
|
32
|
+
const effortProfile = resolveEffortThinkingProfile(params.compat?.supportedReasoningEfforts);
|
|
33
|
+
if (effortProfile) return effortProfile;
|
|
34
|
+
return params.reasoning === true && params.api !== "anthropic-messages" ? FIXED_REASONING_PROFILE : void 0;
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
export { resolveThinkingProfile };
|
|
@@ -0,0 +1,248 @@
|
|
|
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";
|
|
3
|
+
import { checkOpenCodeUpstreamActivity, linkContinuedOpenCodeSession } from "./session-upstream-activity.js";
|
|
4
|
+
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
5
|
+
import { accessSync, constants, statSync } from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import process from "node:process";
|
|
8
|
+
import { resolveAcpSessionAvailability } from "openclaw/plugin-sdk/acp-runtime";
|
|
9
|
+
import { resolveSessionAgentIds } from "openclaw/plugin-sdk/agent-runtime";
|
|
10
|
+
import { resolveNodeHostExecutable } from "openclaw/plugin-sdk/node-host";
|
|
11
|
+
import { createSessionCatalogFamily, createSessionCatalogNodeHostBindings, importSessionCatalogHistory, listAdoptedSessionCatalogSessions, sessionCatalogAdoptedSessionKey } from "openclaw/plugin-sdk/session-catalog";
|
|
12
|
+
//#region extensions/opencode/session-catalog-plugin.ts
|
|
13
|
+
const MAX_HOSTS = 100;
|
|
14
|
+
const ACPX_BACKEND_ID = "acpx";
|
|
15
|
+
const OPENCODE_ACP_AGENT_ID = "opencode";
|
|
16
|
+
const OPENCODE_ADOPTED_SESSION_KEY_PREFIX = "plugin:opencode:catalog-adopt:";
|
|
17
|
+
function executableOnPath(command, env) {
|
|
18
|
+
const pathValue = env.PATH ?? env.Path ?? "";
|
|
19
|
+
const delimiter = process.platform === "win32" ? ";" : path.delimiter;
|
|
20
|
+
const extensions = process.platform === "win32" ? (env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";") : [""];
|
|
21
|
+
for (const directory of pathValue.split(delimiter)) for (const extension of extensions) {
|
|
22
|
+
if (!directory.trim()) continue;
|
|
23
|
+
const candidate = path.join(directory, `${command}${extension}`);
|
|
24
|
+
try {
|
|
25
|
+
if (!statSync(candidate).isFile()) continue;
|
|
26
|
+
if (process.platform !== "win32") accessSync(candidate, constants.X_OK);
|
|
27
|
+
return true;
|
|
28
|
+
} catch {}
|
|
29
|
+
}
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
function parseNodeParams(paramsJSON) {
|
|
33
|
+
if (!paramsJSON) return;
|
|
34
|
+
try {
|
|
35
|
+
return JSON.parse(paramsJSON);
|
|
36
|
+
} catch (error) {
|
|
37
|
+
throw new Error("OpenCode session parameters must be valid JSON", { cause: error });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function fullConfigCatalogEnabled(config) {
|
|
41
|
+
if (!isRecord(config) || !isRecord(config.plugins) || !isRecord(config.plugins.entries)) return true;
|
|
42
|
+
const entry = config.plugins.entries.opencode;
|
|
43
|
+
if (!isRecord(entry) || !isRecord(entry.config) || !isRecord(entry.config.sessionCatalog)) return true;
|
|
44
|
+
return entry.config.sessionCatalog.enabled !== false;
|
|
45
|
+
}
|
|
46
|
+
function isOpenCodeSessionCatalogEnabled(pluginConfig) {
|
|
47
|
+
return !isRecord(pluginConfig) || !isRecord(pluginConfig.sessionCatalog) || pluginConfig.sessionCatalog.enabled !== false;
|
|
48
|
+
}
|
|
49
|
+
function openCodeUsesProcessHomeFallback(env) {
|
|
50
|
+
return !env.OPENCODE_DB?.trim() && !path.isAbsolute(env.XDG_DATA_HOME?.trim() ?? "");
|
|
51
|
+
}
|
|
52
|
+
function assertOpenCodeLocalAccess(hostId, allowProcessHomeFallback) {
|
|
53
|
+
if (hostId === "gateway" && allowProcessHomeFallback === false && openCodeUsesProcessHomeFallback(process.env)) throw new Error("local OpenCode sessions are unavailable in isolated state");
|
|
54
|
+
}
|
|
55
|
+
function currentOpenCodeCatalogConfig(api) {
|
|
56
|
+
return api.runtime.config?.current?.() ?? api.config ?? {};
|
|
57
|
+
}
|
|
58
|
+
function listAdoptedOpenCodeSessions(api, agentId, sessionEntries) {
|
|
59
|
+
return listAdoptedSessionCatalogSessions({
|
|
60
|
+
...agentId ? { agentId } : {},
|
|
61
|
+
config: currentOpenCodeCatalogConfig(api),
|
|
62
|
+
pluginId: api.id,
|
|
63
|
+
runtime: api.runtime,
|
|
64
|
+
sessionEntries,
|
|
65
|
+
sourceFromEntry: (entry) => {
|
|
66
|
+
const opencode = isRecord(entry.pluginExtensions?.opencode) ? entry.pluginExtensions.opencode : void 0;
|
|
67
|
+
const marker = opencode && isRecord(opencode.sessionCatalog) ? opencode.sessionCatalog : void 0;
|
|
68
|
+
return marker && typeof marker.sourceThreadId === "string" ? {
|
|
69
|
+
hostId: OPENCODE_LOCAL_SESSION_HOST_ID,
|
|
70
|
+
threadId: marker.sourceThreadId
|
|
71
|
+
} : void 0;
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
}
|
|
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 } }
|
|
103
|
+
},
|
|
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"
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
function registerOpenCodeSessionCatalog(api) {
|
|
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);
|
|
237
|
+
api.registerSessionCatalog({
|
|
238
|
+
id: "opencode",
|
|
239
|
+
label: "OpenCode",
|
|
240
|
+
supportsProcessHomeIsolation: true,
|
|
241
|
+
...provider
|
|
242
|
+
});
|
|
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);
|
|
246
|
+
}
|
|
247
|
+
//#endregion
|
|
248
|
+
export { registerOpenCodeSessionCatalog };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
//#region extensions/opencode/session-catalog-shared.ts
|
|
2
|
+
const OPENCODE_SESSIONS_LIST_COMMAND = "opencode.sessions.list.v1";
|
|
3
|
+
const OPENCODE_SESSION_READ_COMMAND = "opencode.sessions.read.v1";
|
|
4
|
+
const OPENCODE_TERMINAL_RESUME_COMMAND = "opencode.terminal.resume.v1";
|
|
5
|
+
const OPENCODE_SESSIONS_CAPABILITY = "opencode-sessions";
|
|
6
|
+
const OPENCODE_LOCAL_SESSION_HOST_ID = "gateway";
|
|
7
|
+
const OPENCODE_SESSION_CATALOG_MAX_PAGE_LIMIT = 100;
|
|
8
|
+
const OPENCODE_NODE_INVOKE_TIMEOUT_MS = 35e3;
|
|
9
|
+
const OPENCODE_SESSION_ID_PATTERN = /^(?!-)[A-Za-z0-9._:-]{1,256}$/u;
|
|
10
|
+
//#endregion
|
|
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 };
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import { OPENCODE_SESSION_ID_PATTERN } from "./session-catalog-shared.js";
|
|
2
|
+
import { isRecord, normalizeBoundedOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
3
|
+
import process from "node:process";
|
|
4
|
+
import { sessionCatalogPaging } from "openclaw/plugin-sdk/session-catalog";
|
|
5
|
+
import { runCommandBuffered } from "openclaw/plugin-sdk/process-runtime";
|
|
6
|
+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
7
|
+
import { materializeWindowsSpawnProgram, resolveWindowsSpawnProgram } from "openclaw/plugin-sdk/windows-spawn";
|
|
8
|
+
//#region extensions/opencode/session-catalog.ts
|
|
9
|
+
const LOCAL_HOST_ID = "gateway";
|
|
10
|
+
const MAX_SEARCH_LENGTH = 500;
|
|
11
|
+
const MAX_CLI_LIST_SESSIONS = 1e4;
|
|
12
|
+
const MAX_CLI_OUTPUT_BYTES = 32 * 1024 * 1024;
|
|
13
|
+
const CLI_TIMEOUT_MS = 3e4;
|
|
14
|
+
const OPENCODE_QUERY_CACHE_TTL_MS = 32e3;
|
|
15
|
+
const OPENCODE_QUERY_CACHE_MAX_ENTRIES = 32;
|
|
16
|
+
const SAFE_ENV_KEYS = [
|
|
17
|
+
"APPDATA",
|
|
18
|
+
"COMSPEC",
|
|
19
|
+
"HOME",
|
|
20
|
+
"LANG",
|
|
21
|
+
"LC_ALL",
|
|
22
|
+
"LOCALAPPDATA",
|
|
23
|
+
"OPENCODE_DB",
|
|
24
|
+
"PATH",
|
|
25
|
+
"Path",
|
|
26
|
+
"PATHEXT",
|
|
27
|
+
"SYSTEMROOT",
|
|
28
|
+
"TEMP",
|
|
29
|
+
"TMP",
|
|
30
|
+
"TMPDIR",
|
|
31
|
+
"USERPROFILE",
|
|
32
|
+
"WINDIR",
|
|
33
|
+
"XDG_CACHE_HOME",
|
|
34
|
+
"XDG_CONFIG_HOME",
|
|
35
|
+
"XDG_DATA_HOME",
|
|
36
|
+
"XDG_STATE_HOME"
|
|
37
|
+
];
|
|
38
|
+
const openCodeConfigIdentities = /* @__PURE__ */ new WeakMap();
|
|
39
|
+
const openCodeQueryCache = /* @__PURE__ */ new Map();
|
|
40
|
+
let nextOpenCodeConfigIdentity = 1;
|
|
41
|
+
function openCodeQueryCacheKey(query, configIdentity) {
|
|
42
|
+
let identity = openCodeConfigIdentities.get(configIdentity);
|
|
43
|
+
if (identity === void 0) {
|
|
44
|
+
identity = nextOpenCodeConfigIdentity++;
|
|
45
|
+
openCodeConfigIdentities.set(configIdentity, identity);
|
|
46
|
+
}
|
|
47
|
+
const environment = SAFE_ENV_KEYS.map((key) => `${key}=${process.env[key] ?? ""}`).join("\0");
|
|
48
|
+
return `${String(identity)}\0${environment}\0${query}`;
|
|
49
|
+
}
|
|
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({
|
|
61
|
+
command: "opencode",
|
|
62
|
+
platform: process.platform,
|
|
63
|
+
env: process.env,
|
|
64
|
+
execPath: process.execPath,
|
|
65
|
+
packageName: "opencode-ai"
|
|
66
|
+
}), args);
|
|
67
|
+
const env = {
|
|
68
|
+
OPENCODE_PURE: "1",
|
|
69
|
+
NO_COLOR: "1"
|
|
70
|
+
};
|
|
71
|
+
for (const key of SAFE_ENV_KEYS) if (process.env[key] !== void 0) env[key] = process.env[key];
|
|
72
|
+
const result = await runCommandBuffered([invocation.command, ...invocation.argv], {
|
|
73
|
+
baseEnv: {},
|
|
74
|
+
env,
|
|
75
|
+
input: "",
|
|
76
|
+
maxCombinedOutputBytes: MAX_CLI_OUTPUT_BYTES,
|
|
77
|
+
maxOutputBytes: MAX_CLI_OUTPUT_BYTES,
|
|
78
|
+
terminateOnOutputError: true,
|
|
79
|
+
timeoutMs: CLI_TIMEOUT_MS
|
|
80
|
+
});
|
|
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 });
|
|
85
|
+
}
|
|
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");
|
|
92
|
+
}
|
|
93
|
+
async function queryOpenCodeDatabase(query) {
|
|
94
|
+
const output = await runOpenCode([
|
|
95
|
+
"--pure",
|
|
96
|
+
"db",
|
|
97
|
+
query,
|
|
98
|
+
"--format",
|
|
99
|
+
"json"
|
|
100
|
+
]);
|
|
101
|
+
return output.trim() ? JSON.parse(output) : [];
|
|
102
|
+
}
|
|
103
|
+
async function queryCachedOpenCodeSessions(query, options) {
|
|
104
|
+
const key = openCodeQueryCacheKey(query, options.configIdentity ?? process.env);
|
|
105
|
+
const cached = openCodeQueryCache.get(key);
|
|
106
|
+
if (options.forceRefresh !== true && cached && cached.expiresAt > Date.now()) {
|
|
107
|
+
openCodeQueryCache.delete(key);
|
|
108
|
+
openCodeQueryCache.set(key, cached);
|
|
109
|
+
return await cached.result;
|
|
110
|
+
}
|
|
111
|
+
if (cached) openCodeQueryCache.delete(key);
|
|
112
|
+
const result = queryOpenCodeDatabase(query);
|
|
113
|
+
const entry = {
|
|
114
|
+
expiresAt: Date.now() + OPENCODE_QUERY_CACHE_TTL_MS,
|
|
115
|
+
result
|
|
116
|
+
};
|
|
117
|
+
openCodeQueryCache.set(key, entry);
|
|
118
|
+
while (openCodeQueryCache.size > OPENCODE_QUERY_CACHE_MAX_ENTRIES) {
|
|
119
|
+
const oldest = openCodeQueryCache.keys().next();
|
|
120
|
+
if (oldest.done) break;
|
|
121
|
+
openCodeQueryCache.delete(oldest.value);
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
const value = await result;
|
|
125
|
+
entry.resolved = true;
|
|
126
|
+
return value;
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (openCodeQueryCache.get(key) === entry) if (cached?.resolved) openCodeQueryCache.set(key, cached);
|
|
129
|
+
else openCodeQueryCache.delete(key);
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
async function exportOpenCodeSession(threadId) {
|
|
134
|
+
const output = await runOpenCode([
|
|
135
|
+
"--pure",
|
|
136
|
+
"export",
|
|
137
|
+
threadId
|
|
138
|
+
]);
|
|
139
|
+
return JSON.parse(output);
|
|
140
|
+
}
|
|
141
|
+
function parseOpenCodeSession(value) {
|
|
142
|
+
if (!isRecord(value)) return;
|
|
143
|
+
const threadId = normalizeBoundedOptionalString(value.id, 256);
|
|
144
|
+
if (!threadId || !OPENCODE_SESSION_ID_PATTERN.test(threadId)) return;
|
|
145
|
+
const name = normalizeBoundedOptionalString(value.title, 1e3);
|
|
146
|
+
const cwd = normalizeBoundedOptionalString(value.directory, 4096);
|
|
147
|
+
const createdAt = typeof value.created === "number" && Number.isFinite(value.created) ? value.created : void 0;
|
|
148
|
+
const updatedAt = typeof value.updated === "number" && Number.isFinite(value.updated) ? value.updated : void 0;
|
|
149
|
+
return {
|
|
150
|
+
threadId,
|
|
151
|
+
...name ? { name } : {},
|
|
152
|
+
...cwd ? { cwd } : {},
|
|
153
|
+
status: "stored",
|
|
154
|
+
...createdAt !== void 0 ? { createdAt } : {},
|
|
155
|
+
...updatedAt !== void 0 ? {
|
|
156
|
+
updatedAt,
|
|
157
|
+
recencyAt: updatedAt
|
|
158
|
+
} : {},
|
|
159
|
+
source: "opencode-cli",
|
|
160
|
+
modelProvider: "opencode",
|
|
161
|
+
archived: false,
|
|
162
|
+
canContinue: true,
|
|
163
|
+
canArchive: false
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
async function listLocalOpenCodeSessionPage(value, options = {}) {
|
|
167
|
+
const params = sessionCatalogPaging.parseListParams(value, {
|
|
168
|
+
searchMaxLength: MAX_SEARCH_LENGTH,
|
|
169
|
+
messages: OPENCODE_PARAMETER_MESSAGES
|
|
170
|
+
});
|
|
171
|
+
const offset = sessionCatalogPaging.decodeCursor(params.cursor);
|
|
172
|
+
const requestedCount = params.searchTerm ? MAX_CLI_LIST_SESSIONS : Math.min(MAX_CLI_LIST_SESSIONS, offset + params.limit + 1);
|
|
173
|
+
const parsed = await queryCachedOpenCodeSessions([
|
|
174
|
+
"SELECT id, title, time_created AS created, time_updated AS updated,",
|
|
175
|
+
"project_id AS projectId, directory FROM session",
|
|
176
|
+
"WHERE parent_id IS NULL AND time_archived IS NULL",
|
|
177
|
+
`ORDER BY time_updated DESC, id DESC LIMIT ${String(requestedCount)}`
|
|
178
|
+
].join(" "), options);
|
|
179
|
+
if (!Array.isArray(parsed) || parsed.length > MAX_CLI_LIST_SESSIONS) throw new Error("OpenCode returned an invalid session list");
|
|
180
|
+
const needle = params.searchTerm?.toLocaleLowerCase();
|
|
181
|
+
const sessions = parsed.flatMap((entry) => {
|
|
182
|
+
const session = parseOpenCodeSession(entry);
|
|
183
|
+
return session ? [session] : [];
|
|
184
|
+
}).filter((session) => {
|
|
185
|
+
if (!needle) return true;
|
|
186
|
+
return [
|
|
187
|
+
session.threadId,
|
|
188
|
+
session.name,
|
|
189
|
+
session.cwd
|
|
190
|
+
].some((field) => field?.toLocaleLowerCase().includes(needle));
|
|
191
|
+
});
|
|
192
|
+
const page = sessions.slice(offset, offset + params.limit);
|
|
193
|
+
return {
|
|
194
|
+
sessions: page,
|
|
195
|
+
...offset + page.length < sessions.length ? { nextCursor: sessionCatalogPaging.encodeCursor(offset + page.length) } : {}
|
|
196
|
+
};
|
|
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
|
+
}
|
|
206
|
+
function jsonText(value, maxLength = 2e4) {
|
|
207
|
+
try {
|
|
208
|
+
const text = JSON.stringify(value);
|
|
209
|
+
return text.length > maxLength ? `${truncateUtf16Safe(text, maxLength)}…` : text;
|
|
210
|
+
} catch {
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
function timestampFromInfo(info) {
|
|
215
|
+
if (!isRecord(info.time) || typeof info.time.created !== "number") return;
|
|
216
|
+
const date = new Date(info.time.created);
|
|
217
|
+
return Number.isNaN(date.getTime()) ? void 0 : date.toISOString();
|
|
218
|
+
}
|
|
219
|
+
function openCodeTranscriptItems(value) {
|
|
220
|
+
if (!isRecord(value) || !Array.isArray(value.messages)) throw new Error("OpenCode returned an invalid session export");
|
|
221
|
+
return value.messages.flatMap((message) => {
|
|
222
|
+
if (!isRecord(message) || !isRecord(message.info) || !Array.isArray(message.parts)) return [];
|
|
223
|
+
const info = message.info;
|
|
224
|
+
const role = info.role;
|
|
225
|
+
const messageId = normalizeBoundedOptionalString(info.id, 256);
|
|
226
|
+
const timestamp = timestampFromInfo(info);
|
|
227
|
+
const modelId = role === "assistant" ? normalizeBoundedOptionalString(info.modelID, 256) : isRecord(info.model) ? normalizeBoundedOptionalString(info.model.modelID, 256) : void 0;
|
|
228
|
+
const providerId = role === "assistant" ? normalizeBoundedOptionalString(info.providerID, 256) : isRecord(info.model) ? normalizeBoundedOptionalString(info.model.providerID, 256) : void 0;
|
|
229
|
+
const model = providerId && modelId ? `${providerId}/${modelId}` : modelId;
|
|
230
|
+
return message.parts.flatMap((part, partIndex) => {
|
|
231
|
+
if (!isRecord(part)) return [];
|
|
232
|
+
const id = normalizeBoundedOptionalString(part.id, 256) ?? (messageId ? `${messageId}:${String(partIndex)}` : void 0);
|
|
233
|
+
const common = {
|
|
234
|
+
...id ? { id } : {},
|
|
235
|
+
...timestamp ? { timestamp } : {},
|
|
236
|
+
...model ? { model } : {}
|
|
237
|
+
};
|
|
238
|
+
if (part.type === "text" && typeof part.text === "string") return [{
|
|
239
|
+
...common,
|
|
240
|
+
type: role === "user" ? "userMessage" : "agentMessage",
|
|
241
|
+
text: part.text
|
|
242
|
+
}];
|
|
243
|
+
if (part.type === "reasoning" && typeof part.text === "string") return [{
|
|
244
|
+
...common,
|
|
245
|
+
type: "reasoning",
|
|
246
|
+
text: part.text
|
|
247
|
+
}];
|
|
248
|
+
if (part.type === "tool") {
|
|
249
|
+
const tool = normalizeBoundedOptionalString(part.tool, 256) ?? "tool";
|
|
250
|
+
const state = isRecord(part.state) ? part.state : void 0;
|
|
251
|
+
const callText = state && "input" in state ? jsonText(state.input) : void 0;
|
|
252
|
+
const resultText = state?.status === "completed" && typeof state.output === "string" ? state.output : state?.status === "error" && typeof state.error === "string" ? state.error : void 0;
|
|
253
|
+
return [{
|
|
254
|
+
...common,
|
|
255
|
+
type: "toolCall",
|
|
256
|
+
text: callText ? `${tool}\n${callText}` : tool
|
|
257
|
+
}, ...resultText ? [{
|
|
258
|
+
...common,
|
|
259
|
+
...id ? { id: `${id}:result` } : {},
|
|
260
|
+
type: "toolResult",
|
|
261
|
+
text: resultText
|
|
262
|
+
}] : []];
|
|
263
|
+
}
|
|
264
|
+
if (part.type === "file") {
|
|
265
|
+
const filename = normalizeBoundedOptionalString(part.filename, 1e3);
|
|
266
|
+
const mime = normalizeBoundedOptionalString(part.mime, 256);
|
|
267
|
+
return [{
|
|
268
|
+
...common,
|
|
269
|
+
type: "other",
|
|
270
|
+
text: `[Attachment${filename ? `: ${filename}` : ""}${mime ? ` (${mime})` : ""}]`
|
|
271
|
+
}];
|
|
272
|
+
}
|
|
273
|
+
return [];
|
|
274
|
+
});
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
async function readLocalOpenCodeTranscriptPage(value) {
|
|
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);
|
|
286
|
+
return {
|
|
287
|
+
hostId: LOCAL_HOST_ID,
|
|
288
|
+
label: "Local OpenCode",
|
|
289
|
+
threadId: params.threadId,
|
|
290
|
+
...page
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
//#endregion
|
|
294
|
+
export { exportOpenCodeSession, isExactOpenCodeSessionCursor, listLocalOpenCodeSessionPage, queryOpenCodeDatabase, readLocalOpenCodeTranscriptPage, requireLocalOpenCodeSession };
|