@neuralnomads/codenomad 0.14.0 → 0.16.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 (148) hide show
  1. package/dist/cli-upgrade.js +53 -0
  2. package/dist/cli-upgrade.test.js +31 -0
  3. package/dist/filesystem/__tests__/browser.test.js +65 -0
  4. package/dist/filesystem/__tests__/search-cache.test.js +2 -2
  5. package/dist/filesystem/browser.js +40 -5
  6. package/dist/index.js +27 -6
  7. package/dist/opencode-plugin/codenomad-opencode-plugin.tgz +0 -0
  8. package/dist/opencode-plugin.js +146 -0
  9. package/dist/opencode-plugin.test.js +28 -0
  10. package/dist/previews/manager.js +63 -0
  11. package/dist/server/__tests__/remote-proxy.test.js +204 -0
  12. package/dist/server/http-server.js +380 -46
  13. package/dist/server/remote-proxy.js +466 -0
  14. package/dist/server/routes/filesystem.js +13 -0
  15. package/dist/server/routes/previews.js +25 -0
  16. package/dist/server/routes/remote-proxy.js +42 -0
  17. package/dist/server/routes/settings.js +1 -1
  18. package/dist/server/routes/workspaces.js +141 -1
  19. package/dist/workspaces/__tests__/git-clone.test.js +141 -0
  20. package/dist/workspaces/__tests__/git-worktrees.test.js +43 -0
  21. package/dist/workspaces/__tests__/spawn.test.js +158 -0
  22. package/dist/workspaces/git-clone.js +148 -0
  23. package/dist/workspaces/git-mutations.js +98 -0
  24. package/dist/workspaces/git-status.js +323 -0
  25. package/dist/workspaces/git-worktrees.js +18 -1
  26. package/dist/workspaces/manager.js +17 -9
  27. package/dist/workspaces/opencode-auth.js +18 -0
  28. package/dist/workspaces/opencode-auth.test.js +34 -0
  29. package/dist/workspaces/runtime.js +54 -77
  30. package/dist/workspaces/spawn.js +245 -0
  31. package/dist/workspaces/worktree-directory.js +74 -0
  32. package/package.json +3 -3
  33. package/public/assets/ChangesTab-CxrJwz2Z.js +2 -0
  34. package/public/assets/DiffToolbar-CqJttTgx.js +1 -0
  35. package/public/assets/FilesTab-tBrdrLID.js +2 -0
  36. package/public/assets/GitChangesTab-DUUJn4Va.js +2 -0
  37. package/public/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  38. package/public/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  39. package/public/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  40. package/public/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  41. package/public/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  42. package/public/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  43. package/public/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  44. package/public/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  45. package/public/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  46. package/public/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  47. package/public/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  48. package/public/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  49. package/public/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  50. package/public/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  51. package/public/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  52. package/public/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  53. package/public/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  54. package/public/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  55. package/public/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  56. package/public/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  57. package/public/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  58. package/public/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  59. package/public/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  60. package/public/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  61. package/public/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  62. package/public/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  63. package/public/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  64. package/public/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  65. package/public/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  66. package/public/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  67. package/public/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  68. package/public/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  69. package/public/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  70. package/public/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  71. package/public/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  72. package/public/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  73. package/public/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  74. package/public/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  75. package/public/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  76. package/public/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  77. package/public/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  78. package/public/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  79. package/public/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  80. package/public/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  81. package/public/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  82. package/public/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  83. package/public/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  84. package/public/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  85. package/public/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  86. package/public/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  87. package/public/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  88. package/public/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  89. package/public/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  90. package/public/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  91. package/public/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  92. package/public/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  93. package/public/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  94. package/public/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  95. package/public/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  96. package/public/assets/{SplitFilePanel-CupweEA5.js → SplitFilePanel-CiZrHI3o.js} +1 -1
  97. package/public/assets/StatusTab-DN31GijL.js +1 -0
  98. package/public/assets/align-justify-CKbOni6U.js +1 -0
  99. package/public/assets/{bundle-full-B-5u6Iv3.js → bundle-full-B_MbXXHv.js} +1 -1
  100. package/public/assets/{diff-viewer-_ehhYA-Z.js → diff-viewer-CersJruo.js} +1 -1
  101. package/public/assets/index-BTenW4sL.js +1 -0
  102. package/public/assets/index-BsYORY4z.js +1 -0
  103. package/public/assets/index-BvfQjuig.js +1 -0
  104. package/public/assets/{index-BqiNjV6R.js → index-CK51N0B7.js} +1 -1
  105. package/public/assets/index-Chghci_R.js +1 -0
  106. package/public/assets/{index-CxQr-wOF.js → index-DYa3o0_M.js} +1 -1
  107. package/public/assets/index-DskBWxXS.js +2 -0
  108. package/public/assets/index-DslkXxdb.js +1 -0
  109. package/public/assets/index-UCZ7MxNK.js +1 -0
  110. package/public/assets/index-i5UooSrU.css +1 -0
  111. package/public/assets/{loading-Dck2H3XH.js → loading-hkCubi3k.js} +1 -1
  112. package/public/assets/main-CXJTHRp1.js +62 -0
  113. package/public/assets/markdown-Cy9tCAXp.js +315 -0
  114. package/public/assets/monaco-viewer-B3iAKbO0.js +26 -0
  115. package/public/assets/tool-call-DhWimeRu.js +59 -0
  116. package/public/assets/{unified-picker-Dw0kTXoT.js → unified-picker-C47f5lFi.js} +1 -1
  117. package/public/assets/wrap-text-hwXbREuU.js +1 -0
  118. package/public/index.html +4 -4
  119. package/public/loading.html +4 -4
  120. package/public/sw.js +1 -1
  121. package/public/ui-version.json +1 -1
  122. package/dist/opencode-config/README.md +0 -32
  123. package/dist/opencode-config/opencode.jsonc +0 -3
  124. package/dist/opencode-config/package.json +0 -9
  125. package/dist/opencode-config/plugin/codenomad.ts +0 -62
  126. package/dist/opencode-config/plugin/lib/background-process.ts +0 -265
  127. package/dist/opencode-config/plugin/lib/client.ts +0 -133
  128. package/dist/opencode-config/plugin/lib/request.ts +0 -214
  129. package/dist/opencode-config.js +0 -26
  130. package/public/assets/ChangesTab-CFkk3tAp.js +0 -2
  131. package/public/assets/DiffToolbar-CQQLR1mp.js +0 -1
  132. package/public/assets/FilesTab-CXgucPtN.js +0 -2
  133. package/public/assets/GitChangesTab-BidSb28_.js +0 -2
  134. package/public/assets/StatusTab-C2Pl_Vce.js +0 -1
  135. package/public/assets/index-BnfDkr8C.js +0 -1
  136. package/public/assets/index-BntAaLZs.js +0 -1
  137. package/public/assets/index-BwCEJ4BE.css +0 -1
  138. package/public/assets/index-DXaitXVC.js +0 -1
  139. package/public/assets/index-DzRzoTK8.js +0 -2
  140. package/public/assets/index-ShHad48G.js +0 -1
  141. package/public/assets/index-_EaXFUIj.js +0 -1
  142. package/public/assets/index-mMh5TJvW.js +0 -1
  143. package/public/assets/main-BsIf5lOY.js +0 -50
  144. package/public/assets/markdown-CFV9kR80.js +0 -58
  145. package/public/assets/monaco-viewer-CMM6n0T3.js +0 -25
  146. package/public/assets/todo-Ghwirj-b.js +0 -1
  147. package/public/assets/tool-call-BC2Pv3uG.js +0 -60
  148. package/public/assets/wrap-text-D2MJk2ad.js +0 -1
