nemo-fabric-adapters-opencode 0.0.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,673 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { LifecycleError } from "nemo-fabric-adapters-common";
4
+ import { randomUUID } from "node:crypto";
5
+ import { realpath, stat } from "node:fs/promises";
6
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
7
+ import { selectModel, selectSystemInstruction } from "./configuration.js";
8
+ import { ModelEndpointProxy } from "./model-endpoint-proxy.js";
9
+ // Fabric invokes OpenCode non-interactively. Session rules are evaluated after
10
+ // OpenCode's agent defaults, so they override upstream "ask" rules without
11
+ // changing the permissions of other OpenCode sessions in the process.
12
+ const NONINTERACTIVE_SESSION_PERMISSIONS = [
13
+ { action: "external_directory", resource: "*", effect: "deny" },
14
+ { action: "read", resource: "*.env", effect: "deny" },
15
+ { action: "read", resource: "*.env.*", effect: "deny" },
16
+ { action: "read", resource: "*.env.example", effect: "allow" },
17
+ { action: "question", resource: "*", effect: "deny" },
18
+ ];
19
+ // OpenCode allows 30 seconds each for MCP transport startup and initial tool
20
+ // catalog discovery. Keep the Fabric readiness deadline aligned with both.
21
+ const MCP_CONNECTION_TIMEOUT_MS = 65_000;
22
+ const MCP_CONNECTION_POLL_INTERVAL_MS = 50;
23
+ const HTTP_HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u;
24
+ function loopbackHostname(hostname) {
25
+ return hostname === "localhost" || hostname === "::1" || hostname === "[::1]" || /^127(?:\.\d{1,3}){3}$/u.test(hostname);
26
+ }
27
+ /**
28
+ * OpenCode's Promise SDK accepts embedding overrides. They set the
29
+ * location-specific configuration and instruction services to OpenCode's
30
+ * documented `project: false, global: false` profile while leaving the session
31
+ * location at the Fabric workspace.
32
+ */
33
+ async function loadIsolatedEmbedOptions(configContent) {
34
+ const [{ Config }, { InstructionDiscovery }] = await Promise.all([
35
+ import("@opencode/core/config"),
36
+ import("@opencode/core/instruction-discovery"),
37
+ ]);
38
+ return {
39
+ overrides: [
40
+ Config.node.replace(Config.configured({ project: false, global: false, content: configContent })),
41
+ InstructionDiscovery.node.replace(InstructionDiscovery.configured({ project: false, global: false })),
42
+ ],
43
+ };
44
+ }
45
+ function hostConfigContent(model, baseUrl = model.baseUrl, systemInstruction, skillPaths = [], mcpServers = {}) {
46
+ const literals = new Map();
47
+ const literal = (value) => {
48
+ const placeholder = `__NEMO_FABRIC_OPENCODE_LITERAL_${randomUUID()}__`;
49
+ literals.set(placeholder, value);
50
+ return placeholder;
51
+ };
52
+ const provider = {
53
+ settings: { apiKey: `{env:${model.apiKeyEnv}}` },
54
+ };
55
+ if (baseUrl !== undefined) {
56
+ Object.assign(provider, {
57
+ package: "aisdk:@ai-sdk/openai-compatible",
58
+ settings: { ...provider.settings, baseURL: baseUrl },
59
+ models: {
60
+ [model.model]: model.sampling === undefined
61
+ ? {}
62
+ : {
63
+ body: {
64
+ ...(model.sampling.temperature === undefined ? {} : { temperature: model.sampling.temperature }),
65
+ ...(model.sampling.topP === undefined ? {} : { top_p: model.sampling.topP }),
66
+ },
67
+ },
68
+ },
69
+ });
70
+ }
71
+ const configuredMcpServers = Object.fromEntries(Object.entries(mcpServers).map(([name, server]) => [
72
+ literal(name),
73
+ server.type === "local"
74
+ ? {
75
+ type: "local",
76
+ command: server.command.map(literal),
77
+ ...(server.environment === undefined
78
+ ? {}
79
+ : {
80
+ environment: Object.fromEntries(Object.entries(server.environment).map(([key, value]) => [literal(key), literal(value)])),
81
+ }),
82
+ }
83
+ : {
84
+ type: "remote",
85
+ url: literal(server.url),
86
+ ...(server.headers === undefined
87
+ ? {}
88
+ : {
89
+ headers: Object.fromEntries(Object.entries(server.headers).map(([key, value]) => [literal(key), literal(value)])),
90
+ }),
91
+ oauth: false,
92
+ },
93
+ ]));
94
+ let content = JSON.stringify({
95
+ providers: {
96
+ [model.provider]: provider,
97
+ },
98
+ ...(systemInstruction === undefined ? {} : { agents: { build: { system: literal(systemInstruction) } } }),
99
+ ...(skillPaths.length === 0 ? {} : { skills: skillPaths.map(literal) }),
100
+ ...(Object.keys(configuredMcpServers).length === 0 ? {} : { mcp: { servers: configuredMcpServers } }),
101
+ });
102
+ for (const [placeholder, value] of literals) {
103
+ const encoded = JSON.stringify(value).replaceAll("{", "\\u007b");
104
+ content = content.replace(JSON.stringify(placeholder), () => encoded);
105
+ }
106
+ return content;
107
+ }
108
+ async function resolveSkills(baseDir, configured) {
109
+ const skills = [];
110
+ for (const entry of configured) {
111
+ if (typeof entry !== "string") {
112
+ throw new LifecycleError("opencode_invalid_skill", "OpenCode skill paths must be strings");
113
+ }
114
+ let candidate;
115
+ try {
116
+ candidate = await realpath(resolve(baseDir, entry));
117
+ }
118
+ catch {
119
+ throw new LifecycleError("opencode_skill_not_found", "A configured NeMo Fabric skill path does not exist");
120
+ }
121
+ try {
122
+ if (!(await stat(candidate)).isDirectory()) {
123
+ throw new Error("not a directory");
124
+ }
125
+ }
126
+ catch {
127
+ throw new LifecycleError("opencode_skill_invalid", "NeMo Fabric skill paths must be directories");
128
+ }
129
+ let location;
130
+ try {
131
+ location = await realpath(join(candidate, "SKILL.md"));
132
+ if (!(await stat(location)).isFile()) {
133
+ throw new Error("not a file");
134
+ }
135
+ }
136
+ catch {
137
+ throw new LifecycleError("opencode_skill_invalid", "NeMo Fabric skill directories must contain a SKILL.md file");
138
+ }
139
+ skills.push({ directory: candidate, location });
140
+ }
141
+ return skills;
142
+ }
143
+ async function verifyLoadedSkills(client, workspace, configured) {
144
+ if (configured.length === 0) {
145
+ return;
146
+ }
147
+ let loaded;
148
+ try {
149
+ await client.plugin.awaitActivation({ location: { directory: workspace } });
150
+ loaded = (await client.skill.list({ location: { directory: workspace } })).data;
151
+ }
152
+ catch {
153
+ throw new LifecycleError("opencode_skill_status_unavailable", "OpenCode could not determine the configured skill status");
154
+ }
155
+ const byLocation = new Map(loaded
156
+ .filter((skill) => typeof skill.name === "string" && typeof skill.location === "string")
157
+ .map((skill) => [skill.location, skill]));
158
+ const configuredLocations = new Set(configured.map((skill) => skill.location));
159
+ const hasUnexpectedConfiguredSkill = Array.from(byLocation.keys()).some((location) => !configuredLocations.has(location) &&
160
+ configured.some((skill) => {
161
+ const relativeLocation = relative(skill.directory, location);
162
+ return relativeLocation !== ".." && !relativeLocation.startsWith(`..${sep}`) && !isAbsolute(relativeLocation);
163
+ }));
164
+ if (hasUnexpectedConfiguredSkill) {
165
+ throw new LifecycleError("opencode_skill_unexpected", "OpenCode loaded a skill that was not configured by NeMo Fabric");
166
+ }
167
+ const configuredSkills = configured.map((skill) => byLocation.get(skill.location));
168
+ if (configuredSkills.some((skill) => skill === undefined)) {
169
+ throw new LifecycleError("opencode_skill_load_failed", "OpenCode did not load every configured NeMo Fabric skill");
170
+ }
171
+ const names = new Set();
172
+ for (const skill of configuredSkills) {
173
+ if (skill === undefined) {
174
+ continue;
175
+ }
176
+ if (names.has(skill.name)) {
177
+ throw new LifecycleError("opencode_skill_name_duplicate", "Configured NeMo Fabric skills must have distinct names");
178
+ }
179
+ names.add(skill.name);
180
+ }
181
+ }
182
+ function expandMcpHeaders(headers, configuredEnvironment, parentEnvironment) {
183
+ if (headers === undefined) {
184
+ return undefined;
185
+ }
186
+ return Object.fromEntries(Object.entries(headers).map(([name, value]) => {
187
+ const expanded = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/gu, (_reference, variable) => {
188
+ const configured = configuredEnvironment[variable];
189
+ if (Object.hasOwn(configuredEnvironment, variable) && configured !== undefined) {
190
+ return configured;
191
+ }
192
+ const inherited = parentEnvironment[variable];
193
+ if (Object.hasOwn(parentEnvironment, variable) && inherited !== undefined) {
194
+ return inherited;
195
+ }
196
+ throw new LifecycleError("opencode_mcp_header_variable_missing", "A configured OpenCode MCP header references an environment variable that is not available");
197
+ });
198
+ validateMcpHttpHeader(name, expanded);
199
+ return [name, expanded];
200
+ }));
201
+ }
202
+ function validateMcpHttpHeader(name, value) {
203
+ if (!HTTP_HEADER_NAME.test(name) ||
204
+ value.length === 0 ||
205
+ value.trim().length === 0 ||
206
+ value.startsWith(" ") ||
207
+ value.startsWith("\t") ||
208
+ value.endsWith(" ") ||
209
+ value.endsWith("\t")) {
210
+ throw new LifecycleError("opencode_mcp_invalid_header", "A configured OpenCode MCP HTTP header is invalid");
211
+ }
212
+ for (const character of value) {
213
+ const codePoint = character.codePointAt(0);
214
+ if (codePoint === undefined ||
215
+ codePoint > 0xFF ||
216
+ (codePoint < 0x20 && codePoint !== 0x09) ||
217
+ codePoint === 0x7F) {
218
+ throw new LifecycleError("opencode_mcp_invalid_header", "A configured OpenCode MCP HTTP header is invalid");
219
+ }
220
+ }
221
+ }
222
+ function selectMcpServers(config, configuredEnvironment, parentEnvironment) {
223
+ const servers = Object.create(null);
224
+ for (const [name, server] of Object.entries(config.mcp?.servers ?? {})) {
225
+ if (server.authentication !== undefined && server.authentication !== null) {
226
+ throw new LifecycleError("opencode_mcp_authentication_unsupported", "OpenCode MCP authentication is unsupported; configure a custom authorization header instead");
227
+ }
228
+ if ((server.allowed_tools !== undefined && server.allowed_tools !== null) ||
229
+ (server.blocked_tools?.length ?? 0) > 0) {
230
+ throw new LifecycleError("opencode_mcp_tool_filters_unsupported", "OpenCode MCP per-server tool filters are unsupported");
231
+ }
232
+ if (server.transport === "stdio") {
233
+ if (Object.keys(server.custom_headers ?? {}).length > 0) {
234
+ throw new LifecycleError("opencode_mcp_invalid_server", "OpenCode stdio MCP servers do not accept custom HTTP headers");
235
+ }
236
+ servers[name] = {
237
+ type: "local",
238
+ command: [server.url, ...(server.args ?? [])],
239
+ ...(Object.keys(server.env ?? {}).length === 0 ? {} : { environment: server.env }),
240
+ };
241
+ continue;
242
+ }
243
+ if (server.transport === "streamable-http") {
244
+ if ((server.args?.length ?? 0) > 0) {
245
+ throw new LifecycleError("opencode_mcp_invalid_server", "OpenCode streamable-HTTP MCP servers do not accept command arguments");
246
+ }
247
+ if (Object.keys(server.env ?? {}).length > 0) {
248
+ throw new LifecycleError("opencode_mcp_invalid_server", "OpenCode streamable-HTTP MCP servers do not accept environment variables");
249
+ }
250
+ let endpoint;
251
+ try {
252
+ endpoint = new URL(server.url);
253
+ }
254
+ catch {
255
+ throw new LifecycleError("opencode_mcp_invalid_server", "OpenCode streamable-HTTP MCP servers require an HTTP or HTTPS URL");
256
+ }
257
+ if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") {
258
+ throw new LifecycleError("opencode_mcp_invalid_server", "OpenCode streamable-HTTP MCP servers require an HTTP or HTTPS URL");
259
+ }
260
+ if (endpoint.protocol === "http:" && !loopbackHostname(endpoint.hostname)) {
261
+ throw new LifecycleError("opencode_mcp_invalid_server", "OpenCode streamable-HTTP MCP servers require HTTPS unless the endpoint is loopback");
262
+ }
263
+ servers[name] = {
264
+ type: "remote",
265
+ url: server.url,
266
+ ...(Object.keys(server.custom_headers ?? {}).length === 0
267
+ ? {}
268
+ : { headers: expandMcpHeaders(server.custom_headers, configuredEnvironment, parentEnvironment) }),
269
+ oauth: false,
270
+ };
271
+ continue;
272
+ }
273
+ throw new LifecycleError("opencode_mcp_transport_unsupported", `OpenCode does not support MCP transport ${JSON.stringify(server.transport)}; supported transports: stdio, streamable-http`, {
274
+ metadata: {
275
+ field: `mcp.servers.${name}.transport`,
276
+ transport: server.transport,
277
+ supported_transports: ["stdio", "streamable-http"],
278
+ },
279
+ });
280
+ }
281
+ return servers;
282
+ }
283
+ async function waitForMcpConnections(client, workspace, servers) {
284
+ if (servers.length === 0) {
285
+ return;
286
+ }
287
+ const deadline = Date.now() + MCP_CONNECTION_TIMEOUT_MS;
288
+ while (true) {
289
+ const remainingMs = deadline - Date.now();
290
+ if (remainingMs <= 0) {
291
+ throw new LifecycleError("opencode_mcp_connection_timeout", "Timed out waiting for configured OpenCode MCP servers to connect", { metadata: { servers } });
292
+ }
293
+ const signal = AbortSignal.timeout(remainingMs);
294
+ let statusByServer;
295
+ try {
296
+ const listed = await client.mcp.list({ location: { directory: workspace } }, { signal });
297
+ statusByServer = new Map(listed.data.map((server) => [server.name, server.status.status]));
298
+ }
299
+ catch {
300
+ if (signal.aborted) {
301
+ throw new LifecycleError("opencode_mcp_connection_timeout", "Timed out waiting for configured OpenCode MCP servers to connect", { metadata: { servers } });
302
+ }
303
+ throw new LifecycleError("opencode_mcp_status_unavailable", "OpenCode could not determine the configured MCP connection status");
304
+ }
305
+ for (const name of servers) {
306
+ const status = statusByServer.get(name);
307
+ if (status !== undefined && status !== "pending" && status !== "connected") {
308
+ throw new LifecycleError("opencode_mcp_connection_failed", "A configured OpenCode MCP server did not connect", { metadata: { server: name, status } });
309
+ }
310
+ }
311
+ if (servers.every((name) => statusByServer.get(name) === "connected")) {
312
+ return;
313
+ }
314
+ const pollDelayMs = Math.min(MCP_CONNECTION_POLL_INTERVAL_MS, deadline - Date.now());
315
+ if (pollDelayMs <= 0) {
316
+ throw new LifecycleError("opencode_mcp_connection_timeout", "Timed out waiting for configured OpenCode MCP servers to connect", { metadata: { servers } });
317
+ }
318
+ await new Promise((resolve) => setTimeout(resolve, pollDelayMs));
319
+ }
320
+ }
321
+ function isRecord(value) {
322
+ return typeof value === "object" && value !== null && !Array.isArray(value);
323
+ }
324
+ function usage(message) {
325
+ const tokens = isRecord(message.tokens) ? message.tokens : undefined;
326
+ const input = tokens?.input;
327
+ const output = tokens?.output;
328
+ const cost = message.cost;
329
+ if (typeof input !== "number" && typeof output !== "number" && typeof cost !== "number") {
330
+ return undefined;
331
+ }
332
+ const result = {};
333
+ if (typeof input === "number") {
334
+ result.input_tokens = input;
335
+ }
336
+ if (typeof output === "number") {
337
+ result.output_tokens = output;
338
+ }
339
+ if (typeof input === "number" && typeof output === "number") {
340
+ result.total_tokens = input + output;
341
+ }
342
+ if (typeof cost === "number") {
343
+ result.cost_usd = cost;
344
+ }
345
+ return result;
346
+ }
347
+ function totalUsage(messages) {
348
+ let inputTokens = 0;
349
+ let outputTokens = 0;
350
+ let costUsd = 0;
351
+ let hasInputTokens = false;
352
+ let hasOutputTokens = false;
353
+ let hasCostUsd = false;
354
+ for (const message of messages) {
355
+ const current = usage(message);
356
+ if (current?.input_tokens !== undefined && current.input_tokens !== null) {
357
+ inputTokens += current.input_tokens;
358
+ hasInputTokens = true;
359
+ }
360
+ if (current?.output_tokens !== undefined && current.output_tokens !== null) {
361
+ outputTokens += current.output_tokens;
362
+ hasOutputTokens = true;
363
+ }
364
+ if (current?.cost_usd !== undefined && current.cost_usd !== null) {
365
+ costUsd += current.cost_usd;
366
+ hasCostUsd = true;
367
+ }
368
+ }
369
+ if (!hasInputTokens && !hasOutputTokens && !hasCostUsd) {
370
+ return undefined;
371
+ }
372
+ return {
373
+ ...(hasInputTokens ? { input_tokens: inputTokens } : {}),
374
+ ...(hasOutputTokens ? { output_tokens: outputTokens } : {}),
375
+ ...(hasInputTokens && hasOutputTokens ? { total_tokens: inputTokens + outputTokens } : {}),
376
+ ...(hasCostUsd ? { cost_usd: costUsd } : {}),
377
+ };
378
+ }
379
+ function patch(diffs) {
380
+ if (!Array.isArray(diffs)) {
381
+ return undefined;
382
+ }
383
+ const patches = diffs
384
+ .filter((diff) => isRecord(diff))
385
+ .map((diff) => diff.patch)
386
+ .filter((value) => typeof value === "string" && value.length > 0);
387
+ return patches.length === 0 ? undefined : patches.join("\n");
388
+ }
389
+ function messageIds(messages) {
390
+ return new Set(messages
391
+ .filter((message) => isRecord(message))
392
+ .map((message) => message.id)
393
+ .filter((id) => typeof id === "string"));
394
+ }
395
+ /** Extract the terminal assistant outcome after OpenCode reports a session idle. */
396
+ export function extractOpenCodePromptOutcome(messages, existingMessageIds) {
397
+ const assistantMessages = [];
398
+ for (const message of messages) {
399
+ if (!isRecord(message) || message.type !== "assistant") {
400
+ continue;
401
+ }
402
+ if (existingMessageIds !== undefined &&
403
+ (typeof message.id !== "string" || existingMessageIds.has(message.id))) {
404
+ continue;
405
+ }
406
+ assistantMessages.push(message);
407
+ }
408
+ const terminal = assistantMessages.at(-1);
409
+ if (terminal === undefined) {
410
+ return {};
411
+ }
412
+ const invocationUsage = totalUsage(assistantMessages);
413
+ if (terminal.finish === "error" || terminal.error !== undefined) {
414
+ return {
415
+ errorMessage: "OpenCode model invocation failed",
416
+ ...(invocationUsage === undefined ? {} : { usage: invocationUsage }),
417
+ };
418
+ }
419
+ if (!Array.isArray(terminal.content)) {
420
+ return {};
421
+ }
422
+ const text = terminal.content
423
+ .filter((part) => isRecord(part) && part.type === "text")
424
+ .map((part) => part.text)
425
+ .filter((part) => typeof part === "string")
426
+ .join("");
427
+ return {
428
+ ...(text.length === 0 ? {} : { text }),
429
+ ...(invocationUsage === undefined ? {} : { usage: invocationUsage }),
430
+ };
431
+ }
432
+ export async function loadOpenCodeSdk(resolveModule = (specifier) => import.meta.resolve(specifier), loadModule = (specifier) => import(specifier)) {
433
+ let coreConfig;
434
+ let sdk;
435
+ try {
436
+ coreConfig = resolveModule("@opencode/core/config");
437
+ sdk = resolveModule("@opencode/sdk");
438
+ }
439
+ catch {
440
+ throw new LifecycleError("opencode_harness_unavailable", "The OpenCode v2 harness is not installed. Install compatible packages with: npm install @opencode/core@2.0.3 @opencode/sdk@2.0.3");
441
+ }
442
+ try {
443
+ const [, loadedSdk] = await Promise.all([loadModule(coreConfig), loadModule(sdk)]);
444
+ return loadedSdk;
445
+ }
446
+ catch {
447
+ throw new LifecycleError("opencode_harness_load_failed", "The installed OpenCode v2 SDK could not be loaded");
448
+ }
449
+ }
450
+ async function loadEmbeddedOpenCodeCreate() {
451
+ // @opencode/sdk@2.0.3 exposes its two-argument Promise SDK entry point as a
452
+ // packaged file but does not export it from the package root. Resolve the
453
+ // package root first so this remains valid when npm hoists dependencies. The
454
+ // adapter exact-pins its Core and SDK peers while this private-file workaround
455
+ // is required.
456
+ const sdkRoot = import.meta.resolve("@opencode/sdk");
457
+ const { create } = await import(new URL("./promise.js", sdkRoot).href);
458
+ return create;
459
+ }
460
+ const INHERITED_ENVIRONMENT_NAMES = new Set([
461
+ "APPDATA",
462
+ "BUN_INSTALL",
463
+ "COMSPEC",
464
+ "ComSpec",
465
+ "DBUS_SESSION_BUS_ADDRESS",
466
+ "HOME",
467
+ "HTTP_PROXY",
468
+ "HTTPS_PROXY",
469
+ "LANG",
470
+ "LC_ALL",
471
+ "LC_CTYPE",
472
+ "LOCALAPPDATA",
473
+ "NO_PROXY",
474
+ "PATH",
475
+ "PATHEXT",
476
+ "Path",
477
+ "PathExt",
478
+ "SHELL",
479
+ "SSL_CERT_DIR",
480
+ "SSL_CERT_FILE",
481
+ "SYSTEMROOT",
482
+ "SystemRoot",
483
+ "TEMP",
484
+ "TERM",
485
+ "TERM_PROGRAM",
486
+ "TMP",
487
+ "TMPDIR",
488
+ "USER",
489
+ "USERPROFILE",
490
+ "XDG_CACHE_HOME",
491
+ "XDG_CONFIG_HOME",
492
+ "XDG_DATA_HOME",
493
+ "XDG_RUNTIME_DIR",
494
+ "http_proxy",
495
+ "https_proxy",
496
+ "no_proxy",
497
+ ]);
498
+ function replaceEnvironment(values) {
499
+ for (const name of Object.keys(process.env)) {
500
+ delete process.env[name];
501
+ }
502
+ for (const [name, value] of Object.entries(values)) {
503
+ process.env[name] = value;
504
+ }
505
+ }
506
+ function leaseEnvironment(input, credentialName) {
507
+ const original = { ...process.env };
508
+ const configured = input.runtimeContext.environment.env ?? {};
509
+ const configuredCredential = Object.hasOwn(configured, credentialName) ? configured[credentialName] : undefined;
510
+ const inheritedCredential = Object.hasOwn(original, credentialName) ? original[credentialName] : undefined;
511
+ const credential = configuredCredential ?? inheritedCredential;
512
+ const values = Object.create(null);
513
+ for (const name of INHERITED_ENVIRONMENT_NAMES) {
514
+ const value = original[name];
515
+ if (value !== undefined) {
516
+ values[name] = value;
517
+ }
518
+ }
519
+ for (const [name, value] of Object.entries(configured)) {
520
+ values[name] = value;
521
+ }
522
+ if (credential === undefined || credential.length === 0) {
523
+ throw new LifecycleError("opencode_credential_missing", "The configured OpenCode credential is not available");
524
+ }
525
+ values[credentialName] = credential;
526
+ replaceEnvironment(values);
527
+ return { release: () => replaceEnvironment(original) };
528
+ }
529
+ class OpenCodeSdkSessionHandle {
530
+ id;
531
+ client;
532
+ environment;
533
+ endpointProxy;
534
+ stopped = false;
535
+ constructor(id, client, environment, endpointProxy) {
536
+ this.id = id;
537
+ this.client = client;
538
+ this.environment = environment;
539
+ this.endpointProxy = endpointProxy;
540
+ }
541
+ async prompt(text) {
542
+ let promptMayHaveBeenSubmitted = false;
543
+ try {
544
+ const historyBeforePrompt = await this.client.sessions.context({ sessionID: this.id });
545
+ const existingMessageIds = messageIds(historyBeforePrompt);
546
+ promptMayHaveBeenSubmitted = true;
547
+ await this.client.sessions.prompt({ sessionID: this.id, text });
548
+ await this.client.sessions.wait({ sessionID: this.id });
549
+ const historyAfterPrompt = await this.client.sessions.context({ sessionID: this.id });
550
+ const outcome = extractOpenCodePromptOutcome(historyAfterPrompt, existingMessageIds);
551
+ try {
552
+ const sessionPatch = patch(await this.client.sessions.diff({ sessionID: this.id }));
553
+ return { ...outcome, ...(sessionPatch === undefined ? {} : { patch: sessionPatch }) };
554
+ }
555
+ catch {
556
+ return outcome;
557
+ }
558
+ }
559
+ catch {
560
+ throw new LifecycleError("opencode_session_failed", "OpenCode session communication failed", {
561
+ retryable: !promptMayHaveBeenSubmitted,
562
+ });
563
+ }
564
+ }
565
+ async stop() {
566
+ if (this.stopped) {
567
+ return;
568
+ }
569
+ this.stopped = true;
570
+ try {
571
+ await this.client.sessions.remove({ sessionID: this.id });
572
+ }
573
+ finally {
574
+ try {
575
+ await this.client.close();
576
+ }
577
+ finally {
578
+ try {
579
+ await this.endpointProxy?.close();
580
+ }
581
+ finally {
582
+ this.environment.release();
583
+ }
584
+ }
585
+ }
586
+ }
587
+ }
588
+ export class OpenCodeSdkSessionFactory {
589
+ sdkLoader;
590
+ embedOptionsLoader;
591
+ endpointProxyFactory;
592
+ constructor(sdkLoader = loadOpenCodeSdk, embedOptionsLoader = sdkLoader === loadOpenCodeSdk ? loadIsolatedEmbedOptions : async () => ({}), endpointProxyFactory = ModelEndpointProxy.create) {
593
+ this.sdkLoader = sdkLoader;
594
+ this.embedOptionsLoader = embedOptionsLoader;
595
+ this.endpointProxyFactory = endpointProxyFactory;
596
+ }
597
+ async create(input) {
598
+ const model = selectModel(input.config);
599
+ const systemInstruction = selectSystemInstruction(input.config);
600
+ const skills = await resolveSkills(input.baseDir, input.config.skills?.paths ?? []);
601
+ const configuredEnvironment = input.runtimeContext.environment.env ?? {};
602
+ const mcpServers = selectMcpServers(input.config, configuredEnvironment, process.env);
603
+ const workspace = input.runtimeContext.environment.workspace ?? input.baseDir;
604
+ const environment = leaseEnvironment(input, model.apiKeyEnv);
605
+ let client;
606
+ let endpointProxy;
607
+ let sessionId;
608
+ try {
609
+ const sdk = await this.sdkLoader();
610
+ if (model.baseUrl !== undefined) {
611
+ endpointProxy = await this.endpointProxyFactory(model.baseUrl);
612
+ }
613
+ const configContent = hostConfigContent(model, endpointProxy?.url, systemInstruction, skills.map((skill) => skill.directory), mcpServers);
614
+ const embedOptions = await this.embedOptionsLoader(configContent);
615
+ // The OpenCode convenience namespace silently ignores the embed argument.
616
+ // Use the v2.0.3 Promise SDK entry point for production and retain the
617
+ // public convenience API only for injected unit-test doubles.
618
+ const createEmbeddedClient = this.sdkLoader === loadOpenCodeSdk
619
+ ? await loadEmbeddedOpenCodeCreate()
620
+ : sdk.OpenCode.create;
621
+ client = await createEmbeddedClient({
622
+ config: { directory: workspace, project: false, content: configContent },
623
+ fs: { filewatcher: false },
624
+ models: { fetch: false },
625
+ }, embedOptions);
626
+ await verifyLoadedSkills(client, workspace, skills);
627
+ const session = await client.sessions.create({
628
+ location: { directory: workspace },
629
+ model: { providerID: model.provider, id: model.model },
630
+ permissions: NONINTERACTIVE_SESSION_PERMISSIONS,
631
+ });
632
+ sessionId = session.id;
633
+ await waitForMcpConnections(client, workspace, Object.keys(mcpServers));
634
+ return new OpenCodeSdkSessionHandle(session.id, client, environment, endpointProxy);
635
+ }
636
+ catch (error) {
637
+ if (client !== undefined) {
638
+ if (sessionId !== undefined) {
639
+ try {
640
+ await client.sessions.remove({ sessionID: sessionId });
641
+ }
642
+ catch {
643
+ // Preserve the startup failure while still closing the embedded client.
644
+ }
645
+ }
646
+ try {
647
+ await client.close();
648
+ }
649
+ catch {
650
+ // Preserve the startup failure while releasing local adapter resources.
651
+ }
652
+ }
653
+ try {
654
+ await endpointProxy?.close();
655
+ }
656
+ catch {
657
+ // Preserve the startup failure while releasing local adapter resources.
658
+ }
659
+ finally {
660
+ try {
661
+ environment.release();
662
+ }
663
+ catch {
664
+ // Preserve the startup failure when restoring the environment fails.
665
+ }
666
+ }
667
+ if (error instanceof LifecycleError) {
668
+ throw error;
669
+ }
670
+ throw new LifecycleError("opencode_start_failed", "OpenCode could not start an embedded session");
671
+ }
672
+ }
673
+ }