@neuralnomads/codenomad 0.18.0 → 0.19.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.
Files changed (135) hide show
  1. package/README.md +12 -0
  2. package/THIRD_PARTY_NOTICES.md +26 -0
  3. package/dist/auth/manager.js +1 -1
  4. package/dist/background-processes/manager.js +15 -30
  5. package/dist/background-processes/manager.test.js +123 -0
  6. package/dist/config/schema.js +2 -1
  7. package/dist/config/schema.test.js +13 -0
  8. package/dist/events/bus.js +17 -0
  9. package/dist/events/bus.test.js +37 -0
  10. package/dist/filesystem/__tests__/search-cache.test.js +20 -8
  11. package/dist/filesystem/__tests__/search.test.js +53 -0
  12. package/dist/filesystem/search-cache.js +6 -10
  13. package/dist/filesystem/search.js +22 -9
  14. package/dist/index.js +77 -58
  15. package/dist/index.test.js +62 -0
  16. package/dist/opencode-plugin/codenomad-opencode-plugin.tgz +0 -0
  17. package/dist/opencode-update/service.js +150 -0
  18. package/dist/opencode-update/service.test.js +107 -0
  19. package/dist/permissions/auto-accept-manager.js +380 -0
  20. package/dist/permissions/auto-accept-manager.test.js +736 -0
  21. package/dist/permissions/auto-accept-store.js +118 -0
  22. package/dist/permissions/auto-accept-store.test.js +157 -0
  23. package/dist/permissions/opencode-replier.js +31 -0
  24. package/dist/permissions/opencode-yolo-metadata.js +81 -0
  25. package/dist/permissions/opencode-yolo-metadata.test.js +54 -0
  26. package/dist/server/__tests__/listener-retry.test.js +15 -0
  27. package/dist/server/__tests__/remote-proxy.test.js +151 -47
  28. package/dist/server/http-server.js +22 -9
  29. package/dist/server/remote-proxy.js +91 -34
  30. package/dist/server/routes/auth-pages/login.html +3 -3
  31. package/dist/server/routes/auth.js +1 -1
  32. package/dist/server/routes/auth.test.js +21 -0
  33. package/dist/server/routes/opencode-update.js +37 -0
  34. package/dist/server/routes/opencode-update.test.js +34 -0
  35. package/dist/server/routes/remote-servers.js +1 -1
  36. package/dist/server/routes/settings.js +48 -2
  37. package/dist/server/routes/settings.test.js +58 -0
  38. package/dist/server/routes/usage.js +18 -0
  39. package/dist/server/routes/usage.test.js +26 -0
  40. package/dist/server/routes/workspaces.js +34 -2
  41. package/dist/server/routes/workspaces.test.js +113 -0
  42. package/dist/server/routes/worktrees.js +19 -0
  43. package/dist/server/routes/yolo.js +13 -0
  44. package/dist/server/tls.js +2 -2
  45. package/dist/settings/binaries.js +4 -1
  46. package/dist/settings/binaries.test.js +19 -0
  47. package/dist/settings/public-config.js +14 -0
  48. package/dist/settings/public-config.test.js +56 -0
  49. package/dist/settings/service.js +17 -5
  50. package/dist/settings/service.test.js +51 -0
  51. package/dist/settings/yaml-doc-store.js +55 -4
  52. package/dist/settings/yaml-doc-store.test.js +78 -0
  53. package/dist/shutdown.js +83 -0
  54. package/dist/shutdown.test.js +148 -0
  55. package/dist/sidecars/manager.js +26 -3
  56. package/dist/sidecars/manager.test.js +42 -0
  57. package/dist/speech/service.js +121 -10
  58. package/dist/speech/service.test.js +247 -0
  59. package/dist/ui/remote-ui.js +2 -2
  60. package/dist/usage/providers/api-key.js +171 -0
  61. package/dist/usage/providers/google.js +171 -0
  62. package/dist/usage/providers/minimax.js +109 -0
  63. package/dist/usage/providers/oauth.js +76 -0
  64. package/dist/usage/providers/special.js +148 -0
  65. package/dist/usage/service.js +83 -0
  66. package/dist/usage/service.test.js +61 -0
  67. package/dist/usage/shared.js +130 -0
  68. package/dist/usage/shared.test.js +33 -0
  69. package/dist/usage/types.js +1 -0
  70. package/dist/workspaces/__tests__/spawn.test.js +64 -7
  71. package/dist/workspaces/__tests__/workspace-identity.test.js +163 -0
  72. package/dist/workspaces/binary-path.test.js +10 -0
  73. package/dist/workspaces/instance-client.js +42 -0
  74. package/dist/workspaces/instance-client.test.js +149 -0
  75. package/dist/workspaces/instance-events.js +2 -2
  76. package/dist/workspaces/launch-cleanup.test.js +29 -0
  77. package/dist/workspaces/loopback.js +8 -0
  78. package/dist/workspaces/manager.js +473 -128
  79. package/dist/workspaces/manager.test.js +335 -0
  80. package/dist/workspaces/process-identity.darwin.test.js +88 -0
  81. package/dist/workspaces/process-identity.js +449 -0
  82. package/dist/workspaces/process-identity.test.js +140 -0
  83. package/dist/workspaces/runtime.js +471 -138
  84. package/dist/workspaces/runtime.test.js +286 -0
  85. package/dist/workspaces/spawn.js +86 -15
  86. package/dist/workspaces/workspace-identity.js +27 -0
  87. package/package.json +2 -1
  88. package/public/assets/FilesTab-Cbs7b7y9.js +2 -0
  89. package/public/assets/{GitChangesTab-DyRStL3G.js → GitChangesTab-D3H4cqJJ.js} +2 -2
  90. package/public/assets/{SplitFilePanel-C4FztlTR.js → SplitFilePanel-C_Bcle0r.js} +1 -1
  91. package/public/assets/StatusTab-D1-tfkgN.js +1 -0
  92. package/public/assets/{align-justify-GNs_d9nT.js → align-justify-B5HUL_LR.js} +1 -1
  93. package/public/assets/{bundle-full-B0vc8NGv.js → bundle-full-CEFzES5w.js} +1 -1
  94. package/public/assets/{diff-viewer-BmSzmlPC.js → diff-viewer-BBC2_yI1.js} +1 -1
  95. package/public/assets/{git-diff-vendor-CSgooKT_.js → git-diff-vendor-CYS3ApzA.js} +1 -1
  96. package/public/assets/{index-ChDVvMF4.js → index-B81f0aWL.js} +1 -1
  97. package/public/assets/index-BHlYVddm.js +1 -0
  98. package/public/assets/index-Best16ZB.js +2 -0
  99. package/public/assets/index-Boq37ErX.js +1 -0
  100. package/public/assets/index-By9pgzQk.css +1 -0
  101. package/public/assets/index-C0caoeJg.js +1 -0
  102. package/public/assets/index-Dqg2UVvS.js +1 -0
  103. package/public/assets/index-it6EGJV6.js +1 -0
  104. package/public/assets/{index-Bv867yIC.js → index-lORR8OnW.js} +1 -1
  105. package/public/assets/index-ppe6yWaU.js +1 -0
  106. package/public/assets/index-wEqeBwqT.js +1 -0
  107. package/public/assets/index-yEcajWX_.js +1 -0
  108. package/public/assets/{loading-DRzViX8M.js → loading-CbUWFqQ_.js} +1 -1
  109. package/public/assets/main-DfSREDgt.js +69 -0
  110. package/public/assets/{markdown-BlxzERp2.js → markdown-CEtfpKK-.js} +60 -47
  111. package/public/assets/monaco-viewer-NKl8kwH2.js +26 -0
  112. package/public/assets/terminal-square-q-by1uT7.js +1 -0
  113. package/public/assets/tool-call-CZL2uqIM.js +59 -0
  114. package/public/assets/unified-picker-CvJXD-j8.js +1 -0
  115. package/public/assets/{wrap-text-CMFBVbBi.js → wrap-text-Bo7xr74P.js} +1 -1
  116. package/public/index.html +5 -5
  117. package/public/loading.html +5 -5
  118. package/public/sw.js +1 -1
  119. package/public/ui-version.json +1 -1
  120. package/public/assets/FilesTab-CFF9uJuc.js +0 -2
  121. package/public/assets/StatusTab-CcoPFya8.js +0 -1
  122. package/public/assets/index--bYE3fA1.js +0 -1
  123. package/public/assets/index-B-9c-wPM.css +0 -1
  124. package/public/assets/index-BDJqHo1E.js +0 -1
  125. package/public/assets/index-BEXDNmDA.js +0 -1
  126. package/public/assets/index-BWX6Cyx3.js +0 -2
  127. package/public/assets/index-CUB1cngT.js +0 -1
  128. package/public/assets/index-CyGPk9Qx.js +0 -1
  129. package/public/assets/index-D9T8sYiH.js +0 -1
  130. package/public/assets/index-DQ8RfkwK.js +0 -1
  131. package/public/assets/index-udaOwtFG.js +0 -1
  132. package/public/assets/main-DUP17Bqi.js +0 -68
  133. package/public/assets/monaco-viewer-BbohfXZk.js +0 -26
  134. package/public/assets/tool-call-B0Ri40qI.js +0 -59
  135. package/public/assets/unified-picker-CGg8mlSo.js +0 -1
