@neuralnomads/codenomad 0.15.0 → 0.17.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 (145) hide show
  1. package/README.md +50 -4
  2. package/dist/background-processes/manager.js +0 -1
  3. package/dist/config/schema.js +1 -0
  4. package/dist/filesystem/__tests__/browser.test.js +65 -0
  5. package/dist/filesystem/__tests__/search-cache.test.js +2 -2
  6. package/dist/filesystem/browser.js +25 -4
  7. package/dist/index.js +13 -6
  8. package/dist/launcher.js +12 -1
  9. package/dist/opencode-plugin/codenomad-opencode-plugin.tgz +0 -0
  10. package/dist/opencode-plugin.js +146 -0
  11. package/dist/opencode-plugin.test.js +28 -0
  12. package/dist/previews/manager.js +63 -0
  13. package/dist/server/__tests__/listener-base-url.test.js +30 -0
  14. package/dist/server/http-server.js +378 -152
  15. package/dist/server/listener-base-url.js +17 -0
  16. package/dist/server/routes/config-files.js +92 -0
  17. package/dist/server/routes/config-files.test.js +115 -0
  18. package/dist/server/routes/filesystem.js +13 -0
  19. package/dist/server/routes/previews.js +25 -0
  20. package/dist/server/routes/workspaces.js +38 -1
  21. package/dist/workspaces/__tests__/git-clone.test.js +142 -0
  22. package/dist/workspaces/__tests__/spawn.test.js +27 -9
  23. package/dist/workspaces/git-clone.js +148 -0
  24. package/dist/workspaces/manager.js +27 -6
  25. package/dist/workspaces/spawn.js +35 -9
  26. package/dist/workspaces/worktree-map.js +16 -0
  27. package/package.json +3 -3
  28. package/public/assets/FilesTab-B5ysoRLh.js +2 -0
  29. package/public/assets/GitChangesTab-BksCi53d.js +2 -0
  30. package/public/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  31. package/public/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  32. package/public/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  33. package/public/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  34. package/public/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  35. package/public/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  36. package/public/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  37. package/public/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  38. package/public/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  39. package/public/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  40. package/public/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  41. package/public/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  42. package/public/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  43. package/public/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  44. package/public/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  45. package/public/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  46. package/public/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  47. package/public/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  48. package/public/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  49. package/public/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  50. package/public/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  51. package/public/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  52. package/public/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  53. package/public/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  54. package/public/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  55. package/public/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  56. package/public/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  57. package/public/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  58. package/public/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  59. package/public/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  60. package/public/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  61. package/public/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  62. package/public/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  63. package/public/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  64. package/public/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  65. package/public/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  66. package/public/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  67. package/public/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  68. package/public/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  69. package/public/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  70. package/public/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  71. package/public/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  72. package/public/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  73. package/public/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  74. package/public/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  75. package/public/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  76. package/public/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  77. package/public/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  78. package/public/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  79. package/public/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  80. package/public/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  81. package/public/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  82. package/public/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  83. package/public/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  84. package/public/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  85. package/public/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  86. package/public/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  87. package/public/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  88. package/public/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  89. package/public/assets/{SplitFilePanel-BOHH3F--.js → SplitFilePanel-CrSfR22r.js} +1 -1
  90. package/public/assets/StatusTab-Dgqekgjn.js +1 -0
  91. package/public/assets/{align-justify-9zpyaAdy.js → align-justify-hRtBz8xe.js} +1 -1
  92. package/public/assets/{bundle-full-xFW13Lny.js → bundle-full-BVDA-a9Y.js} +2 -2
  93. package/public/assets/{diff-viewer-xG9yjpN8.js → diff-viewer-BCAI0Cw8.js} +1 -1
  94. package/public/assets/index-B2Qd6xQq.css +1 -0
  95. package/public/assets/index-BQpEhdk5.js +1 -0
  96. package/public/assets/index-BXIEm2zT.js +1 -0
  97. package/public/assets/index-CWjU9mAF.js +1 -0
  98. package/public/assets/index-Cvtlo58a.js +1 -0
  99. package/public/assets/index-DFlxnvHT.js +2 -0
  100. package/public/assets/index-Ddsv8Uc0.js +1 -0
  101. package/public/assets/index-Dn7woJnK.js +1 -0
  102. package/public/assets/index-DnCBfFB3.js +1 -0
  103. package/public/assets/index-DnXT1F8T.js +1 -0
  104. package/public/assets/index-Kv-3BRTi.js +1 -0
  105. package/public/assets/index-g-G1RiME.js +1 -0
  106. package/public/assets/{loading-HUhLEgb_.js → loading-bD3ppK2l.js} +1 -1
  107. package/public/assets/main-BsbMOeQg.js +65 -0
  108. package/public/assets/markdown-DJuaMC5H.js +315 -0
  109. package/public/assets/monaco-viewer-BFNhPQX7.js +26 -0
  110. package/public/assets/tool-call-BSJluZRW.js +59 -0
  111. package/public/assets/{unified-picker-DuNuUpLy.js → unified-picker-DmFyrIis.js} +1 -1
  112. package/public/assets/{wrap-text-zghCl6wN.js → wrap-text-BkcW_eTA.js} +1 -1
  113. package/public/index.html +4 -4
  114. package/public/loading.html +4 -4
  115. package/public/sw.js +1 -1
  116. package/public/ui-version.json +1 -1
  117. package/dist/opencode-config/README.md +0 -32
  118. package/dist/opencode-config/opencode.jsonc +0 -3
  119. package/dist/opencode-config/package-lock.json +0 -380
  120. package/dist/opencode-config/package.json +0 -9
  121. package/dist/opencode-config/plugin/codenomad.ts +0 -62
  122. package/dist/opencode-config/plugin/lib/background-process.ts +0 -265
  123. package/dist/opencode-config/plugin/lib/client.ts +0 -133
  124. package/dist/opencode-config/plugin/lib/request.ts +0 -214
  125. package/dist/opencode-config.js +0 -26
  126. package/public/assets/ChangesTab-ovdqLHc3.js +0 -2
  127. package/public/assets/DiffToolbar-B12EfXMX.js +0 -1
  128. package/public/assets/FilesTab-nb_itEXG.js +0 -2
  129. package/public/assets/GitChangesTab-DcT_4BL2.js +0 -2
  130. package/public/assets/StatusTab-Dyt_EG33.js +0 -1
  131. package/public/assets/index-7DpT014-.js +0 -1
  132. package/public/assets/index-BDK4V9L0.js +0 -1
  133. package/public/assets/index-Bx-Bezt2.js +0 -1
  134. package/public/assets/index-CCAZZY0l.js +0 -1
  135. package/public/assets/index-CEcZq5WB.js +0 -1
  136. package/public/assets/index-CQCmSDHL.js +0 -1
  137. package/public/assets/index-Cz_fl8aY.js +0 -1
  138. package/public/assets/index-Dcgftm1m.css +0 -1
  139. package/public/assets/index-m4C3yx3J.js +0 -1
  140. package/public/assets/index-mh_z9p40.js +0 -2
  141. package/public/assets/main-CKhfaeKI.js +0 -48
  142. package/public/assets/markdown-BeXU9Z-x.js +0 -58
  143. package/public/assets/monaco-viewer-BgP6xpZ6.js +0 -26
  144. package/public/assets/todo-D6PVVp_f.js +0 -1
  145. package/public/assets/tool-call-Dgn3NlA8.js +0 -60
