Skip to content

Commit 60bcadd

Browse files
committed
fix(pty): graceful degradation when bun-pty native library unavailable
Auto-resolve BUN_PTY_LIB by probing .opencode/node_modules/ and other paths that bun-pty's resolveLibPath() misses. Load bun-pty dynamically so the plugin still works (without PTY tools) when the native library can't be found. Fixes #20 See: anomalyco/opencode#10556
1 parent ed9f56c commit 60bcadd

11 files changed

Lines changed: 213 additions & 24 deletions

File tree

‎src/index.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import { milestone_artifact_search } from "./tools/milestone-artifact-search";
2828
import { createMindmodelLookupTool } from "./tools/mindmodel-lookup";
2929
import { createOcttoTools, createSessionStore } from "./tools/octto";
3030
// PTY System
31-
import { createPtyTools, PTYManager } from "./tools/pty";
31+
import { createPtyTools, loadBunPty, PTYManager } from "./tools/pty";
3232
import { createSpawnAgentTool } from "./tools/spawn-agent";
3333
import { log } from "./utils/logger";
3434

@@ -174,9 +174,15 @@ const OpenCodeConfigPlugin: Plugin = async (ctx) => {
174174
}
175175
});
176176

177-
// PTY System
177+
// PTY System - load bun-pty with graceful degradation
178+
// Sets BUN_PTY_LIB env var to fix path resolution in OpenCode plugin environments
179+
// See: https://github.com/vtemian/micode/issues/20
178180
const ptyManager = new PTYManager();
179-
const ptyTools = createPtyTools(ptyManager);
181+
const bunPty = await loadBunPty();
182+
if (bunPty) {
183+
ptyManager.init(bunPty.spawn);
184+
}
185+
const ptyTools = ptyManager.available ? createPtyTools(ptyManager) : {};
180186

181187
// Spawn agent tool (for subagents to spawn other subagents)
182188
const spawn_agent = createSpawnAgentTool(ctx);

‎src/tools/pty/index.ts‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,29 @@
11
// src/tools/pty/index.ts
2-
export { PTYManager } from "./manager";
2+
33
export { RingBuffer } from "./buffer";
4+
export { PTYManager } from "./manager";
5+
export { getBunPtyLoadError, isBunPtyAvailable, loadBunPty } from "./pty-loader";
6+
export { createPtyKillTool } from "./tools/kill";
7+
export { createPtyListTool } from "./tools/list";
8+
export { createPtyReadTool } from "./tools/read";
49
export { createPtySpawnTool } from "./tools/spawn";
510
export { createPtyWriteTool } from "./tools/write";
6-
export { createPtyReadTool } from "./tools/read";
7-
export { createPtyListTool } from "./tools/list";
8-
export { createPtyKillTool } from "./tools/kill";
911
export type {
1012
PTYSession,
1113
PTYSessionInfo,
1214
PTYStatus,
13-
SpawnOptions,
1415
ReadResult,
1516
SearchMatch,
1617
SearchResult,
18+
SpawnOptions,
1719
} from "./types";
1820

1921
import type { PTYManager } from "./manager";
22+
import { createPtyKillTool } from "./tools/kill";
23+
import { createPtyListTool } from "./tools/list";
24+
import { createPtyReadTool } from "./tools/read";
2025
import { createPtySpawnTool } from "./tools/spawn";
2126
import { createPtyWriteTool } from "./tools/write";
22-
import { createPtyReadTool } from "./tools/read";
23-
import { createPtyListTool } from "./tools/list";
24-
import { createPtyKillTool } from "./tools/kill";
2527