@@ -0,0 +1,98 @@
1
+ import { spawn } from "child_process";
2
+ import path from "path";
3
+ class GitMutationError extends Error {
4
+ constructor(message, statusCode = 400) {
5
+ super(message);
6
+ this.name = "GitMutationError";
7
+ this.statusCode = statusCode;
8
+ }
9
+ }
10
+ function runGit(args, cwd) {
11
+ return new Promise((resolve) => {
12
+ const child = spawn("git", args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
13
+ let stdout = "";
14
+ let stderr = "";
15
+ child.stdout?.on("data", (chunk) => {
16
+ stdout += chunk.toString();
17
+ });
18
+ child.stderr?.on("data", (chunk) => {
19
+ stderr += chunk.toString();
20
+ });
21
+ child.once("error", (error) => {
22
+ resolve({ ok: false, error, stdout, stderr });
23
+ });
24
+ child.once("close", (code) => {
25
+ if (code === 0) {
26
+ resolve({ ok: true, stdout });
27
+ }
28
+ else {
29
+ const error = new Error(stderr.trim() || `git ${args.join(" ")} failed with code ${code}`);
30
+ resolve({ ok: false, error, stdout, stderr });
31
+ }
32
+ });
33
+ });
34
+ }
35
+ export function normalizeGitWorktreeRelativePath(input) {
36
+ const normalized = input.trim().replace(/\\+/g, "/").replace(/^\.\//, "");
37
+ if (!normalized) {
38
+ throw new GitMutationError("Path is required", 400);
39
+ }
40
+ if (path.posix.isAbsolute(normalized) || path.win32.isAbsolute(normalized)) {
41
+ throw new GitMutationError(`Absolute paths are not allowed: ${input}`, 400);
42
+ }
43
+ if (normalized === "." || normalized === "..") {
44
+ throw new GitMutationError(`Invalid path: ${input}`, 400);
45
+ }
46
+ if (normalized.startsWith("../") || normalized.includes("/../") || normalized.endsWith("/..")) {
47
+ throw new GitMutationError(`Path traversal is not allowed: ${input}`, 400);
48
+ }
49
+ return normalized;
50
+ }
51
+ function normalizeGitMutationPaths(paths) {
52
+ const deduped = new Set();
53
+ for (const rawPath of paths) {
54
+ deduped.add(normalizeGitWorktreeRelativePath(rawPath));
55
+ }
56
+ const normalized = Array.from(deduped);
57
+ if (normalized.length === 0) {
58
+ throw new GitMutationError("At least one path is required", 400);
59
+ }
60
+ return normalized;
61
+ }
62
+ async function ensureGitCommandSucceeded(resultPromise, fallbackMessage) {
63
+ const result = await resultPromise;
64
+ if (!result.ok) {
65
+ const message = result.stderr?.trim() || result.error.message || fallbackMessage;
66
+ throw new GitMutationError(message, 409);
67
+ }
68
+ return result.stdout;
69
+ }
70
+ export function isGitMutationError(error) {
71
+ return error instanceof GitMutationError;
72
+ }
73
+ export async function stageWorktreePaths(params) {
74
+ const paths = normalizeGitMutationPaths(params.paths);
75
+ await ensureGitCommandSucceeded(runGit(["add", "--", ...paths], params.workspaceFolder), "Failed to stage files");
76
+ }
77
+ export async function unstageWorktreePaths(params) {
78
+ const paths = normalizeGitMutationPaths(params.paths);
79
+ const headResult = await runGit(["rev-parse", "--verify", "HEAD"], params.workspaceFolder);
80
+ if (headResult.ok) {
81
+ await ensureGitCommandSucceeded(runGit(["restore", "--staged", "--", ...paths], params.workspaceFolder), "Failed to unstage files");
82
+ return;
83
+ }
84
+ await ensureGitCommandSucceeded(runGit(["rm", "--cached", "--quiet", "--", ...paths], params.workspaceFolder), "Failed to unstage files");
85
+ }
86
+ export async function commitWorktreeChanges(params) {
87
+ const message = params.message.trim();
88
+ if (!message) {
89
+ throw new GitMutationError("Commit message is required", 400);
90
+ }
91
+ await ensureGitCommandSucceeded(runGit(["commit", "-m", message], params.workspaceFolder), "Failed to create commit");
92
+ const shaResult = await runGit(["rev-parse", "HEAD"], params.workspaceFolder);
93
+ if (!shaResult.ok) {
94
+ return {};
95
+ }
96
+ const commitSha = shaResult.stdout.trim();
97
+ return commitSha ? { commitSha } : {};
98
+ }
@@ -0,0 +1,323 @@
1
+ import { spawn } from "child_process";
2
+ import { readFile } from "fs/promises";
3
+ import path from "path";
4
+ import { normalizeGitWorktreeRelativePath } from "./git-mutations";
5
+ async function readFileAsDiffText(filePath) {
6
+ return readFile(filePath, "utf-8");
7
+ }
8
+ async function readGitBlobAsDiffText(resultPromise, missingOk = false) {
9
+ const result = await resultPromise;
10
+ if (!result.ok) {
11
+ return decodeGitShowResult(result, missingOk);
12
+ }
13
+ return result.stdout;
14
+ }
15
+ function runGit(args, cwd, acceptedExitCodes = [0]) {
16
+ return new Promise((resolve) => {
17
+ const child = spawn("git", args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
18
+ let stdout = "";
19
+ let stderr = "";
20
+ child.stdout?.on("data", (chunk) => {
21
+ stdout += chunk.toString();
22
+ });
23
+ child.stderr?.on("data", (chunk) => {
24
+ stderr += chunk.toString();
25
+ });
26
+ child.once("error", (error) => {
27
+ resolve({ ok: false, error, stdout, stderr });
28
+ });
29
+ child.once("close", (code) => {
30
+ if (acceptedExitCodes.includes(code ?? 0)) {
31
+ resolve({ ok: true, stdout });
32
+ }
33
+ else {
34
+ const error = new Error(stderr.trim() || `git ${args.join(" ")} failed with code ${code}`);
35
+ resolve({ ok: false, error, stdout, stderr });
36
+ }
37
+ });
38
+ });
39
+ }
40
+ function ensureEntry(map, path) {
41
+ const existing = map.get(path);
42
+ if (existing)
43
+ return existing;
44
+ const next = {
45
+ path,
46
+ originalPath: null,
47
+ stagedStatus: null,
48
+ stagedAdditions: 0,
49
+ stagedDeletions: 0,
50
+ unstagedStatus: null,
51
+ unstagedAdditions: 0,
52
+ unstagedDeletions: 0,
53
+ };
54
+ map.set(path, next);
55
+ return next;
56
+ }
57
+ function normalizeGitStatusPath(value) {
58
+ return value.trim().replace(/\\+/g, "/");
59
+ }
60
+ function parseGitChangeKind(code) {
61
+ const normalized = code.trim().toUpperCase();
62
+ if (!normalized)
63
+ return null;
64
+ if (normalized === "A")
65
+ return "added";
66
+ if (normalized === "M")
67
+ return "modified";
68
+ if (normalized === "D")
69
+ return "deleted";
70
+ if (normalized.startsWith("R"))
71
+ return "renamed";
72
+ if (normalized.startsWith("C"))
73
+ return "copied";
74
+ if (normalized === "U")
75
+ return "unmerged";
76
+ return null;
77
+ }
78
+ function applyNameStatusOutput(map, output, target) {
79
+ const tokens = output.split("\0");
80
+ let index = 0;
81
+ while (index < tokens.length) {
82
+ const record = tokens[index++] ?? "";
83
+ if (!record)
84
+ continue;
85
+ const parts = record.split("\t");
86
+ const statusCode = parseGitChangeKind(parts[0] ?? "");
87
+ if (!statusCode)
88
+ continue;
89
+ const inlinePath = parts.slice(1).join("\t");
90
+ const firstPath = inlinePath || tokens[index++] || "";
91
+ const secondPath = statusCode === "renamed" || statusCode === "copied" ? tokens[index++] || "" : "";
92
+ const path = statusCode === "renamed" || statusCode === "copied" ? secondPath || firstPath : firstPath;
93
+ const normalizedPath = normalizeGitStatusPath(path);
94
+ if (!normalizedPath)
95
+ continue;
96
+ const entry = ensureEntry(map, normalizedPath);
97
+ entry[target] = statusCode;
98
+ if (statusCode === "renamed" || statusCode === "copied") {
99
+ const originalPath = normalizeGitStatusPath(firstPath);
100
+ entry.originalPath = originalPath || entry.originalPath || null;
101
+ }
102
+ }
103
+ }
104
+ function applyUntrackedOutput(map, output) {
105
+ for (const rawLine of output.split(/\r?\n/)) {
106
+ const path = normalizeGitStatusPath(rawLine);
107
+ if (!path)
108
+ continue;
109
+ ensureEntry(map, path).unstagedStatus = "untracked";
110
+ }
111
+ }
112
+ function parseSingleNumstat(output) {
113
+ for (const rawLine of output.split(/\r?\n/)) {
114
+ const line = rawLine.trim();
115
+ if (!line)
116
+ continue;
117
+ const parts = rawLine.split("\t");
118
+ const isBinary = parts[0] === "-" || parts[1] === "-";
119
+ return {
120
+ additions: isBinary ? 0 : Number.parseInt(parts[0] ?? "0", 10) || 0,
121
+ deletions: isBinary ? 0 : Number.parseInt(parts[1] ?? "0", 10) || 0,
122
+ isBinary,
123
+ found: true,
124
+ };
125
+ }
126
+ return { additions: 0, deletions: 0, isBinary: false, found: false };
127
+ }
128
+ async function getUntrackedFileNumstat(workspaceFolder, relativePath) {
129
+ const absolutePath = path.join(workspaceFolder, relativePath);
130
+ const result = await runGit(["diff", "--numstat", "--no-index", "--", "/dev/null", absolutePath], workspaceFolder, [0, 1]);
131
+ if (!result.ok) {
132
+ throw result.error;
133
+ }
134
+ const parsed = parseSingleNumstat(result.stdout);
135
+ return { additions: parsed.additions, deletions: parsed.deletions };
136
+ }
137
+ async function applyUntrackedFileStats(map, workspaceFolder) {
138
+ const pending = Array.from(map.values())
139
+ .filter((entry) => entry.unstagedStatus === "untracked")
140
+ .map(async (entry) => {
141
+ try {
142
+ const stats = await getUntrackedFileNumstat(workspaceFolder, entry.path);
143
+ entry.unstagedAdditions = stats.additions;
144
+ entry.unstagedDeletions = stats.deletions;
145
+ }
146
+ catch {
147
+ entry.unstagedAdditions = 0;
148
+ entry.unstagedDeletions = 0;
149
+ }
150
+ });
151
+ await Promise.all(pending);
152
+ }
153
+ function applyNumstatOutput(map, output, target) {
154
+ const tokens = output.split("\0");
155
+ let index = 0;
156
+ while (index < tokens.length) {
157
+ const record = tokens[index++] ?? "";
158
+ if (!record)
159
+ continue;
160
+ const parts = record.split("\t");
161
+ if (parts.length < 3)
162
+ continue;
163
+ const additions = parts[0] === "-" ? 0 : Number.parseInt(parts[0] ?? "0", 10);
164
+ const deletions = parts[1] === "-" ? 0 : Number.parseInt(parts[1] ?? "0", 10);
165
+ const inlinePath = parts.slice(2).join("\t");
166
+ const isRenameLike = inlinePath === "";
167
+ const originalPath = isRenameLike ? normalizeGitStatusPath(tokens[index++] ?? "") : null;
168
+ const normalizedPath = normalizeGitStatusPath(isRenameLike ? tokens[index++] ?? "" : inlinePath);
169
+ if (!normalizedPath)
170
+ continue;
171
+ const entry = ensureEntry(map, normalizedPath);
172
+ if (originalPath) {
173
+ entry.originalPath = originalPath;
174
+ }
175
+ if (target === "staged") {
176
+ entry.stagedAdditions = Number.isFinite(additions) ? additions : 0;
177
+ entry.stagedDeletions = Number.isFinite(deletions) ? deletions : 0;
178
+ }
179
+ else {
180
+ entry.unstagedAdditions = Number.isFinite(additions) ? additions : 0;
181
+ entry.unstagedDeletions = Number.isFinite(deletions) ? deletions : 0;
182
+ }
183
+ }
184
+ }
185
+ export async function getWorktreeGitStatus(params) {
186
+ const { workspaceFolder, logger } = params;
187
+ const [stagedResult, unstagedResult, untrackedResult, stagedNumstatResult, unstagedNumstatResult] = await Promise.all([
188
+ runGit(["diff", "--name-status", "-z", "--cached", "--find-renames", "--find-copies"], workspaceFolder),
189
+ runGit(["diff", "--name-status", "-z", "--find-renames", "--find-copies"], workspaceFolder),
190
+ runGit(["ls-files", "--others", "--exclude-standard"], workspaceFolder),
191
+ runGit(["diff", "--numstat", "-z", "--cached", "--find-renames", "--find-copies"], workspaceFolder),
192
+ runGit(["diff", "--numstat", "-z", "--find-renames", "--find-copies"], workspaceFolder),
193
+ ]);
194
+ for (const result of [stagedResult, unstagedResult, untrackedResult, stagedNumstatResult, unstagedNumstatResult]) {
195
+ if (!result.ok) {
196
+ logger?.warn?.({ workspaceFolder, err: result.error }, "Failed to read git status for worktree");
197
+ throw result.error;
198
+ }
199
+ }
200
+ const stagedOutput = stagedResult.stdout;
201
+ const unstagedOutput = unstagedResult.stdout;
202
+ const untrackedOutput = untrackedResult.stdout;
203
+ const stagedNumstatOutput = stagedNumstatResult.stdout;
204
+ const unstagedNumstatOutput = unstagedNumstatResult.stdout;
205
+ const entries = new Map();
206
+ applyNameStatusOutput(entries, stagedOutput, "stagedStatus");
207
+ applyNameStatusOutput(entries, unstagedOutput, "unstagedStatus");
208
+ applyUntrackedOutput(entries, untrackedOutput);
209
+ applyNumstatOutput(entries, stagedNumstatOutput, "staged");
210
+ applyNumstatOutput(entries, unstagedNumstatOutput, "unstaged");
211
+ await applyUntrackedFileStats(entries, workspaceFolder);
212
+ return Array.from(entries.values()).sort((a, b) => a.path.localeCompare(b.path));
213
+ }
214
+ function decodeGitShowResult(result, missingOk = false) {
215
+ if (result.ok)
216
+ return result.stdout;
217
+ const message = result.stderr?.trim() || result.error.message || "";
218
+ if (missingOk &&
219
+ (message.includes("exists on disk, but not in") ||
220
+ message.includes("Path '") ||
221
+ message.includes("does not exist") ||
222
+ message.includes("unknown revision or path not in the working tree"))) {
223
+ return "";
224
+ }
225
+ throw result.error;
226
+ }
227
+ async function readGitIndexBlob(workspaceFolder, normalizedPath) {
228
+ return runGit(["cat-file", "-p", `:${normalizedPath}`], workspaceFolder);
229
+ }
230
+ async function getTrackedDiffMetadata(params) {
231
+ const args = ["diff", "--numstat"];
232
+ if (params.scope === "staged") {
233
+ args.push("--cached");
234
+ }
235
+ args.push("--find-renames", "--find-copies", "--");
236
+ args.push(params.normalizedPath);
237
+ if (params.normalizedOriginalPath && params.normalizedOriginalPath !== params.normalizedPath) {
238
+ args.push(params.normalizedOriginalPath);
239
+ }
240
+ const result = await runGit(args, params.workspaceFolder);
241
+ if (!result.ok) {
242
+ throw result.error;
243
+ }
244
+ const parsed = parseSingleNumstat(result.stdout);
245
+ return { isBinary: parsed.isBinary, found: parsed.found };
246
+ }
247
+ async function getUntrackedDiffMetadata(params) {
248
+ const absolutePath = path.join(params.workspaceFolder, params.normalizedPath);
249
+ const result = await runGit(["diff", "--numstat", "--no-index", "--", "/dev/null", absolutePath], params.workspaceFolder, [0, 1]);
250
+ if (!result.ok) {
251
+ throw result.error;
252
+ }
253
+ return { isBinary: parseSingleNumstat(result.stdout).isBinary };
254
+ }
255
+ async function resolveUnstagedBeforePath(params) {
256
+ const currentPathResult = await readGitIndexBlob(params.workspaceFolder, params.normalizedPath);
257
+ if (currentPathResult.ok || !params.normalizedOriginalPath || params.normalizedOriginalPath === params.normalizedPath) {
258
+ return currentPathResult;
259
+ }
260
+ return readGitIndexBlob(params.workspaceFolder, params.normalizedOriginalPath);
261
+ }
262
+ export async function getWorktreeGitDiff(params) {
263
+ const normalizedPath = normalizeGitWorktreeRelativePath(params.path);
264
+ const normalizedOriginalPath = params.originalPath ? normalizeGitWorktreeRelativePath(params.originalPath) : null;
265
+ const trackedMetadata = await getTrackedDiffMetadata({
266
+ workspaceFolder: params.workspaceFolder,
267
+ scope: params.scope,
268
+ normalizedPath,
269
+ normalizedOriginalPath,
270
+ });
271
+ const diffMetadata = params.scope === "unstaged" && !trackedMetadata.found
272
+ ? await getUntrackedDiffMetadata({
273
+ workspaceFolder: params.workspaceFolder,
274
+ normalizedPath,
275
+ })
276
+ : trackedMetadata;
277
+ if (diffMetadata.isBinary) {
278
+ return {
279
+ path: normalizedPath,
280
+ originalPath: normalizedOriginalPath,
281
+ scope: params.scope,
282
+ before: "",
283
+ after: "",
284
+ isBinary: true,
285
+ };
286
+ }
287
+ if (params.scope === "staged") {
288
+ const [beforeResult, afterResult] = await Promise.all([
289
+ readGitBlobAsDiffText(runGit(["show", `HEAD:${normalizedOriginalPath ?? normalizedPath}`], params.workspaceFolder), true),
290
+ readGitBlobAsDiffText(readGitIndexBlob(params.workspaceFolder, normalizedPath), true),
291
+ ]);
292
+ return {
293
+ path: normalizedPath,
294
+ originalPath: normalizedOriginalPath,
295
+ scope: params.scope,
296
+ before: beforeResult,
297
+ after: afterResult,
298
+ isBinary: false,
299
+ };
300
+ }
301
+ const indexResult = await resolveUnstagedBeforePath({
302
+ workspaceFolder: params.workspaceFolder,
303
+ normalizedPath,
304
+ normalizedOriginalPath,
305
+ });
306
+ const beforeResult = await readGitBlobAsDiffText(Promise.resolve(indexResult), true);
307
+ let after = beforeResult;
308
+ const fsPath = path.join(params.workspaceFolder, normalizedPath);
309
+ try {
310
+ after = await readFileAsDiffText(fsPath);
311
+ }
312
+ catch {
313
+ after = "";
314
+ }
315
+ return {
316
+ path: normalizedPath,
317
+ originalPath: normalizedOriginalPath,
318
+ scope: params.scope,
319
+ before: beforeResult,
320
+ after,
321
+ isBinary: false,
322
+ };
323
+ }
@@ -1,6 +1,9 @@
1
1
  import path from "path";
2
2
  import { spawn } from "child_process";
3
3
  import { promises as fsp } from "fs";
4
+ function isGitUnavailableResult(result) {
5
+ return !result.ok && result.error?.code === "ENOENT";
6
+ }
4
7
  function runGit(args, cwd) {
5
8
  return new Promise((resolve) => {
6
9
  const child = spawn("git", args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
@@ -28,6 +31,9 @@ function runGit(args, cwd) {
28
31
  }
29
32
  export async function resolveRepoRoot(folder, logger) {
30
33
  const result = await runGit(["rev-parse", "--show-toplevel"], folder);
34
+ if (isGitUnavailableResult(result)) {
35
+ throw new Error("Git is not installed or not available in PATH");
36
+ }
31
37
  if (!result.ok) {
32
38
  logger?.debug?.({ folder, err: result.error }, "Folder is not a Git repository; using workspace folder as root");
33
39
  return { repoRoot: folder, isGitRepo: false };
@@ -38,6 +44,10 @@ export async function resolveRepoRoot(folder, logger) {
38
44
  }
39
45
  return { repoRoot, isGitRepo: true };
40
46
  }
47
+ export async function isGitAvailable(folder) {
48
+ const result = await runGit(["--version"], folder);
49
+ return result.ok || !isGitUnavailableResult(result);
50
+ }
41
51
  function parseWorktreePorcelain(output) {
42
52
  const records = [];
43
53
  const lines = output.split(/\r?\n/);
@@ -75,13 +85,20 @@ function parseWorktreePorcelain(output) {
75
85
  }
76
86
  export async function listWorktrees(params) {
77
87
  const { repoRoot, workspaceFolder, logger } = params;
78
- const rootDescriptor = { slug: "root", directory: repoRoot, kind: "root" };
79
88
  const result = await runGit(["worktree", "list", "--porcelain"], workspaceFolder);
80
89
  if (!result.ok) {
90
+ const rootDescriptor = { slug: "root", directory: workspaceFolder, kind: "root" };
81
91
  logger?.debug?.({ repoRoot, err: result.error }, "Failed to list git worktrees; returning root only");
82
92
  return [rootDescriptor];
83
93
  }
84
94
  const records = parseWorktreePorcelain(result.stdout);
95
+ const rootRecord = records.find((record) => path.resolve(record.worktree) === path.resolve(repoRoot));
96
+ const rootDescriptor = {
97
+ slug: "root",
98
+ directory: workspaceFolder,
99
+ kind: "root",
100
+ branch: rootRecord?.branch,
101
+ };
85
102
  const worktrees = [rootDescriptor];
86
103
  const seen = new Set(["root"]);
87
104
  const normalizeSlug = (record) => {
@@ -5,8 +5,8 @@ import { FileSystemBrowser } from "../filesystem/browser";
5
5
  import { searchWorkspaceFiles } from "../filesystem/search";
6
6
  import { clearWorkspaceSearchCache } from "../filesystem/search-cache";
7
7
  import { WorkspaceRuntime } from "./runtime";
8
- import { getOpencodeConfigDir } from "../opencode-config.js";
9
- import { buildOpencodeBasicAuthHeader, DEFAULT_OPENCODE_USERNAME, generateOpencodeServerPassword, OPENCODE_SERVER_PASSWORD_ENV, OPENCODE_SERVER_USERNAME_ENV, } from "./opencode-auth";
8
+ import { buildOpencodeConfigContent, getCodeNomadPluginUrl, resolveExistingOpencodeConfigContent, } from "../opencode-plugin.js";
9
+ import { OPENCODE_SERVER_BASE_URL_ENV, buildOpencodeBasicAuthHeader, OPENCODE_SERVER_PASSWORD_ENV, OPENCODE_SERVER_USERNAME_ENV, resolveOpencodeServerAuth, } from "./opencode-auth";
10
10
  const STARTUP_STABILITY_DELAY_MS = 1500;
11
11
  export class WorkspaceManager {
12
12
  constructor(options) {
@@ -14,7 +14,7 @@ export class WorkspaceManager {
14
14
  this.workspaces = new Map();
15
15
  this.opencodeAuth = new Map();
16
16
  this.runtime = new WorkspaceRuntime(this.options.eventBus, this.options.logger);
17
- this.opencodeConfigDir = getOpencodeConfigDir();
17
+ this.codeNomadPluginUrl = getCodeNomadPluginUrl();
18
18
  }
19
19
  list() {
20
20
  return Array.from(this.workspaces.values());
@@ -37,14 +37,16 @@ export class WorkspaceManager {
37
37
  const workspace = this.requireWorkspace(workspaceId);
38
38
  return searchWorkspaceFiles(workspace.path, query, options);
39
39
  }
40
- readFile(workspaceId, relativePath) {
40
+ readFile(workspaceId, relativePath, options) {
41
41
  const workspace = this.requireWorkspace(workspaceId);
42
42
  const browser = new FileSystemBrowser({ rootDir: workspace.path });
43
- const contents = browser.readFile(relativePath);
43
+ const encoding = options?.encoding ?? "utf-8";
44
+ const contents = encoding === "base64" ? browser.readFileBase64(relativePath) : browser.readFile(relativePath);
44
45
  return {
45
46
  workspaceId,
46
47
  relativePath,
47
48
  contents,
49
+ encoding,
48
50
  };
49
51
  }
50
52
  writeFile(workspaceId, relativePath, contents) {
@@ -77,8 +79,13 @@ export class WorkspaceManager {
77
79
  const serverConfig = this.options.settings.getOwner("config", "server");
78
80
  const envVars = serverConfig?.environmentVariables;
79
81
  const userEnvironment = envVars && typeof envVars === "object" && !Array.isArray(envVars) ? envVars : {};
80
- const opencodeUsername = DEFAULT_OPENCODE_USERNAME;
81
- const opencodePassword = generateOpencodeServerPassword();
82
+ const opencodeConfigContent = buildOpencodeConfigContent(resolveExistingOpencodeConfigContent(userEnvironment), this.codeNomadPluginUrl);
83
+ const serverBaseUrl = this.options.getServerBaseUrl();
84
+ const normalizedServerBaseUrl = serverBaseUrl.replace(/\/+$/, "");
85
+ const { username: opencodeUsername, password: opencodePassword } = resolveOpencodeServerAuth({
86
+ userEnvironment,
87
+ processEnv: process.env,
88
+ });
82
89
  const authorization = buildOpencodeBasicAuthHeader({ username: opencodeUsername, password: opencodePassword });
83
90
  if (!authorization) {
84
91
  throw new Error("Failed to build OpenCode auth header");
@@ -86,10 +93,11 @@ export class WorkspaceManager {
86
93
  this.opencodeAuth.set(id, { username: opencodeUsername, password: opencodePassword, authorization });
87
94
  const environment = {
88
95
  ...userEnvironment,
89
- OPENCODE_CONFIG_DIR: this.opencodeConfigDir,
96
+ OPENCODE_CONFIG_CONTENT: opencodeConfigContent,
90
97
  CODENOMAD_INSTANCE_ID: id,
91
- CODENOMAD_BASE_URL: this.options.getServerBaseUrl(),
98
+ CODENOMAD_BASE_URL: serverBaseUrl,
92
99
  ...(this.options.nodeExtraCaCertsPath ? { NODE_EXTRA_CA_CERTS: this.options.nodeExtraCaCertsPath } : {}),
100
+ [OPENCODE_SERVER_BASE_URL_ENV]: `${normalizedServerBaseUrl}${proxyPath}`,
93
101
  [OPENCODE_SERVER_USERNAME_ENV]: opencodeUsername,
94
102
  [OPENCODE_SERVER_PASSWORD_ENV]: opencodePassword,
95
103
  };
@@ -1,10 +1,28 @@
1
1
  import crypto from "node:crypto";
2
2
  export const OPENCODE_SERVER_USERNAME_ENV = "OPENCODE_SERVER_USERNAME";
3
3
  export const OPENCODE_SERVER_PASSWORD_ENV = "OPENCODE_SERVER_PASSWORD";
4
+ export const OPENCODE_SERVER_BASE_URL_ENV = "OPENCODE_SERVER_BASE_URL";
4
5
  export const DEFAULT_OPENCODE_USERNAME = "codenomad";
5
6
  export function generateOpencodeServerPassword() {
6
7
  return crypto.randomBytes(32).toString("base64url");
7
8
  }
9
+ function readConfiguredValue(key, ...sources) {
10
+ for (const source of sources) {
11
+ const value = source?.[key];
12
+ if (typeof value === "string" && value.trim().length > 0) {
13
+ return value;
14
+ }
15
+ }
16
+ return undefined;
17
+ }
18
+ export function resolveOpencodeServerAuth(options = {}) {
19
+ const generatePassword = options.generatePassword ?? generateOpencodeServerPassword;
20
+ const username = readConfiguredValue(OPENCODE_SERVER_USERNAME_ENV, options.userEnvironment, options.processEnv) ??
21
+ DEFAULT_OPENCODE_USERNAME;
22
+ const password = readConfiguredValue(OPENCODE_SERVER_PASSWORD_ENV, options.userEnvironment, options.processEnv) ??
23
+ generatePassword();
24
+ return { username, password };
25
+ }
8
26
  export function buildOpencodeBasicAuthHeader(params) {
9
27
  const username = params.username;
10
28
  const password = params.password;
@@ -0,0 +1,34 @@
1
+ import assert from "node:assert/strict";
2
+ import { describe, it } from "node:test";
3
+ import { resolveOpencodeServerAuth } from "./opencode-auth";
4
+ describe("resolveOpencodeServerAuth", () => {
5
+ it("uses configured OpenCode auth from workspace environment", () => {
6
+ const auth = resolveOpencodeServerAuth({
7
+ userEnvironment: {
8
+ OPENCODE_SERVER_USERNAME: "alice",
9
+ OPENCODE_SERVER_PASSWORD: "secret",
10
+ },
11
+ processEnv: {},
12
+ generatePassword: () => "generated",
13
+ });
14
+ assert.deepEqual(auth, { username: "alice", password: "secret" });
15
+ });
16
+ it("uses process environment when workspace environment does not provide credentials", () => {
17
+ const auth = resolveOpencodeServerAuth({
18
+ userEnvironment: {},
19
+ processEnv: {
20
+ OPENCODE_SERVER_PASSWORD: "process-secret",
21
+ },
22
+ generatePassword: () => "generated",
23
+ });
24
+ assert.deepEqual(auth, { username: "codenomad", password: "process-secret" });
25
+ });
26
+ it("falls back to generated credentials", () => {
27
+ const auth = resolveOpencodeServerAuth({
28
+ userEnvironment: {},
29
+ processEnv: {},
30
+ generatePassword: () => "generated",
31
+ });
32
+ assert.deepEqual(auth, { username: "codenomad", password: "generated" });
33
+ });
34
+ });