@@ -0,0 +1,17 @@
1
+ export function resolvePluginBaseUrl(input) {
2
+ const loopbackListener = [input.httpStart, input.httpsStart].find((listener) => listener && acceptsLoopback(listener.bindHost));
3
+ if (loopbackListener) {
4
+ return `${loopbackListener.protocol}://127.0.0.1:${loopbackListener.port}`;
5
+ }
6
+ if (input.remoteUrl) {
7
+ return input.remoteUrl;
8
+ }
9
+ const fallbackListener = input.httpStart ?? input.httpsStart;
10
+ if (!fallbackListener) {
11
+ throw new Error("No listeners started");
12
+ }
13
+ return `${fallbackListener.protocol}://${fallbackListener.bindHost}:${fallbackListener.port}`;
14
+ }
15
+ function acceptsLoopback(bindHost) {
16
+ return bindHost === "0.0.0.0" || bindHost === "::" || bindHost === "localhost" || bindHost === "::1" || bindHost.startsWith("127.");
17
+ }
@@ -0,0 +1,92 @@
1
+ import fs from "fs/promises";
2
+ import os from "os";
3
+ import path from "path";
4
+ import { z } from "zod";
5
+ const ConfigFileContentBodySchema = z.object({
6
+ contents: z.string(),
7
+ });
8
+ function resolveOpenCodeGlobalConfigPaths() {
9
+ if (process.platform === "win32") {
10
+ const basePath = path.join(os.homedir(), ".config", "opencode");
11
+ return [
12
+ {
13
+ id: "opencode-global-config",
14
+ label: "OpenCode Global Config",
15
+ path: "%USERPROFILE%\\.config\\opencode\\opencode.json",
16
+ absolutePath: path.join(basePath, "opencode.json"),
17
+ language: "json",
18
+ },
19
+ {
20
+ id: "opencode-global-config-jsonc",
21
+ label: "OpenCode Global Config (JSONC)",
22
+ path: "%USERPROFILE%\\.config\\opencode\\opencode.jsonc",
23
+ absolutePath: path.join(basePath, "opencode.jsonc"),
24
+ language: "jsonc",
25
+ },
26
+ ];
27
+ }
28
+ return [
29
+ {
30
+ id: "opencode-global-config",
31
+ label: "OpenCode Global Config",
32
+ path: "~/.config/opencode/opencode.json",
33
+ absolutePath: path.join(os.homedir(), ".config", "opencode", "opencode.json"),
34
+ language: "json",
35
+ },
36
+ {
37
+ id: "opencode-global-config-jsonc",
38
+ label: "OpenCode Global Config (JSONC)",
39
+ path: "~/.config/opencode/opencode.jsonc",
40
+ absolutePath: path.join(os.homedir(), ".config", "opencode", "opencode.jsonc"),
41
+ language: "jsonc",
42
+ },
43
+ ];
44
+ }
45
+ function defaultConfigFileEntries() {
46
+ return resolveOpenCodeGlobalConfigPaths();
47
+ }
48
+ function listConfigFiles(files) {
49
+ return files.map(({ absolutePath: _absolutePath, ...file }) => file);
50
+ }
51
+ function getConfigFile(files, id) {
52
+ return files.find((file) => file.id === id) ?? null;
53
+ }
54
+ export function registerConfigFileRoutes(app, options = {}) {
55
+ const configFiles = options.files ?? defaultConfigFileEntries();
56
+ app.get("/api/config-files", async () => listConfigFiles(configFiles));
57
+ app.get("/api/config-files/:id/content", async (request, reply) => {
58
+ const file = getConfigFile(configFiles, request.params.id);
59
+ if (!file) {
60
+ reply.code(404);
61
+ return { error: "Config file not found" };
62
+ }
63
+ try {
64
+ const contents = await fs.readFile(file.absolutePath, "utf-8");
65
+ return { id: file.id, path: file.path, contents, exists: true };
66
+ }
67
+ catch (error) {
68
+ if (error.code === "ENOENT") {
69
+ return { id: file.id, path: file.path, contents: "", exists: false };
70
+ }
71
+ reply.code(400);
72
+ return { error: error instanceof Error ? error.message : "Failed to read config file" };
73
+ }
74
+ });
75
+ app.put("/api/config-files/:id/content", async (request, reply) => {
76
+ const file = getConfigFile(configFiles, request.params.id);
77
+ if (!file) {
78
+ reply.code(404);
79
+ return { error: "Config file not found" };
80
+ }
81
+ try {
82
+ const body = ConfigFileContentBodySchema.parse(request.body ?? {});
83
+ await fs.mkdir(path.dirname(file.absolutePath), { recursive: true });
84
+ await fs.writeFile(file.absolutePath, body.contents, "utf-8");
85
+ reply.code(204);
86
+ }
87
+ catch (error) {
88
+ reply.code(400);
89
+ return { error: error instanceof Error ? error.message : "Failed to save config file" };
90
+ }
91
+ });
92
+ }
@@ -0,0 +1,115 @@
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 { afterEach, describe, it } from "node:test";
6
+ import Fastify from "fastify";
7
+ import { registerConfigFileRoutes } from "./config-files";
8
+ const tempDirs = new Set();
9
+ afterEach(() => {
10
+ for (const dir of tempDirs) {
11
+ fs.rmSync(dir, { recursive: true, force: true });
12
+ }
13
+ tempDirs.clear();
14
+ });
15
+ describe("config file routes", () => {
16
+ it("lists only allowlisted config file descriptors", async () => {
17
+ const tempDir = createTempDir();
18
+ const app = createApp([
19
+ createConfigEntry(path.join(tempDir, "opencode", "opencode.json"), "~/.config/opencode/opencode.json"),
20
+ createConfigEntry(path.join(tempDir, "opencode", "opencode.jsonc"), "~/.config/opencode/opencode.jsonc", {
21
+ id: "test-config-jsonc",
22
+ label: "Test Config JSONC",
23
+ language: "jsonc",
24
+ }),
25
+ ]);
26
+ const response = await app.inject({ method: "GET", url: "/api/config-files" });
27
+ assert.equal(response.statusCode, 200);
28
+ assert.deepEqual(response.json(), [
29
+ {
30
+ id: "test-config",
31
+ label: "Test Config",
32
+ path: "~/.config/opencode/opencode.json",
33
+ language: "json",
34
+ },
35
+ {
36
+ id: "test-config-jsonc",
37
+ label: "Test Config JSONC",
38
+ path: "~/.config/opencode/opencode.jsonc",
39
+ language: "jsonc",
40
+ },
41
+ ]);
42
+ await app.close();
43
+ });
44
+ it("returns empty content for an allowlisted missing file", async () => {
45
+ const tempDir = createTempDir();
46
+ const app = createApp([createConfigEntry(path.join(tempDir, "missing", "config.json"), "display/config.json")]);
47
+ const response = await app.inject({ method: "GET", url: "/api/config-files/test-config/content" });
48
+ assert.equal(response.statusCode, 200);
49
+ assert.deepEqual(response.json(), {
50
+ id: "test-config",
51
+ path: "display/config.json",
52
+ contents: "",
53
+ exists: false,
54
+ });
55
+ await app.close();
56
+ });
57
+ it("creates parent directories when writing an allowlisted file", async () => {
58
+ const tempDir = createTempDir();
59
+ const targetPath = path.join(tempDir, "nested", "opencode.json");
60
+ const app = createApp([createConfigEntry(targetPath, "display/opencode.json")]);
61
+ const response = await app.inject({
62
+ method: "PUT",
63
+ url: "/api/config-files/test-config/content",
64
+ payload: { contents: '{"model":"test"}' },
65
+ });
66
+ assert.equal(response.statusCode, 204);
67
+ assert.equal(fs.readFileSync(targetPath, "utf-8"), '{"model":"test"}');
68
+ await app.close();
69
+ });
70
+ it("rejects unknown config file ids", async () => {
71
+ const tempDir = createTempDir();
72
+ const app = createApp([createConfigEntry(path.join(tempDir, "opencode.json"), "display/opencode.json")]);
73
+ const readResponse = await app.inject({ method: "GET", url: "/api/config-files/unknown/content" });
74
+ const writeResponse = await app.inject({
75
+ method: "PUT",
76
+ url: "/api/config-files/unknown/content",
77
+ payload: { contents: "{}" },
78
+ });
79
+ assert.equal(readResponse.statusCode, 404);
80
+ assert.equal(writeResponse.statusCode, 404);
81
+ await app.close();
82
+ });
83
+ it("returns a client error when writes fail", async () => {
84
+ const tempDir = createTempDir();
85
+ const blockedParent = path.join(tempDir, "not-a-directory");
86
+ fs.writeFileSync(blockedParent, "occupied");
87
+ const app = createApp([createConfigEntry(path.join(blockedParent, "opencode.json"), "display/opencode.json")]);
88
+ const response = await app.inject({
89
+ method: "PUT",
90
+ url: "/api/config-files/test-config/content",
91
+ payload: { contents: "{}" },
92
+ });
93
+ assert.equal(response.statusCode, 400);
94
+ await app.close();
95
+ });
96
+ });
97
+ function createTempDir() {
98
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-config-files-test-"));
99
+ tempDirs.add(dir);
100
+ return dir;
101
+ }
102
+ function createConfigEntry(absolutePath, displayPath, overrides = {}) {
103
+ return {
104
+ id: overrides.id ?? "test-config",
105
+ label: overrides.label ?? "Test Config",
106
+ path: displayPath,
107
+ absolutePath,
108
+ language: overrides.language ?? "json",
109
+ };
110
+ }
111
+ function createApp(files) {
112
+ const app = Fastify({ logger: false });
113
+ registerConfigFileRoutes(app, { files });
114
+ return app;
115
+ }
@@ -7,6 +7,10 @@ const FilesystemCreateFolderSchema = z.object({
7
7
  parentPath: z.string().optional(),
8
8
  name: z.string(),
9
9
  });