2628
export function createPtyTools(manager: PTYManager) {
2729
return {

‎src/tools/pty/manager.ts‎

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
// src/tools/pty/manager.ts
2-
import { spawn, type IPty } from "bun-pty";
32
import { RingBuffer } from "./buffer";
4-
import type { PTYSession, PTYSessionInfo, SpawnOptions, ReadResult, SearchResult } from "./types";
3+
import type { PTYSession, PTYSessionInfo, ReadResult, SearchResult, SpawnOptions } from "./types";
4+
5+
// bun-pty types used locally - the actual module is injected via init()
6+
type IPty = import("bun-pty").IPty;
7+
type SpawnFn = typeof import("bun-pty").spawn;
58

69
function generateId(): string {
710
const hex = Array.from(crypto.getRandomValues(new Uint8Array(4)))
@@ -12,8 +15,35 @@ function generateId(): string {
1215

1316
export class PTYManager {
1417
private sessions: Map<string, PTYSession> = new Map();
18+
private spawnFn: SpawnFn | null = null;
19+
private _available = false;
20+
21+
/**
22+
* Initialize the manager with the bun-pty spawn function.
23+
* Must be called before spawn(). If not called or called with null,
24+
* PTY operations will return errors indicating PTY is unavailable.
25+
*/
26+
init(spawnFn: SpawnFn): void {
27+
this.spawnFn = spawnFn;
28+
this._available = true;
29+
}
30+
31+
/**
32+
* Whether PTY functionality is available (bun-pty loaded successfully).
33+
*/
34+
get available(): boolean {
35+
return this._available;
36+
}
1537

1638
spawn(opts: SpawnOptions): PTYSessionInfo {
39+
if (!this.spawnFn) {
40+
throw new Error(
41+
"PTY unavailable: bun-pty native library could not be loaded. " +
42+
"Set BUN_PTY_LIB environment variable to the path of the native library " +
43+
"(e.g., .opencode/node_modules/bun-pty/rust-pty/target/release/librust_pty.dylib)",
44+
);
45+
}
46+
1747
const id = generateId();
1848
const args = opts.args ?? [];
1949
const workdir = opts.workdir ?? process.cwd();
@@ -22,7 +52,7 @@ export class PTYManager {
2252

2353
let ptyProcess: IPty;
2454
try {
25-
ptyProcess = spawn(opts.command, args, {
55+
ptyProcess = this.spawnFn(opts.command, args, {
2656
name: "xterm-256color",
2757
cols: 120,
2858
rows: 40,

‎src/tools/pty/pty-loader.ts‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
// src/tools/pty/pty-loader.ts
2+
// Resolves bun-pty native library path and loads bun-pty with graceful degradation.
3+
//
4+
// bun-pty's resolveLibPath() checks BUN_PTY_LIB env var first, then hardcoded paths
5+
// relative to import.meta.url. When micode is installed as an OpenCode plugin,
6+
// the library ends up in .opencode/node_modules/bun-pty/... which isn't in the
7+
// hardcoded search paths. We fix this by probing likely locations and setting
8+
// BUN_PTY_LIB before the dynamic import.
9+
//
10+
// See: https://github.com/vtemian/micode/issues/20
11+
// See: https://github.com/anomalyco/opencode/issues/10556
12+
13+
import { existsSync } from "node:fs";
14+
import { dirname, join } from "node:path";
15+
16+
import { log } from "../../utils/logger";
17+
18+
type BunPtyModule = typeof import("bun-pty");
19+
20+
let cachedModule: BunPtyModule | null = null;
21+
let loadAttempted = false;
22+
let loadError: string | null = null;
23+
24+
/**
25+
* Probe additional paths where the bun-pty native library might live,
26+
* beyond what bun-pty checks itself. Sets BUN_PTY_LIB if found.
27+
*/
28+
function probeBunPtyLib(): void {
29+
// If already set by user, respect it
30+
if (process.env.BUN_PTY_LIB) return;
31+
32+
const platform = process.platform;
33+
const arch = process.arch;
34+
35+
const filenames =
36+
platform === "darwin"
37+
? arch === "arm64"
38+
? ["librust_pty_arm64.dylib", "librust_pty.dylib"]
39+
: ["librust_pty.dylib"]
40+
: platform === "win32"
41+
? ["rust_pty.dll"]
42+
: arch === "arm64"
43+
? ["librust_pty_arm64.so", "librust_pty.so"]
44+
: ["librust_pty.so"];
45+
46+
const cwd = process.cwd();
47+
48+
// Paths that bun-pty does NOT check but where the lib may exist
49+
// when installed as an OpenCode plugin dependency
50+
const additionalBasePaths = [
51+
// .opencode/node_modules/bun-pty/... (plugin installed via .opencode/package.json)
52+
join(cwd, ".opencode", "node_modules", "bun-pty", "rust-pty", "target", "release"),
53+
// .micode/node_modules/bun-pty/... (if micode has its own node_modules)
54+
join(cwd, ".micode", "node_modules", "bun-pty", "rust-pty", "target", "release"),
55+
];
56+
57+
// Also try resolving from require.resolve if available
58+
try {
59+
const bunPtyMain = require.resolve("bun-pty");
60+
if (bunPtyMain) {
61+
// require.resolve gives us something like .../node_modules/bun-pty/src/index.ts
62+
// Go up to the bun-pty package root
63+
const pkgDir = dirname(dirname(bunPtyMain));
64+
additionalBasePaths.unshift(join(pkgDir, "rust-pty", "target", "release"));
65+
}
66+
} catch {
67+
// require.resolve may fail in some environments
68+
}
69+
70+
for (const basePath of additionalBasePaths) {
71+
for (const filename of filenames) {
72+
const candidate = join(basePath, filename);
73+
if (existsSync(candidate)) {
74+
process.env.BUN_PTY_LIB = candidate;
75+
log.info("pty.loader", `Auto-resolved BUN_PTY_LIB=${candidate}`);
76+
return;
77+
}
78+
}
79+
}
80+
}
81+
82+
/**
83+
* Dynamically load bun-pty with graceful degradation.
84+
* Sets BUN_PTY_LIB env var before import to fix path resolution
85+
* in OpenCode plugin environments.
86+
*
87+
* Returns null if bun-pty cannot be loaded (native library missing, etc.)
88+
*/
89+
export async function loadBunPty(): Promise<BunPtyModule | null> {
90+
if (loadAttempted) return cachedModule;
91+
loadAttempted = true;
92+
93+
// Probe and set BUN_PTY_LIB before importing
94+
probeBunPtyLib();
95+
96+
try {
97+
cachedModule = await import("bun-pty");
98+
log.info("pty.loader", "bun-pty loaded successfully");
99+
return cachedModule;
100+
} catch (error) {
101+
loadError = error instanceof Error ? error.message : String(error);
102+
// Extract just the first line for a cleaner warning
103+
const firstLine = loadError.split("\n")[0];
104+
log.warn("pty.loader", `bun-pty unavailable: ${firstLine}`);
105+
log.warn("pty.loader", "PTY tools will be disabled. Set BUN_PTY_LIB env var to the native library path to fix.");
106+
cachedModule = null;
107+
return null;
108+
}
109+
}
110+
111+
/**
112+
* Check if bun-pty is available (must call loadBunPty first).
113+
*/
114+
export function isBunPtyAvailable(): boolean {
115+
return cachedModule !== null;
116+
}
117+
118+
/**
119+
* Get the load error message, if any.
120+
*/
121+
export function getBunPtyLoadError(): string | null {
122+
return loadError;
123+
}

‎tests/tools/pty/integration.test.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
// tests/tools/pty/integration.test.ts
2-
import { describe, it, expect, beforeEach, afterEach } from "bun:test";
2+
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
3+
4+
import { spawn } from "bun-pty";
5+
36
import { PTYManager } from "../../../src/tools/pty/manager";
7+
import { createPtyKillTool } from "../../../src/tools/pty/tools/kill";
8+
import { createPtyReadTool } from "../../../src/tools/pty/tools/read";
49
import { createPtySpawnTool } from "../../../src/tools/pty/tools/spawn";
510
import { createPtyWriteTool } from "../../../src/tools/pty/tools/write";
6-
import { createPtyReadTool } from "../../../src/tools/pty/tools/read";
7-
import { createPtyKillTool } from "../../../src/tools/pty/tools/kill";
811

912
describe("PTY Integration", () => {
1013
let manager: PTYManager;
@@ -20,6 +23,7 @@ describe("PTY Integration", () => {
2023

2124
beforeEach(() => {
2225
manager = new PTYManager();
26+
manager.init(spawn);
2327
pty_spawn = createPtySpawnTool(manager);
2428
pty_write = createPtyWriteTool(manager);
2529
pty_read = createPtyReadTool(manager);

‎tests/tools/pty/kill.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
// tests/tools/pty/kill.test.ts
2-
import { describe, it, expect, beforeEach, afterEach } from "bun:test";
2+
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
3+
4+
import { spawn } from "bun-pty";
5+
36
import { PTYManager } from "../../../src/tools/pty/manager";
47
import { createPtyKillTool } from "../../../src/tools/pty/tools/kill";
58
import { createPtySpawnTool } from "../../../src/tools/pty/tools/spawn";
@@ -11,6 +14,7 @@ describe("pty_kill tool", () => {
1114

1215
beforeEach(() => {
1316
manager = new PTYManager();
17+
manager.init(spawn);
1418
pty_kill = createPtyKillTool(manager);
1519
pty_spawn = createPtySpawnTool(manager);
1620
});

‎tests/tools/pty/list.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
// tests/tools/pty/list.test.ts
2-
import { describe, it, expect, beforeEach, afterEach } from "bun:test";
2+
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
3+
4+
import { spawn } from "bun-pty";
5+
36
import { PTYManager } from "../../../src/tools/pty/manager";
47
import { createPtyListTool } from "../../../src/tools/pty/tools/list";
58
import { createPtySpawnTool } from "../../../src/tools/pty/tools/spawn";
@@ -11,6 +14,7 @@ describe("pty_list tool", () => {
1114

1215
beforeEach(() => {
1316
manager = new PTYManager();
17+
manager.init(spawn);
1418
pty_list = createPtyListTool(manager);
1519
pty_spawn = createPtySpawnTool(manager);
1620
});

‎tests/tools/pty/manager.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
// tests/tools/pty/manager.test.ts
2-
import { describe, it, expect, beforeEach, afterEach } from "bun:test";
2+
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
3+
4+
import { spawn } from "bun-pty";
5+
36
import { PTYManager } from "../../../src/tools/pty/manager";
47

58
describe("PTYManager", () => {
69
let manager: PTYManager;
710

811
beforeEach(() => {
912
manager = new PTYManager();
13+
manager.init(spawn);
1014
});
1115

1216
afterEach(() => {

‎tests/tools/pty/read.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
// tests/tools/pty/read.test.ts
2-
import { describe, it, expect, beforeEach, afterEach } from "bun:test";
2+
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
3+
4+
import { spawn } from "bun-pty";
5+
36
import { PTYManager } from "../../../src/tools/pty/manager";
47
import { createPtyReadTool } from "../../../src/tools/pty/tools/read";
58
import { createPtySpawnTool } from "../../../src/tools/pty/tools/spawn";
@@ -11,6 +14,7 @@ describe("pty_read tool", () => {
1114

1215
beforeEach(() => {
1316
manager = new PTYManager();
17+
manager.init(spawn);
1418
pty_read = createPtyReadTool(manager);
1519
pty_spawn = createPtySpawnTool(manager);
1620
});

‎tests/tools/pty/spawn.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
// tests/tools/pty/spawn.test.ts
2-
import { describe, it, expect, beforeEach, afterEach } from "bun:test";
2+
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
3+
4+
import { spawn } from "bun-pty";
5+
36
import { PTYManager } from "../../../src/tools/pty/manager";
47
import { createPtySpawnTool } from "../../../src/tools/pty/tools/spawn";
58

@@ -9,6 +12,7 @@ describe("pty_spawn tool", () => {
912

1013
beforeEach(() => {
1114
manager = new PTYManager();
15+
manager.init(spawn);
1216
pty_spawn = createPtySpawnTool(manager);
1317
});
1418

0 commit comments

Comments
 (0)