@@ -0,0 +1,130 @@
1
+ import fs from "fs";
2
+ import os from "os";
3
+ import path from "path";
4
+ const REQUEST_TIMEOUT_MS = 15_000;
5
+ function authFileCandidates() {
6
+ const home = os.homedir();
7
+ const candidates = [
8
+ process.env.OPENCODE_AUTH_FILE,
9
+ process.env.OPENCODE_DATA_DIR ? path.join(process.env.OPENCODE_DATA_DIR, "auth.json") : undefined,
10
+ process.env.XDG_DATA_HOME ? path.join(process.env.XDG_DATA_HOME, "opencode", "auth.json") : undefined,
11
+ path.join(home, ".local", "share", "opencode", "auth.json"),
12
+ process.env.LOCALAPPDATA ? path.join(process.env.LOCALAPPDATA, "opencode", "Data", "auth.json") : undefined,
13
+ process.env.APPDATA ? path.join(process.env.APPDATA, "opencode", "auth.json") : undefined,
14
+ path.join(home, "Library", "Application Support", "opencode", "auth.json"),
15
+ ];
16
+ return Array.from(new Set(candidates.filter((candidate) => Boolean(candidate))));
17
+ }
18
+ export function readOpenCodeAuth() {
19
+ for (const candidate of authFileCandidates()) {
20
+ try {
21
+ const parsed = JSON.parse(fs.readFileSync(candidate, "utf8"));
22
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
23
+ return parsed;
24
+ }
25
+ catch (error) {
26
+ if (error.code !== "ENOENT")
27
+ continue;
28
+ }
29
+ }
30
+ return {};
31
+ }
32
+ export function getAuthEntry(aliases) {
33
+ const auth = readOpenCodeAuth();
34
+ for (const alias of aliases) {
35
+ const value = auth[alias];
36
+ if (typeof value === "string" && value.trim())
37
+ return { token: value.trim() };
38
+ if (value && typeof value === "object" && !Array.isArray(value))
39
+ return value;
40
+ }
41
+ return null;
42
+ }
43
+ export function getString(value) {
44
+ return typeof value === "string" && value.trim() ? value.trim() : null;
45
+ }
46
+ export function getCredential(aliases, fields) {
47
+ const entry = getAuthEntry(aliases);
48
+ if (!entry)
49
+ return null;
50
+ for (const field of fields) {
51
+ const value = getString(entry[field]);
52
+ if (value)
53
+ return value;
54
+ }
55
+ return null;
56
+ }
57
+ export function asObject(value) {
58
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
59
+ }
60
+ export function toNumber(value) {
61
+ if (typeof value === "number" && Number.isFinite(value))
62
+ return value;
63
+ if (typeof value === "string" && value.trim()) {
64
+ const parsed = Number(value);
65
+ return Number.isFinite(parsed) ? parsed : null;
66
+ }
67
+ return null;
68
+ }
69
+ export function toTimestamp(value) {
70
+ if (typeof value === "number" && Number.isFinite(value))
71
+ return value < 1_000_000_000_000 ? value * 1000 : value;
72
+ if (typeof value === "string" && value.trim()) {
73
+ const parsed = Date.parse(value);
74
+ return Number.isNaN(parsed) ? null : parsed;
75
+ }
76
+ return null;
77
+ }
78
+ export function toUsageWindow(input) {
79
+ const usedPercent = input.usedPercent === null ? null : Math.max(0, Math.min(100, input.usedPercent));
80
+ return {
81
+ usedPercent,
82
+ remainingPercent: usedPercent === null ? null : 100 - usedPercent,
83
+ windowSeconds: input.windowSeconds ?? null,
84
+ resetAt: input.resetAt ?? null,
85
+ ...(input.valueLabel ? { valueLabel: input.valueLabel } : {}),
86
+ };
87
+ }
88
+ export function resolveWindowLabel(windowSeconds) {
89
+ if (!windowSeconds)
90
+ return "usage";
91
+ if (windowSeconds % 86_400 === 0) {
92
+ const days = windowSeconds / 86_400;
93
+ return days === 7 ? "weekly" : `${days}d`;
94
+ }
95
+ if (windowSeconds % 3600 === 0)
96
+ return `${windowSeconds / 3600}h`;
97
+ return `${windowSeconds}s`;
98
+ }
99
+ export function result(providerId, providerName, input) {
100
+ return {
101
+ providerId,
102
+ providerName,
103
+ ok: input.ok,
104
+ configured: input.configured,
105
+ usage: input.usage ?? null,
106
+ fetchedAt: Date.now(),
107
+ ...(input.error ? { error: input.error } : {}),
108
+ };
109
+ }
110
+ export function notConfigured(providerId, providerName) {
111
+ return result(providerId, providerName, { ok: false, configured: false, error: "Not configured" });
112
+ }
113
+ export async function fetchJson(url, init = {}) {
114
+ const response = await fetch(url, { ...init, signal: init.signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
115
+ if (!response.ok)
116
+ throw new Error(`Provider returned HTTP ${response.status}`);
117
+ return response.json();
118
+ }
119
+ export async function safeFetch(providerId, providerName, operation) {
120
+ try {
121
+ return result(providerId, providerName, { ok: true, configured: true, usage: await operation() });
122
+ }
123
+ catch (error) {
124
+ return result(providerId, providerName, {
125
+ ok: false,
126
+ configured: true,
127
+ error: error instanceof Error ? error.message : "Request failed",
128
+ });
129
+ }
130
+ }
@@ -0,0 +1,33 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import test from "node:test";
6
+ import { getCredential, readOpenCodeAuth, toTimestamp, toUsageWindow } from "./shared";
7
+ test("reads the explicit OpenCode auth file without exposing credentials through the API", () => {
8
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-usage-"));
9
+ const authFile = path.join(directory, "auth.json");
10
+ const previous = process.env.OPENCODE_AUTH_FILE;
11
+ fs.writeFileSync(authFile, JSON.stringify({ openai: { type: "oauth", access: "secret-token" } }));
12
+ process.env.OPENCODE_AUTH_FILE = authFile;
13
+ try {
14
+ assert.equal(readOpenCodeAuth().openai.access, "secret-token");
15
+ assert.equal(getCredential(["openai"], ["access"]), "secret-token");
16
+ }
17
+ finally {
18
+ if (previous === undefined)
19
+ delete process.env.OPENCODE_AUTH_FILE;
20
+ else
21
+ process.env.OPENCODE_AUTH_FILE = previous;
22
+ fs.rmSync(directory, { recursive: true, force: true });
23
+ }
24
+ });
25
+ test("normalizes percentages and timestamps", () => {
26
+ assert.deepEqual(toUsageWindow({ usedPercent: 120, resetAt: null }), {
27
+ usedPercent: 100,
28
+ remainingPercent: 0,
29
+ windowSeconds: null,
30
+ resetAt: null,
31
+ });
32
+ assert.equal(toTimestamp(1_700_000_000), 1_700_000_000_000);
33
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -1,6 +1,9 @@
1
1
  import assert from "node:assert/strict";
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
2
5
  import { describe, it } from "node:test";
3
- import { buildWindowsSpawnSpec, buildWslSignalSpec, parseWslUncPath, resolveWslWorkingDirectory } from "../spawn";
6
+ import { buildWindowsSpawnSpec, parseWslUncPath, resolveWslWorkingDirectory } from "../spawn";
4
7
  describe("parseWslUncPath", () => {
5
8
  it("parses WSL UNC paths into distro and linux path", () => {
6
9
  assert.deepEqual(parseWslUncPath(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`), {
@@ -30,6 +33,62 @@ describe("resolveWslWorkingDirectory", () => {
30
33
  });
31
34
  });
32
35
  describe("buildWindowsSpawnSpec", () => {
36
+ it("classifies native executables separately from script and shell wrappers", () => {
37
+ assert.equal(buildWindowsSpawnSpec("opencode.exe", []).processKind, "windows-direct");
38
+ assert.equal(buildWindowsSpawnSpec("opencode.cmd", []).processKind, "windows-wrapper");
39
+ assert.equal(buildWindowsSpawnSpec("powershell.exe", []).processKind, "windows-wrapper");
40
+ });
41
+ it("conservatively classifies bare commands as wrappers", () => {
42
+ assert.equal(buildWindowsSpawnSpec("opencode", []).processKind, "windows-wrapper");
43
+ });
44
+ it("resolves a bare cmd shim from a quoted PATH entry and wraps its absolute path", { skip: process.platform !== "win32" }, () => {
45
+ const root = mkdtempSync(path.join(tmpdir(), "codenomad-spawn-"));
46
+ const cwd = path.join(root, "workspace");
47
+ const bin = path.join(root, "bin with spaces");
48
+ mkdirSync(cwd);
49
+ mkdirSync(bin);
50
+ const shim = path.join(bin, "opencode.cmd");
51
+ writeFileSync(shim, "@echo off\r\n");
52
+ try {
53
+ const spec = buildWindowsSpawnSpec("opencode", ["serve"], {
54
+ cwd,
55
+ env: { Path: `"${bin}"`, PathExt: ".CMD;.EXE", ComSpec: "test-cmd.exe" },
56
+ });
57
+ assert.equal(spec.command, "test-cmd.exe");
58
+ assert.equal(spec.processKind, "windows-wrapper");
59
+ assert.equal(spec.options.windowsVerbatimArguments, true);
60
+ assert.match(spec.args[3] ?? "", new RegExp(escapeRegex(path.win32.resolve(shim)), "i"));
61
+ }
62
+ finally {
63
+ rmSync(root, { recursive: true, force: true });
64
+ }
65
+ });
66
+ it("honors PATHEXT precedence when both native and shim files exist", { skip: process.platform !== "win32" }, () => {
67
+ const root = mkdtempSync(path.join(tmpdir(), "codenomad-spawn-"));
68
+ writeFileSync(path.join(root, "opencode.cmd"), "@echo off\r\n");
69
+ writeFileSync(path.join(root, "opencode.exe"), "");
70
+ try {
71
+ const spec = buildWindowsSpawnSpec("opencode", [], {
72
+ cwd: root,
73
+ env: { PATH: "", PATHEXT: ".EXE;.CMD" },
74
+ });
75
+ assert.equal(spec.command.toLowerCase(), path.win32.resolve(root, "opencode.exe").toLowerCase());
76
+ assert.equal(spec.processKind, "windows-direct");
77
+ }
78
+ finally {
79
+ rmSync(root, { recursive: true, force: true });
80
+ }
81
+ });
82
+ it("leaves an unresolved bare command unchanged without injecting a shell", () => {
83
+ const spec = buildWindowsSpawnSpec("missing-opencode", ["serve"], {
84
+ cwd: String.raw `C:\missing-workspace`,
85
+ env: { PATH: "", PATHEXT: ".CMD;.EXE", ComSpec: "must-not-run.exe" },
86
+ });
87
+ assert.equal(spec.command, "missing-opencode");
88
+ assert.deepEqual(spec.args, ["serve"]);
89
+ assert.equal(spec.processKind, "windows-wrapper");
90
+ assert.equal(spec.options.windowsVerbatimArguments, undefined);
91
+ });
33
92
  it("wraps WSL binaries with wsl.exe and propagates required env vars", () => {
34
93
  const spec = buildWindowsSpawnSpec(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`, ["serve", "--port", "0"], {
35
94
  cwd: String.raw `\\wsl.localhost\Ubuntu\home\dev\workspace`,
@@ -142,7 +201,7 @@ describe("buildWindowsSpawnSpec", () => {
142
201
  "--exec",
143
202
  "sh",
144
203
  "-lc",
145
- `printf '%s%s\\n' '__CODENOMAD_WSL_PID__:' "$$" && cd "$1" && shift && exec "$@"`,
204
+ `codenomad_pgid=$(ps -o pgid= -p "$$" 2>/dev/null | tr -d '[:space:]'); codenomad_start=$(awk '{print $22}' "/proc/$$/stat" 2>/dev/null); codenomad_boot=$(cat /proc/sys/kernel/random/boot_id 2>/dev/null); test -n "$codenomad_pgid" && test -n "$codenomad_start" && test -n "$codenomad_boot" && printf '%s%s:%s:%s:%s\\n' '__CODENOMAD_WSL_PID__:' "$$" "$codenomad_pgid" "$codenomad_start" "$codenomad_boot" && cd "$1" && shift && exec "$@"`,
146
205
  "codenomad-wsl-launch",
147
206
  "/home/dev/workspace",
148
207
  "/home/dev/.opencode/bin/opencode",
@@ -150,9 +209,7 @@ describe("buildWindowsSpawnSpec", () => {
150
209
  ]);
151
210
  assert.equal(spec.wsl?.pidMarker, "__CODENOMAD_WSL_PID__:");
152
211
  });
153
- it("builds the WSL kill command for tracked Linux PIDs", () => {
154
- const spec = buildWslSignalSpec("Ubuntu", 4321, "SIGTERM");
155
- assert.equal(spec.command, "wsl.exe");
156
- assert.deepEqual(spec.args, ["--distribution", "Ubuntu", "--exec", "kill", "-TERM", "4321"]);
157
- });
158
212
  });
213
+ function escapeRegex(value) {
214
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
215
+ }
@@ -0,0 +1,163 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, mkdir, rm, symlink } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { afterEach, describe, it } from "node:test";
6
+ import pino from "pino";
7
+ import { EventBus } from "../../events/bus";
8
+ import { WorkspaceManager } from "../manager";
9
+ import { normalizeWorkspaceIdentityPath, resolveWorkspaceIdentity } from "../workspace-identity";
10
+ const temporaryDirectories = [];
11
+ const runtimeResult = (pid = 123) => ({
12
+ pid,
13
+ port: 4321,
14
+ exitPromise: new Promise(() => undefined),
15
+ getLastOutput: () => "",
16
+ });
17
+ function deferred() {
18
+ let resolve;
19
+ const promise = new Promise((resolvePromise) => { resolve = resolvePromise; });
20
+ return { promise, resolve };
21
+ }
22
+ afterEach(async () => {
23
+ await Promise.all(temporaryDirectories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })));
24
+ });
25
+ async function createLinkedWorkspace() {
26
+ const root = await mkdtemp(path.join(os.tmpdir(), "codenomad-workspace-identity-"));
27
+ temporaryDirectories.push(root);
28
+ const target = path.join(root, "target");
29
+ const link = path.join(root, "link");
30
+ await mkdir(target);
31
+ await symlink(target, link, process.platform === "win32" ? "junction" : "dir");
32
+ return { root, target, link };
33
+ }
34
+ function createManager(rootDir) {
35
+ const logger = pino({ level: "silent" });
36
+ const manager = new WorkspaceManager({
37
+ rootDir,
38
+ settings: { getOwner: () => ({ environmentVariables: {} }) },
39
+ binaryResolver: { resolve: () => ({ path: process.execPath, label: "Node.js", version: process.version }) },
40
+ eventBus: new EventBus(logger),
41
+ logger,
42
+ getServerBaseUrl: () => "http://127.0.0.1:3000",
43
+ });
44
+ manager.runtime.launch = async () => runtimeResult();
45
+ manager.runtime.stop = async () => undefined;
46
+ manager.waitForWorkspaceReadiness = async () => undefined;
47
+ return manager;
48
+ }
49
+ async function waitForOwners(manager, count) {
50
+ while ([...manager.pendingWorkspaceCreations.values()][0]?.ownership.size !== count) {
51
+ await new Promise((resolve) => setImmediate(resolve));
52
+ }
53
+ }
54
+ async function createSharedLaunch() {
55
+ const { root, target, link } = await createLinkedWorkspace();
56
+ const manager = createManager(root);
57
+ const launchGate = deferred();
58
+ let launches = 0;
59
+ manager.runtime.launch = async () => {
60
+ launches += 1;
61
+ await launchGate.promise;
62
+ return runtimeResult();
63
+ };
64
+ const leader = manager.create(target, undefined, { requestId: "leader" });
65
+ const follower = manager.create(link, undefined, { requestId: "follower" });
66
+ await waitForOwners(manager, 2);
67
+ return { manager, launchGate, leader, follower, launches: () => launches };
68
+ }
69
+ describe("workspace identity", () => {
70
+ it("normalizes Windows paths without affecting POSIX case", () => {
71
+ assert.equal(normalizeWorkspaceIdentityPath("C:\\Projects\\CodeNomad\\", "win32"), "c:\\projects\\codenomad\\");
72
+ assert.equal(normalizeWorkspaceIdentityPath(String.raw `\\Server\Share\Repo`, "win32"), String.raw `\\server\share\repo`);
73
+ assert.equal(normalizeWorkspaceIdentityPath("/Projects/CodeNomad/", "linux"), "/Projects/CodeNomad/");
74
+ });
75
+ it("canonicalizes aliases and falls back to an absolute identity for missing paths", async () => {
76
+ const { root, target, link } = await createLinkedWorkspace();
77
+ const [targetResult, linkResult, missing] = await Promise.all([
78
+ resolveWorkspaceIdentity(target, root),
79
+ resolveWorkspaceIdentity(link, root),
80
+ resolveWorkspaceIdentity("missing", root),
81
+ ]);
82
+ const expectedMissing = path.resolve(root, "missing");
83
+ assert.equal(linkResult.identityKey, targetResult.identityKey);
84
+ assert.equal(linkResult.workspacePath, targetResult.workspacePath);
85
+ assert.equal(missing.workspacePath, expectedMissing);
86
+ assert.equal(missing.identityKey, normalizeWorkspaceIdentityPath(expectedMissing));
87
+ });
88
+ it("deduplicates active canonical aliases", async () => {
89
+ const { root, target, link } = await createLinkedWorkspace();
90
+ const manager = createManager(root);
91
+ const [first, second] = await Promise.all([manager.create(target), manager.create(link)]);
92
+ assert.equal(Number(first.created) + Number(second.created), 1);
93
+ assert.equal(first.workspace.id, second.workspace.id);
94
+ assert.equal(manager.list().length, 1);
95
+ });
96
+ it("shares one in-flight launch between canonical aliases", async () => {
97
+ const shared = await createSharedLaunch();
98
+ shared.launchGate.resolve();
99
+ const [leader, follower] = await Promise.all([shared.leader, shared.follower]);
100
+ assert.equal(shared.launches(), 1);
101
+ assert.equal(leader.workspace.id, follower.workspace.id);
102
+ assert.equal(Number(leader.created) + Number(follower.created), 1);
103
+ assert.equal(leader.workspace.status, "ready");
104
+ });
105
+ for (const cancelledRole of ["leader", "follower"]) {
106
+ it(`detaches a cancelled ${cancelledRole} without stopping its shared owner`, async () => {
107
+ const shared = await createSharedLaunch();
108
+ await shared.manager.cancelCreationRequest(cancelledRole);
109
+ shared.launchGate.resolve();
110
+ const cancelled = shared[cancelledRole];
111
+ const survivor = shared[cancelledRole === "leader" ? "follower" : "leader"];
112
+ await assert.rejects(cancelled, new RegExp(`creation request ${cancelledRole} was cancelled`));
113
+ const result = await survivor;
114
+ assert.equal(shared.launches(), 1);
115
+ assert.equal(result.workspace.requestId, cancelledRole === "leader" ? "follower" : "leader");
116
+ assert.equal(shared.manager.list().length, 1);
117
+ });
118
+ }
119
+ for (const releasedRole of ["leader", "follower"]) {
120
+ it(`retains shared ownership when the ${releasedRole} releases and the other owner cancels`, async () => {
121
+ const shared = await createSharedLaunch();
122
+ shared.launchGate.resolve();
123
+ const [leader, follower] = await Promise.all([shared.leader, shared.follower]);
124
+ assert.equal(leader.workspace.id, follower.workspace.id);
125
+ assert.equal(shared.manager.releaseCreationRequest(leader.workspace.id, releasedRole), true);
126
+ await shared.manager.cancelCreationRequest(releasedRole === "leader" ? "follower" : "leader");
127
+ assert.equal(shared.manager.list().length, 1);
128
+ assert.equal(shared.manager.get(leader.workspace.id)?.requestId, undefined);
129
+ });
130
+ }
131
+ it("releases a failed canonical reservation for retry", async () => {
132
+ const { root, target, link } = await createLinkedWorkspace();
133
+ const manager = createManager(root);
134
+ const launchGate = deferred();
135
+ let launches = 0;
136
+ manager.runtime.launch = async () => {
137
+ launches += 1;
138
+ await launchGate.promise;
139
+ throw new Error("launch failed");
140
+ };
141
+ const failures = [
142
+ manager.create(target, undefined, { requestId: "first" }),
143
+ manager.create(link, undefined, { requestId: "second" }),
144
+ ];
145
+ await waitForOwners(manager, 2);
146
+ launchGate.resolve();
147
+ assert.deepEqual((await Promise.allSettled(failures)).map((result) => result.status), ["rejected", "rejected"]);
148
+ assert.equal(launches, 1);
149
+ manager.runtime.launch = async () => runtimeResult(456);
150
+ assert.equal((await manager.create(target)).created, true);
151
+ });
152
+ it("allows forced canonical duplicates without replacing the reusable workspace", async () => {
153
+ const { root, target, link } = await createLinkedWorkspace();
154
+ const manager = createManager(root);
155
+ const normal = await manager.create(target);
156
+ const forced = await manager.create(link, undefined, { forceNew: true });
157
+ assert.notEqual(normal.workspace.id, forced.workspace.id);
158
+ await manager.delete(forced.workspace.id);
159
+ const reused = await manager.create(link);
160
+ assert.equal(reused.created, false);
161
+ assert.equal(reused.workspace.id, normal.workspace.id);
162
+ });
163
+ });
@@ -0,0 +1,10 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { binaryPathsEqual } from "./manager";
4
+ test("matches regular Windows binary paths without case sensitivity", () => {
5
+ assert.equal(binaryPathsEqual(String.raw `C:\Tools\OpenCode.cmd`, String.raw `c:\tools\opencode.CMD`, "win32"), true);
6
+ });
7
+ test("matches WSL distro names without changing Linux path casing", () => {
8
+ assert.equal(binaryPathsEqual(String.raw `\\wsl.localhost\Ubuntu\home\dev\OpenCode`, String.raw `\\wsl$\ubuntu\home\dev\OpenCode`, "win32"), true);
9
+ assert.equal(binaryPathsEqual(String.raw `\\wsl.localhost\Ubuntu\home\dev\OpenCode`, String.raw `\\wsl$\ubuntu\home\dev\opencode`, "win32"), false);
10
+ });
@@ -0,0 +1,42 @@
1
+ import { createOpencodeClient } from "@opencode-ai/sdk/v2/client";
2
+ import { LOOPBACK_HOST } from "./loopback";
3
+ const LOOPBACK_TIMEOUT_MS = 10_000;
4
+ /**
5
+ * Creates an OpenCode SDK client for direct loopback communication with a
6
+ * running workspace instance.
7
+ *
8
+ * Routes and body shapes come from the auto-generated SDK contract
9
+ * (`@opencode-ai/sdk`), eliminating handwritten URL construction that can
10
+ * drift between SDK versions. Other server modules that need to call the
11
+ * OpenCode instance directly should use this factory rather than building
12
+ * `http://127.0.0.1:{port}/...` URLs by hand.
13
+ *
14
+ * Requests carry a 10-second timeout (configurable via `timeoutMs`) —
15
+ * loopback calls should be near-instant; a hang indicates a stuck instance.
16
+ *
17
+ * The client is cheap to create (object only, no connection); create one per
18
+ * call or cache per instance as needed. Returns `null` when the instance has
19
+ * no open port yet.
20
+ */
21
+ export function createInstanceClient(workspaceManager, instanceId, options = {}) {
22
+ const port = workspaceManager.getInstancePort(instanceId);
23
+ if (!port)
24
+ return null;
25
+ const headers = {};
26
+ const authorization = workspaceManager.getInstanceAuthorizationHeader(instanceId);
27
+ if (authorization) {
28
+ headers.authorization = authorization;
29
+ }
30
+ const workspace = workspaceManager.get(instanceId);
31
+ const timeoutMs = options.timeoutMs ?? LOOPBACK_TIMEOUT_MS;
32
+ const directory = options.directory ?? workspace?.path;
33
+ return createOpencodeClient({
34
+ baseUrl: `http://${LOOPBACK_HOST}:${port}/`,
35
+ headers,
36
+ fetch: (url, init) => fetch(url, {
37
+ ...init,
38
+ signal: init?.signal ?? AbortSignal.timeout(timeoutMs),
39
+ }),
40
+ ...(directory ? { directory } : {}),
41
+ });
42
+ }
@@ -0,0 +1,149 @@
1
+ import assert from "node:assert/strict";
2
+ import { describe, it } from "node:test";
3
+ import { createInstanceClient } from "./instance-client";
4
+ function makeManager(overrides = {}) {
5
+ return {
6
+ getInstancePort: overrides.getInstancePort ?? (() => undefined),
7
+ getInstanceAuthorizationHeader: overrides.getInstanceAuthorizationHeader ?? (() => undefined),
8
+ get: overrides.get ?? (() => undefined),
9
+ };
10
+ }
11
+ /**
12
+ * Installs a global `fetch` stub that records every outgoing request and
13
+ * answers a minimal healthy JSON body. Returns the capture buffer and a
14
+ * restore function. The stub tolerates both `fetch(url, init)` and
15
+ * `fetch(Request)` invocation styles so it is independent of the SDK's
16
+ * internal call convention.
17
+ */
18
+ function installRecordingFetch() {
19
+ const requests = [];
20
+ const original = globalThis.fetch;
21
+ globalThis.fetch = (async (input, init) => {
22
+ if (input instanceof Request) {
23
+ requests.push({ url: input.url, headers: new Headers(init?.headers ?? input.headers) });
24
+ }
25
+ else {
26
+ requests.push({ url: String(input), headers: new Headers(init?.headers) });
27
+ }
28
+ return new Response(JSON.stringify({ healthy: true }), {
29
+ status: 200,
30
+ headers: { "content-type": "application/json" },
31
+ });
32
+ });
33
+ return { requests, restore: () => { globalThis.fetch = original; } };
34
+ }
35
+ describe("createInstanceClient", () => {
36
+ it("returns null when the instance has no open port", () => {
37
+ const manager = makeManager({ getInstancePort: () => undefined });
38
+ assert.equal(createInstanceClient(manager, "ws-1"), null);
39
+ });
40
+ it("targets the loopback host and port on outgoing requests", async () => {
41
+ const { requests, restore } = installRecordingFetch();
42
+ try {
43
+ const manager = makeManager({ getInstancePort: () => 4321, get: () => ({ path: "/repo" }) });
44
+ const client = createInstanceClient(manager, "ws-1");
45
+ assert.ok(client, "expected a client when the instance has a port");
46
+ await client.global.health();
47
+ const parsed = new URL(requests[0].url);
48
+ assert.equal(parsed.hostname, "127.0.0.1");
49
+ assert.equal(parsed.port, "4321");
50
+ }
51
+ finally {
52
+ restore();
53
+ }
54
+ });
55
+ it("attaches the authorization header when one is configured", async () => {
56
+ const { requests, restore } = installRecordingFetch();
57
+ try {
58
+ const manager = makeManager({
59
+ getInstancePort: () => 4321,
60
+ getInstanceAuthorizationHeader: () => "Basic abc",
61
+ get: () => ({ path: "/repo" }),
62
+ });
63
+ const client = createInstanceClient(manager, "ws-1");
64
+ await client.global.health();
65
+ assert.equal(requests[0].headers.get("authorization"), "Basic abc");
66
+ }
67
+ finally {
68
+ restore();
69
+ }
70
+ });
71
+ it("omits the authorization header when none is configured", async () => {
72
+ const { requests, restore } = installRecordingFetch();
73
+ try {
74
+ const manager = makeManager({ getInstancePort: () => 4321, get: () => ({ path: "/repo" }) });
75
+ const client = createInstanceClient(manager, "ws-1");
76
+ await client.global.health();
77
+ assert.equal(requests[0].headers.get("authorization"), null);
78
+ }
79
+ finally {
80
+ restore();
81
+ }
82
+ });
83
+ it("scopes requests to the workspace directory", async () => {
84
+ const { requests, restore } = installRecordingFetch();
85
+ try {
86
+ const manager = makeManager({ getInstancePort: () => 4321, get: () => ({ path: "/repo" }) });
87
+ const client = createInstanceClient(manager, "ws-1");
88
+ await client.global.health();
89
+ // GET requests carry directory as a query parameter (see SDK rewrite).
90
+ assert.equal(new URL(requests[0].url).searchParams.get("directory"), "/repo");
91
+ }
92
+ finally {
93
+ restore();
94
+ }
95
+ });
96
+ it("does not scope requests when the workspace has no path", async () => {
97
+ const { requests, restore } = installRecordingFetch();
98
+ try {
99
+ const manager = makeManager({ getInstancePort: () => 4321, get: () => undefined });
100
+ const client = createInstanceClient(manager, "ws-1");
101
+ await client.global.health();
102
+ assert.equal(new URL(requests[0].url).searchParams.get("directory"), null);
103
+ }
104
+ finally {
105
+ restore();
106
+ }
107
+ });
108
+ it("honours an explicit directory override over the workspace root", async () => {
109
+ const { requests, restore } = installRecordingFetch();
110
+ try {
111
+ const manager = makeManager({ getInstancePort: () => 4321, get: () => ({ path: "/workspace-root" }) });
112
+ const client = createInstanceClient(manager, "ws-1", {
113
+ directory: "/explicit/session-dir",
114
+ });
115
+ await client.global.health();
116
+ assert.equal(new URL(requests[0].url).searchParams.get("directory"), "/explicit/session-dir");
117
+ }
118
+ finally {
119
+ restore();
120
+ }
121
+ });
122
+ it("applies the loopback timeout and aborts a stuck instance", async () => {
123
+ const original = globalThis.fetch;
124
+ // Never resolves on its own; only settles when the passed signal aborts,
125
+ // mirroring how a real fetch honours an AbortSignal. Without the factory
126
+ // timeout this call would hang forever and time the test out.
127
+ globalThis.fetch = (async (_input, init) => {
128
+ return new Promise((_resolve, reject) => {
129
+ const signal = init?.signal;
130
+ if (!signal)
131
+ return;
132
+ if (signal.aborted)
133
+ reject(signal.reason ?? new Error("aborted"));
134
+ else
135
+ signal.addEventListener("abort", () => reject(signal.reason ?? new Error("aborted")));
136
+ });
137
+ });
138
+ try {
139
+ const manager = makeManager({ getInstancePort: () => 4321, get: () => ({ path: "/repo" }) });
140
+ const client = createInstanceClient(manager, "ws-1", { timeoutMs: 10 });
141
+ // SDK methods resolve with { error } rather than throwing by default.
142
+ const result = await client.global.health();
143
+ assert.ok(result.error, "expected the stuck-instance call to surface an error");
144
+ }
145
+ finally {
146
+ globalThis.fetch = original;
147
+ }
148
+ });
149
+ });
@@ -1,6 +1,6 @@
1
1
  import { fetch } from "undici";
2
2
  import { Agent as UndiciAgent } from "undici";
3
- const INSTANCE_HOST = "127.0.0.1";
3
+ import { LOOPBACK_HOST } from "./loopback";
4
4
  const STREAM_AGENT = new UndiciAgent({ bodyTimeout: 0, headersTimeout: 0 });
5
5
  const RECONNECT_DELAY_MS = 1000;
6
6
  export class InstanceEventBridge {
@@ -70,7 +70,7 @@ export class InstanceEventBridge {
70
70
  }
71
71
  }
72
72
  async consumeStream(workspaceId, port, signal) {
73
- const url = `http://${INSTANCE_HOST}:${port}/global/event`;
73
+ const url = `http://${LOOPBACK_HOST}:${port}/global/event`;
74
74
  const headers = { Accept: "text/event-stream" };
75
75
  const authHeader = this.options.workspaceManager.getInstanceAuthorizationHeader(workspaceId);
76
76
  if (authHeader) {