10
+ const FilesystemFileContentQuerySchema = z.object({
11
+ path: z.string(),
12
+ encoding: z.enum(["utf-8", "base64"]).optional(),
13
+ });
10
14
  export function registerFilesystemRoutes(app, deps) {
11
15
  app.get("/api/filesystem", async (request, reply) => {
12
16
  const query = FilesystemQuerySchema.parse(request.query ?? {});
@@ -40,4 +44,13 @@ export function registerFilesystemRoutes(app, deps) {
40
44
  reply.code(400).type("text/plain").send(error.message);
41
45
  }
42
46
  });
47
+ app.get("/api/filesystem/files/content", async (request, reply) => {
48
+ const query = FilesystemFileContentQuerySchema.parse(request.query ?? {});
49
+ try {
50
+ return deps.fileSystemBrowser.readFileContent(query.path, { encoding: query.encoding });
51
+ }
52
+ catch (error) {
53
+ reply.code(400).type("text/plain").send(error.message);
54
+ }
55
+ });
43
56
  }
@@ -0,0 +1,25 @@
1
+ import { z } from "zod";
2
+ const PreviewCreateSchema = z.object({
3
+ sessionId: z.string().trim().min(1),
4
+ url: z.string().trim().min(1),
5
+ });
6
+ export function registerPreviewRoutes(app, deps) {
7
+ app.post("/api/previews", async (request, reply) => {
8
+ try {
9
+ const body = PreviewCreateSchema.parse(request.body ?? {});
10
+ return deps.previewManager.create(body.sessionId, body.url);
11
+ }
12
+ catch (error) {
13
+ reply.code(400);
14
+ return { error: error instanceof Error ? error.message : "Failed to create preview" };
15
+ }
16
+ });
17
+ app.delete("/api/previews/:token", async (request, reply) => {
18
+ const removed = deps.previewManager.delete(request.params.token);
19
+ if (!removed) {
20
+ reply.code(404);
21
+ return { error: "Preview not found" };
22
+ }
23
+ reply.code(204);
24
+ });
25
+ }
@@ -1,17 +1,25 @@
1
1
  import { z } from "zod";
2
2
  import { getWorktreeGitDiff, getWorktreeGitStatus } from "../../workspaces/git-status";
3
3
  import { commitWorktreeChanges, isGitMutationError, stageWorktreePaths, unstageWorktreePaths } from "../../workspaces/git-mutations";
4
+ import { cloneGitRepository, isGitCloneError } from "../../workspaces/git-clone";
4
5
  import { isGitAvailable, resolveRepoRoot } from "../../workspaces/git-worktrees";
5
6
  import { resolveWorktreeDirectory } from "../../workspaces/worktree-directory";
6
7
  const WorkspaceCreateSchema = z.object({
7
8
  path: z.string(),
8
9
  name: z.string().optional(),
9
10
  });
11
+ const WorkspaceCloneSchema = z.object({
12
+ repositoryUrl: z.string().trim().min(1, "Repository URL is required"),
13
+ destinationPath: z.string().trim().min(1, "Destination path is required"),
14
+ cleanup: z.boolean().optional(),
15
+ });
10
16
  const WorkspaceFilesQuerySchema = z.object({
11
17
  path: z.string().optional(),
12
18
  });
13
19
  const WorkspaceFileContentQuerySchema = z.object({
14
20
  path: z.string(),
21
+ encoding: z.enum(["utf-8", "base64"]).optional(),
22
+ worktree: z.string().trim().optional(),
15
23
  });
16
24
  const WorkspaceFileContentBodySchema = z.object({
17
25
  contents: z.string(),
@@ -53,6 +61,17 @@ export function registerWorkspaceRoutes(app, deps) {
53
61
  reply.code(400).type("text/plain").send(message);
54
62
  }
55
63
  });
64
+ app.post("/api/workspaces/clone", async (request, reply) => {
65
+ try {
66
+ const body = WorkspaceCloneSchema.parse(request.body ?? {});
67
+ const result = await cloneGitRepository(body);
68
+ reply.code(201);
69
+ return result;
70
+ }
71
+ catch (error) {
72
+ return handleWorkspaceError(error, reply);
73
+ }
74
+ });
56
75
  app.get("/api/workspaces/:id", async (request, reply) => {
57
76
  const workspace = deps.workspaceManager.get(request.params.id);
58
77
  if (!workspace) {
@@ -90,7 +109,13 @@ export function registerWorkspaceRoutes(app, deps) {
90
109
  app.get("/api/workspaces/:id/files/content", async (request, reply) => {
91
110
  try {
92
111
  const query = WorkspaceFileContentQuerySchema.parse(request.query ?? {});
93
- return deps.workspaceManager.readFile(request.params.id, query.path);
112
+ if (query.worktree && query.worktree !== "root") {
113
+ const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, query.worktree, request.log, reply);
114
+ if (!directory)
115
+ return;
116
+ return deps.workspaceManager.readFileInDirectory(request.params.id, directory, query.path, { encoding: query.encoding });
117
+ }
118
+ return deps.workspaceManager.readFile(request.params.id, query.path, { encoding: query.encoding });
94
119
  }
95
120
  catch (error) {
96
121
  return handleWorkspaceError(error, reply);
@@ -100,6 +125,14 @@ export function registerWorkspaceRoutes(app, deps) {
100
125
  try {
101
126
  const query = WorkspaceFileContentQuerySchema.parse(request.query ?? {});
102
127
  const body = WorkspaceFileContentBodySchema.parse(request.body ?? {});
128
+ if (query.worktree && query.worktree !== "root") {
129
+ const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, query.worktree, request.log, reply);
130
+ if (!directory)
131
+ return;
132
+ deps.workspaceManager.writeFileInDirectory(request.params.id, directory, query.path, body.contents);
133
+ reply.code(204);
134
+ return;
135
+ }
103
136
  deps.workspaceManager.writeFile(request.params.id, query.path, body.contents);
104
137
  reply.code(204);
105
138
  }
@@ -208,6 +241,10 @@ async function resolveGitWorktreeDirectory(workspaceManager, workspaceId, worktr
208
241
  return directory;
209
242
  }
210
243
  function handleWorkspaceError(error, reply) {
244
+ if (isGitCloneError(error)) {
245
+ reply.code(error.statusCode);
246
+ return { error: error.message };
247
+ }
211
248
  if (isGitMutationError(error)) {
212
249
  reply.code(error.statusCode);
213
250
  return { error: error.message };
@@ -0,0 +1,142 @@
1
+ import assert from "node:assert/strict";
2
+ import { execFileSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { homedir, tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { describe, it } from "node:test";
7
+ import { cloneGitRepository } from "../git-clone";
8
+ function createBareRepository(repoPath) {
9
+ execFileSync("git", ["init", "--bare", repoPath], { stdio: "ignore" });
10
+ }
11
+ async function expectCloneError(callback, expectedStatusCode, messagePattern) {
12
+ await assert.rejects(callback, (error) => {
13
+ assert.equal(typeof error, "object");
14
+ assert.equal(error.statusCode, expectedStatusCode);
15
+ assert.match(String(error.message ?? ""), messagePattern);
16
+ return true;
17
+ });
18
+ }
19
+ describe("cloneGitRepository", () => {
20
+ it("clones into a missing destination", async () => {
21
+ const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-clone-"));
22
+ const sourceRepo = path.join(temp, "source.git");
23
+ const destinationPath = path.join(temp, "cloned-repo");
24
+ try {
25
+ createBareRepository(sourceRepo);
26
+ const result = await cloneGitRepository({
27
+ repositoryUrl: sourceRepo,
28
+ destinationPath,
29
+ });
30
+ assert.equal(result.path, destinationPath);
31
+ assert.equal(existsSync(path.join(destinationPath, ".git")), true);
32
+ }
33
+ finally {
34
+ rmSync(temp, { recursive: true, force: true });
35
+ }
36
+ });
37
+ it("rejects non-empty destinations when cleanup is not enabled", async () => {
38
+ const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-clone-"));
39
+ const sourceRepo = path.join(temp, "source.git");
40
+ const destinationPath = path.join(temp, "existing-destination");
41
+ const sentinelPath = path.join(destinationPath, "keep.txt");
42
+ try {
43
+ createBareRepository(sourceRepo);
44
+ mkdirSync(destinationPath, { recursive: true });
45
+ writeFileSync(sentinelPath, "keep");
46
+ await expectCloneError(() => cloneGitRepository({ repositoryUrl: sourceRepo, destinationPath }), 409, /Destination folder is not empty/);
47
+ assert.equal(readFileSync(sentinelPath, "utf8"), "keep");
48
+ }
49
+ finally {
50
+ rmSync(temp, { recursive: true, force: true });
51
+ }
52
+ });
53
+ it("preserves the existing destination when cleanup is enabled but clone fails", async () => {
54
+ const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-clone-"));
55
+ const missingRepo = path.join(temp, "missing.git");
56
+ const destinationPath = path.join(temp, "existing-destination");
57
+ const sentinelPath = path.join(destinationPath, "keep.txt");
58
+ try {
59
+ mkdirSync(destinationPath, { recursive: true });
60
+ writeFileSync(sentinelPath, "keep");
61
+ await expectCloneError(() => cloneGitRepository({ repositoryUrl: missingRepo, destinationPath, cleanup: true }), 409, /does not appear to be a git repository|does not exist|not found/i);
62
+ assert.equal(readFileSync(sentinelPath, "utf8"), "keep");
63
+ assert.equal(existsSync(destinationPath), true);
64
+ }
65
+ finally {
66
+ rmSync(temp, { recursive: true, force: true });
67
+ }
68
+ });
69
+ it("replaces the existing destination only after a successful cleanup clone", async () => {
70
+ const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-clone-"));
71
+ const sourceRepo = path.join(temp, "source.git");
72
+ const destinationPath = path.join(temp, "existing-destination");
73
+ const sentinelPath = path.join(destinationPath, "keep.txt");
74
+ try {
75
+ createBareRepository(sourceRepo);
76
+ mkdirSync(destinationPath, { recursive: true });
77
+ writeFileSync(sentinelPath, "keep");
78
+ const result = await cloneGitRepository({
79
+ repositoryUrl: sourceRepo,
80
+ destinationPath,
81
+ cleanup: true,
82
+ });
83
+ assert.equal(result.path, destinationPath);
84
+ assert.equal(existsSync(path.join(destinationPath, ".git")), true);
85
+ assert.equal(existsSync(sentinelPath), false);
86
+ }
87
+ finally {
88
+ rmSync(temp, { recursive: true, force: true });
89
+ }
90
+ });
91
+ it("rejects filesystem root destinations", async () => {
92
+ const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-clone-"));
93
+ const sourceRepo = path.join(temp, "source.git");
94
+ try {
95
+ createBareRepository(sourceRepo);
96
+ await expectCloneError(() => cloneGitRepository({
97
+ repositoryUrl: sourceRepo,
98
+ destinationPath: path.parse(process.cwd()).root,
99
+ cleanup: true,
100
+ }), 400, /filesystem root/);
101
+ }
102
+ finally {
103
+ rmSync(temp, { recursive: true, force: true });
104
+ }
105
+ });
106
+ it("rejects home directory destinations", async () => {
107
+ const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-clone-"));
108
+ const sourceRepo = path.join(temp, "source.git");
109
+ try {
110
+ createBareRepository(sourceRepo);
111
+ await expectCloneError(() => cloneGitRepository({
112
+ repositoryUrl: sourceRepo,
113
+ destinationPath: homedir(),
114
+ cleanup: true,
115
+ }), 400, /home folder/);
116
+ }
117
+ finally {
118
+ rmSync(temp, { recursive: true, force: true });
119
+ }
120
+ });
121
+ it("supports destinations directly under a safe parent", async () => {
122
+ const temp = mkdtempSync(path.join(tmpdir(), "codenomad-git-clone-"));
123
+ const sourceRepo = path.join(temp, "source.git");
124
+ const root = path.parse(process.cwd()).root;
125
+ const parentPath = process.platform === "win32" ? root : temp;
126
+ const destinationPath = path.join(parentPath, `codenomad-git-clone-root-${Date.now()}-${Math.random().toString(36).slice(2)}`);
127
+ try {
128
+ createBareRepository(sourceRepo);
129
+ rmSync(destinationPath, { recursive: true, force: true });
130
+ const result = await cloneGitRepository({
131
+ repositoryUrl: sourceRepo,
132
+ destinationPath,
133
+ });
134
+ assert.equal(result.path, destinationPath);
135
+ assert.equal(existsSync(destinationPath), true);
136
+ }
137
+ finally {
138
+ rmSync(destinationPath, { recursive: true, force: true });
139
+ rmSync(temp, { recursive: true, force: true });
140
+ }
141
+ });
142
+ });
@@ -34,12 +34,12 @@ describe("buildWindowsSpawnSpec", () => {
34
34
  const spec = buildWindowsSpawnSpec(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`, ["serve", "--port", "0"], {
35
35
  cwd: String.raw `\\wsl.localhost\Ubuntu\home\dev\workspace`,
36
36
  env: {
37
- OPENCODE_CONFIG_DIR: String.raw `C:\Users\dev\AppData\Roaming\CodeNomad\opencode-config`,
37
+ OPENCODE_CONFIG_CONTENT: JSON.stringify({ plugin: ["file:///C:/Users/dev/AppData/Roaming/CodeNomad/plugin.tgz"] }),
38
38
  CODENOMAD_INSTANCE_ID: "workspace-123",
39
- OPENCODE_SERVER_BASE_URL: "https://127.0.0.1:4321/workspaces/workspace-123/worktrees/root/instance",
39
+ OPENCODE_SERVER_BASE_URL: "https://127.0.0.1:4321/workspaces/workspace-123/instance",
40
40
  OPENCODE_SERVER_PASSWORD: "secret",
41
41
  },
42
- propagateEnvKeys: ["OPENCODE_CONFIG_DIR", "CODENOMAD_INSTANCE_ID", "OPENCODE_SERVER_BASE_URL", "OPENCODE_SERVER_PASSWORD"],
42
+ propagateEnvKeys: ["OPENCODE_CONFIG_CONTENT", "CODENOMAD_INSTANCE_ID", "OPENCODE_SERVER_BASE_URL", "OPENCODE_SERVER_PASSWORD"],
43
43
  });
44
44
  assert.equal(spec.command, "wsl.exe");
45
45
  assert.deepEqual(spec.args, [
@@ -54,17 +54,35 @@ describe("buildWindowsSpawnSpec", () => {
54
54
  "0",
55
55
  ]);
56
56
  assert.equal(spec.cwd, undefined);
57
- assert.equal(spec.env?.WSLENV, "OPENCODE_CONFIG_DIR/p:CODENOMAD_INSTANCE_ID:OPENCODE_SERVER_BASE_URL:OPENCODE_SERVER_PASSWORD");
57
+ assert.equal(spec.env?.WSLENV, "OPENCODE_CONFIG_CONTENT:CODENOMAD_INSTANCE_ID:OPENCODE_SERVER_BASE_URL:OPENCODE_SERVER_PASSWORD");
58
58
  });
59
- it("upgrades existing WSLENV path entries to include /p", () => {
59
+ it("preserves non-path OPENCODE_CONFIG_CONTENT WSLENV entries", () => {
60
60
  const spec = buildWindowsSpawnSpec(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`, ["serve"], {
61
61
  env: {
62
- OPENCODE_CONFIG_DIR: String.raw `C:\Users\dev\AppData\Roaming\CodeNomad\opencode-config`,
63
- WSLENV: "OPENCODE_CONFIG_DIR:CODENOMAD_INSTANCE_ID/u",
62
+ OPENCODE_CONFIG_CONTENT: JSON.stringify({ plugin: ["file:///C:/Users/dev/AppData/Roaming/CodeNomad/plugin.tgz"] }),
63
+ WSLENV: "OPENCODE_CONFIG_CONTENT:CODENOMAD_INSTANCE_ID/u",
64
64
  },
65
- propagateEnvKeys: ["OPENCODE_CONFIG_DIR", "CODENOMAD_INSTANCE_ID"],
65
+ propagateEnvKeys: ["OPENCODE_CONFIG_CONTENT", "CODENOMAD_INSTANCE_ID"],
66
66
  });
67
- assert.equal(spec.env?.WSLENV, "OPENCODE_CONFIG_DIR/p:CODENOMAD_INSTANCE_ID/u");
67
+ assert.equal(spec.env?.WSLENV, "OPENCODE_CONFIG_CONTENT:CODENOMAD_INSTANCE_ID/u");
68
+ });
69
+ it("rewrites packaged plugin paths for WSL before launching", () => {
70
+ const spec = buildWindowsSpawnSpec(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`, ["serve"], {
71
+ env: {
72
+ OPENCODE_CONFIG_CONTENT: JSON.stringify({
73
+ plugin: [
74
+ "@codenomad/codenomad-opencode-plugin@file:C:/Users/dev/AppData/Roaming/CodeNomad/codenomad-opencode-plugin.tgz",
75
+ ],
76
+ }),
77
+ },
78
+ propagateEnvKeys: ["OPENCODE_CONFIG_CONTENT"],
79
+ });
80
+ assert.equal(spec.command, "wsl.exe");
81
+ assert.equal(spec.env?.CODENOMAD_OPENCODE_PLUGIN_WSL_PATH, String.raw `C:\Users\dev\AppData\Roaming\CodeNomad\codenomad-opencode-plugin.tgz`);
82
+ assert.match(spec.env?.OPENCODE_CONFIG_CONTENT ?? "", /__CODENOMAD_OPENCODE_PLUGIN_WSL_PATH__/);
83
+ assert.equal(spec.env?.WSLENV, "OPENCODE_CONFIG_CONTENT:CODENOMAD_OPENCODE_PLUGIN_WSL_PATH/p");
84
+ assert.deepEqual(spec.args.slice(0, 4), ["--distribution", "Ubuntu", "--exec", "sh"]);
85
+ assert.match(spec.args[5] ?? "", /CODENOMAD_OPENCODE_PLUGIN_WSL_PATH/);
68
86
  });
69
87
  it("propagates inherited known path variables even when they are not explicitly requested", () => {
70
88
  const spec = buildWindowsSpawnSpec(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`, ["serve"], {