@acryldev/workspace 0.0.0-stage → 0.2.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 (229) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +61 -2
  3. package/cordis.patch.yml +3 -0
  4. package/lib/agents/argument-text.d.ts +9 -0
  5. package/lib/agents/catalog.d.ts +32 -0
  6. package/lib/agents/contract.d.ts +50 -0
  7. package/lib/agents/definition.d.ts +38 -0
  8. package/lib/agents/file-store.d.ts +7 -0
  9. package/lib/agents/known-agents.d.ts +52 -0
  10. package/lib/agents/launch.d.ts +26 -0
  11. package/lib/agents/preferences.d.ts +40 -0
  12. package/lib/agents/route.d.ts +10 -0
  13. package/lib/agents/settings.d.ts +28 -0
  14. package/lib/agents/status/agent-status.d.ts +38 -0
  15. package/lib/agents/status/claude-hooks.d.ts +18 -0
  16. package/lib/agents/status/route.d.ts +10 -0
  17. package/lib/capabilities/contract.d.ts +17 -0
  18. package/lib/capabilities/route.d.ts +8 -0
  19. package/lib/client.js +91109 -0
  20. package/lib/client.js.map +1 -0
  21. package/lib/files/contract.d.ts +74 -0
  22. package/lib/files/route.d.ts +9 -0
  23. package/lib/files/service.d.ts +48 -0
  24. package/lib/folder-picker/contract.d.ts +9 -0
  25. package/lib/folder-picker/picker.d.ts +23 -0
  26. package/lib/folder-picker/route.d.ts +5 -0
  27. package/lib/git/changes.d.ts +29 -0
  28. package/lib/git/checks.d.ts +8 -0
  29. package/lib/git/commits.d.ts +14 -0
  30. package/lib/git/contract.d.ts +136 -0
  31. package/lib/git/errors.d.ts +9 -0
  32. package/lib/git/guards.d.ts +9 -0
  33. package/lib/git/ignored.d.ts +9 -0
  34. package/lib/git/parsing.d.ts +13 -0
  35. package/lib/git/route.d.ts +9 -0
  36. package/lib/git/runner.d.ts +29 -0
  37. package/lib/git/search.d.ts +14 -0
  38. package/lib/git/service.d.ts +52 -0
  39. package/lib/git/worktrees.d.ts +26 -0
  40. package/lib/index.d.ts +39 -0
  41. package/lib/index.js +3799 -0
  42. package/lib/index.js.map +1 -0
  43. package/lib/private-route.d.ts +15 -0
  44. package/lib/projects/contract.d.ts +82 -0
  45. package/lib/projects/registry.d.ts +73 -0
  46. package/lib/projects/route.d.ts +16 -0
  47. package/lib/projects/tools.d.ts +24 -0
  48. package/lib/pty/contract.d.ts +52 -0
  49. package/lib/pty/node-pty-spawn.d.ts +3 -0
  50. package/lib/pty/route.d.ts +9 -0
  51. package/lib/pty/screen-model.d.ts +25 -0
  52. package/lib/pty/scrollback.d.ts +26 -0
  53. package/lib/pty/service.d.ts +156 -0
  54. package/lib/pty/stream.d.ts +19 -0
  55. package/lib/shared-context/chat.d.ts +34 -0
  56. package/lib/shared-context/launch.d.ts +24 -0
  57. package/lib/shared-context/render.d.ts +29 -0
  58. package/lib/shared-context/route.d.ts +13 -0
  59. package/lib/shared-context/service.d.ts +65 -0
  60. package/lib/shared-context/tool.d.ts +20 -0
  61. package/lib/types/agents/argument-text.d.ts +9 -0
  62. package/lib/types/agents/contract.d.ts +50 -0
  63. package/lib/types/agents/definition.d.ts +38 -0
  64. package/lib/types/agents/known-agents.d.ts +52 -0
  65. package/lib/types/agents/launch.d.ts +26 -0
  66. package/lib/types/agents/preferences.d.ts +40 -0
  67. package/lib/types/agents/status/agent-status.d.ts +38 -0
  68. package/lib/types/capabilities/contract.d.ts +17 -0
  69. package/lib/types/client/agents/AddAgentForm.d.ts +10 -0
  70. package/lib/types/client/agents/AgentRow.d.ts +11 -0
  71. package/lib/types/client/agents/AgentsSection.d.ts +14 -0
  72. package/lib/types/client/agents/acryl-logo-data.d.ts +3 -0
  73. package/lib/types/client/agents/agent-draft.d.ts +24 -0
  74. package/lib/types/client/agents/agents-api.d.ts +18 -0
  75. package/lib/types/client/agents/agents-section-model.d.ts +45 -0
  76. package/lib/types/client/agents/agents-settings-plugin.d.ts +8 -0
  77. package/lib/types/client/agents/agents-state.d.ts +26 -0
  78. package/lib/types/client/agents/controls.d.ts +40 -0
  79. package/lib/types/client/board/NoteColumn.d.ts +17 -0
  80. package/lib/types/client/board/SessionBoardPane.d.ts +16 -0
  81. package/lib/types/client/board/board-model.d.ts +36 -0
  82. package/lib/types/client/browser/BrowserPane.d.ts +28 -0
  83. package/lib/types/client/canvas/SplitDivider.d.ts +9 -0
  84. package/lib/types/client/canvas/WorkspaceCanvas.d.ts +78 -0
  85. package/lib/types/client/canvas/groups.d.ts +47 -0
  86. package/lib/types/client/canvas/persist.d.ts +17 -0
  87. package/lib/types/client/canvas/persistence.d.ts +78 -0
  88. package/lib/types/client/canvas/shell-requests.d.ts +16 -0
  89. package/lib/types/client/canvas/split-ratio.d.ts +12 -0
  90. package/lib/types/client/canvas/state.d.ts +181 -0
  91. package/lib/types/client/canvas/tab-title.d.ts +7 -0
  92. package/lib/types/client/capabilities/capabilities-api.d.ts +8 -0
  93. package/lib/types/client/changes/ChangesBody.d.ts +14 -0
  94. package/lib/types/client/changes/changes-tab.d.ts +20 -0
  95. package/lib/types/client/chat/chat-selection.d.ts +70 -0
  96. package/lib/types/client/chat/composer-focus.d.ts +16 -0
  97. package/lib/types/client/checks/ChecksBody.d.ts +9 -0
  98. package/lib/types/client/checks/checks-tab.d.ts +12 -0
  99. package/lib/types/client/chrome/StatusLine.d.ts +11 -0
  100. package/lib/types/client/chrome/panel-icons.d.ts +16 -0
  101. package/lib/types/client/chrome/status-line.d.ts +19 -0
  102. package/lib/types/client/chrome/worktree-agents.d.ts +13 -0
  103. package/lib/types/client/comments/CommentsBody.d.ts +24 -0
  104. package/lib/types/client/comments/comment-store.d.ts +38 -0
  105. package/lib/types/client/comments/comments-tab.d.ts +14 -0
  106. package/lib/types/client/comments/editor-comments.d.ts +6 -0
  107. package/lib/types/client/comments/terminal-targets.d.ts +35 -0
  108. package/lib/types/client/comments/use-comments.d.ts +27 -0
  109. package/lib/types/client/connection/session-banner.d.ts +51 -0
  110. package/lib/types/client/diff/GitDiffPane.d.ts +27 -0
  111. package/lib/types/client/diff/TextDiffPane.d.ts +6 -0
  112. package/lib/types/client/diff/comment-message.d.ts +29 -0
  113. package/lib/types/client/diff/diff-layout.d.ts +4 -0
  114. package/lib/types/client/diff/line-diff.d.ts +14 -0
  115. package/lib/types/client/diff/unified-diff.d.ts +31 -0
  116. package/lib/types/client/dock/DockButtons.d.ts +19 -0
  117. package/lib/types/client/dock/DockColumns.d.ts +21 -0
  118. package/lib/types/client/dock/DockDivider.d.ts +13 -0
  119. package/lib/types/client/dock/TerminalDockPanel.d.ts +13 -0
  120. package/lib/types/client/dock/dock-controller.d.ts +55 -0
  121. package/lib/types/client/dock/dock-hooks.d.ts +6 -0
  122. package/lib/types/client/dock/dock-host.d.ts +14 -0
  123. package/lib/types/client/dock/dock-icons.d.ts +10 -0
  124. package/lib/types/client/dock/dock-model.d.ts +35 -0
  125. package/lib/types/client/dock/dock-tabs.d.ts +72 -0
  126. package/lib/types/client/dock/terminal-stack.d.ts +19 -0
  127. package/lib/types/client/docs/DocFilePane.d.ts +12 -0
  128. package/lib/types/client/docs/DocPane.d.ts +6 -0
  129. package/lib/types/client/docs/DocView.d.ts +5 -0
  130. package/lib/types/client/docs/doc-format.d.ts +46 -0
  131. package/lib/types/client/dom/find-by-name.d.ts +18 -0
  132. package/lib/types/client/files/CodeEditor.d.ts +19 -0
  133. package/lib/types/client/files/FileBreadcrumbs.d.ts +15 -0
  134. package/lib/types/client/files/FileEditorPane.d.ts +12 -0
  135. package/lib/types/client/files/FileTree.d.ts +25 -0
  136. package/lib/types/client/files/FilesBody.d.ts +14 -0
  137. package/lib/types/client/files/ScratchFilePane.d.ts +6 -0
  138. package/lib/types/client/files/breadcrumbs.d.ts +18 -0
  139. package/lib/types/client/files/file-edit.d.ts +20 -0
  140. package/lib/types/client/files/file-icons.d.ts +17 -0
  141. package/lib/types/client/files/files-api.d.ts +26 -0
  142. package/lib/types/client/files/files-tab.d.ts +25 -0
  143. package/lib/types/client/files/line-comment.d.ts +26 -0
  144. package/lib/types/client/files/line-comments.d.ts +48 -0
  145. package/lib/types/client/files/tree-model.d.ts +60 -0
  146. package/lib/types/client/git/git-api.d.ts +35 -0
  147. package/lib/types/client/index.d.ts +28 -0
  148. package/lib/types/client/models/ModelConnect.d.ts +13 -0
  149. package/lib/types/client/models/model-connect.d.ts +145 -0
  150. package/lib/types/client/notifications/Toasts.d.ts +6 -0
  151. package/lib/types/client/notifications/system-notice.d.ts +19 -0
  152. package/lib/types/client/notifications/toast-state.d.ts +29 -0
  153. package/lib/types/client/palette/CommandPalette.d.ts +9 -0
  154. package/lib/types/client/palette/PalettePanel.d.ts +10 -0
  155. package/lib/types/client/palette/file-search.d.ts +9 -0
  156. package/lib/types/client/palette/fuzzy.d.ts +15 -0
  157. package/lib/types/client/palette/palette-commands.d.ts +64 -0
  158. package/lib/types/client/palette/palette-config.d.ts +21 -0
  159. package/lib/types/client/palette/palette-items.d.ts +40 -0
  160. package/lib/types/client/palette/palette-settings-plugin.d.ts +8 -0
  161. package/lib/types/client/palette/palette-shortcut.d.ts +10 -0
  162. package/lib/types/client/palette/palette-state.d.ts +68 -0
  163. package/lib/types/client/palette/use-workspace-palette.d.ts +39 -0
  164. package/lib/types/client/projects/NewWorkspaceDialog.d.ts +21 -0
  165. package/lib/types/client/projects/ProjectsSidebar.d.ts +39 -0
  166. package/lib/types/client/projects/RepoSection.d.ts +29 -0
  167. package/lib/types/client/projects/WorkspaceStrip.d.ts +14 -0
  168. package/lib/types/client/projects/projects-control.d.ts +119 -0
  169. package/lib/types/client/projects/registry-api.d.ts +22 -0
  170. package/lib/types/client/projects/registry-state.d.ts +67 -0
  171. package/lib/types/client/projects/shown-workspace.d.ts +19 -0
  172. package/lib/types/client/projects/sidebar-model.d.ts +113 -0
  173. package/lib/types/client/projects/upstream-panels.d.ts +54 -0
  174. package/lib/types/client/projects/web-folder-picker.d.ts +13 -0
  175. package/lib/types/client/review/ReviewBody.d.ts +9 -0
  176. package/lib/types/client/review/review-store.d.ts +46 -0
  177. package/lib/types/client/review/review-tab.d.ts +15 -0
  178. package/lib/types/client/sessions/agent-bridge.d.ts +20 -0
  179. package/lib/types/client/sessions/main-session.d.ts +24 -0
  180. package/lib/types/client/sessions/running-agents.d.ts +9 -0
  181. package/lib/types/client/sessions/session-client.d.ts +22 -0
  182. package/lib/types/client/sessions/session-navigation.d.ts +63 -0
  183. package/lib/types/client/sessions/session-pick.d.ts +15 -0
  184. package/lib/types/client/settings/locales.d.ts +5 -0
  185. package/lib/types/client/settings/open-settings.d.ts +37 -0
  186. package/lib/types/client/settings/section-plugin.d.ts +39 -0
  187. package/lib/types/client/settings/styles.d.ts +3 -0
  188. package/lib/types/client/shared-context/BriefTab.d.ts +21 -0
  189. package/lib/types/client/shared-context/brief-api.d.ts +9 -0
  190. package/lib/types/client/status/agent-status-api.d.ts +10 -0
  191. package/lib/types/client/status/agent-status-state.d.ts +27 -0
  192. package/lib/types/client/status/attention-model.d.ts +20 -0
  193. package/lib/types/client/styles.d.ts +2 -0
  194. package/lib/types/client/tabs/AgentIcon.d.ts +12 -0
  195. package/lib/types/client/tabs/NewTabMenu.d.ts +42 -0
  196. package/lib/types/client/tabs/TabActivity.d.ts +7 -0
  197. package/lib/types/client/tabs/TabStrip.d.ts +53 -0
  198. package/lib/types/client/tabs/TabsPanel.d.ts +14 -0
  199. package/lib/types/client/tabs/agent-marks.d.ts +9 -0
  200. package/lib/types/client/tabs/agent-visibility.d.ts +11 -0
  201. package/lib/types/client/tabs/last-tab.d.ts +15 -0
  202. package/lib/types/client/tabs/registry/CustomTabPane.d.ts +13 -0
  203. package/lib/types/client/tabs/registry/provide.d.ts +11 -0
  204. package/lib/types/client/tabs/registry/tab-registry.d.ts +52 -0
  205. package/lib/types/client/tabs/tab-close.d.ts +4 -0
  206. package/lib/types/client/tabs/tab-scroll.d.ts +19 -0
  207. package/lib/types/client/tabs/tab-types-state.d.ts +24 -0
  208. package/lib/types/client/tabs/tabs-settings-plugin.d.ts +9 -0
  209. package/lib/types/client/terminal/PtyPane.d.ts +8 -0
  210. package/lib/types/client/terminal/TerminalSearchBar.d.ts +7 -0
  211. package/lib/types/client/terminal/agent-commands.d.ts +15 -0
  212. package/lib/types/client/terminal/gpu-renderer.d.ts +10 -0
  213. package/lib/types/client/terminal/pty-api.d.ts +21 -0
  214. package/lib/types/client/terminal/pty-stream.d.ts +46 -0
  215. package/lib/types/client/terminal/terminal-links.d.ts +9 -0
  216. package/lib/types/client/terminal/terminal-search.d.ts +18 -0
  217. package/lib/types/client/terminal/terminal-session.d.ts +105 -0
  218. package/lib/types/client/terminal/terminal-size.d.ts +7 -0
  219. package/lib/types/client/ui.d.ts +18 -0
  220. package/lib/types/client/worktrees/shell-polling.d.ts +10 -0
  221. package/lib/types/client/worktrees/shell-state.d.ts +200 -0
  222. package/lib/types/files/contract.d.ts +74 -0
  223. package/lib/types/folder-picker/contract.d.ts +9 -0
  224. package/lib/types/git/contract.d.ts +136 -0
  225. package/lib/types/projects/contract.d.ts +82 -0
  226. package/lib/types/pty/contract.d.ts +52 -0
  227. package/lib/ui.js +12735 -0
  228. package/lib/ui.js.map +1 -0
  229. package/package.json +145 -3
package/lib/index.js ADDED
@@ -0,0 +1,3799 @@
1
+ import { randomBytes, randomUUID } from "node:crypto";
2
+ import { basename, dirname, isAbsolute, join, normalize, resolve, sep } from "node:path";
3
+ import { Acryl } from "@acryldev/blends";
4
+ import { INVALID_JSON, jsonBody, ownPage, ownPageSocket, privateApi, readJson } from "@acryldev/loopback-http/router";
5
+ import { chmod, lstat, mkdir, readFile, readdir, realpath, rename, rmdir, stat, unlink, writeFile } from "node:fs/promises";
6
+ import { bearerAuth } from "@acryldev/blends/bearer-auth";
7
+ import { loopbackOnly } from "@acryldev/blends/loopback-only";
8
+ import { execFile, spawn } from "node:child_process";
9
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
10
+ import z from "@deepseek-ai/schemastery";
11
+ import { streamSSE } from "@acryldev/blends/streaming";
12
+ import { defineAcrylTool } from "@acryldev/control";
13
+ import { spawn as spawn$1 } from "node-pty";
14
+ import { homedir } from "node:os";
15
+ import serializeModule from "@xterm/addon-serialize";
16
+ import headlessModule from "@xterm/headless";
17
+ import { bodyLimit } from "@acryldev/blends/body-limit";
18
+ //#region src/private-route.ts
19
+ /** Every workspace route lives below this path; it is the one prefix the plugin mounts on the Web server. */
20
+ const WORKSPACE_API_PREFIX = "/api/acryl-workspace";
21
+ /** The workspace's routes as one app, the shared rules scoped to {@link WORKSPACE_API_PREFIX}. */
22
+ function privateApi$1(...routes) {
23
+ return privateApi(WORKSPACE_API_PREFIX, ...routes);
24
+ }
25
+ function failure(message) {
26
+ return { error: message };
27
+ }
28
+ function isRecord$5(value) {
29
+ return value !== null && typeof value === "object" && !Array.isArray(value);
30
+ }
31
+ //#endregion
32
+ //#region src/agents/known-agents.ts
33
+ const agent = (id, label, command, homepageUrl, color, yoloArgs = [], yoloEnv) => ({
34
+ id,
35
+ label,
36
+ command,
37
+ homepageUrl,
38
+ yoloArgs,
39
+ ...yoloEnv === void 0 ? {} : { yoloEnv },
40
+ badge: {
41
+ letter: [...label][0]?.toUpperCase() ?? "?",
42
+ color
43
+ }
44
+ });
45
+ /** In the order the lists show them. Ids of agents that shipped earlier keep their spelling. */
46
+ const KNOWN_AGENTS = [
47
+ {
48
+ ...agent("claude", "Claude", "claude", "https://code.claude.com/docs", "#d97757", ["--dangerously-skip-permissions"]),
49
+ statusHooks: "claude"
50
+ },
51
+ agent("codex", "Codex", "codex", "https://github.com/openai/codex", "#10a37f", ["--dangerously-bypass-approvals-and-sandbox"]),
52
+ agent("grok", "Grok", "grok", "https://x.ai/cli", "#94a3b8", ["--permission-mode", "bypassPermissions"]),
53
+ agent("copilot", "GitHub Copilot", "copilot", "https://docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli", "#a78bfa", ["--yolo"]),
54
+ agent("opencode", "OpenCode", "opencode", "https://opencode.ai/docs/cli/", "#94a3b8"),
55
+ agent("ante", "Ante", "ante", "https://github.com/AntigmaLabs/ante-preview", "#fb923c", ["--yolo"]),
56
+ agent("pi", "Pi", "pi", "https://pi.dev", "#a78bfa"),
57
+ agent("omp", "OMP", "omp", "https://omp.sh", "#a78bfa"),
58
+ agent("gemini", "Gemini", "gemini", "https://github.com/google-gemini/gemini-cli", "#4285f4", ["--yolo"]),
59
+ agent("antigravity", "Antigravity", "agy", "https://antigravity.google/docs/cli-overview", "#4285f4", ["--dangerously-skip-permissions"]),
60
+ agent("aider", "Aider", "aider", "https://aider.chat/docs/", "#34d399", ["--yes-always"]),
61
+ agent("goose", "Goose", "goose", "https://block.github.io/goose/docs/quickstart/", "#f59e0b", [], { GOOSE_MODE: "auto" }),
62
+ agent("amp", "Amp", "amp", "https://ampcode.com/manual#install", "#ef4444", ["--dangerously-allow-all"]),
63
+ agent("kilo", "Kilocode", "kilo", "https://kilo.ai/docs/cli", "#f59e0b"),
64
+ agent("crush", "Charm", "crush", "https://github.com/charmbracelet/crush", "#a78bfa", ["--yolo"]),
65
+ agent("command-code", "Command Code", "command-code", "https://commandcode.ai/docs/quickstart", "#94a3b8", ["--yolo"]),
66
+ agent("cursor", "Cursor", "cursor-agent", "https://cursor.com/cli", "#94a3b8", ["--yolo"]),
67
+ agent("droid", "Droid", "droid", "https://docs.factory.ai/cli/getting-started/quickstart", "#94a3b8", ["--auto", "high"]),
68
+ agent("kimi", "Kimi", "kimi", "https://www.kimi.com/code/docs/en/kimi-code-cli/getting-started.html", "#38bdf8", ["--yolo"]),
69
+ agent("mistral-vibe", "Mistral Vibe", "vibe", "https://github.com/mistralai/mistral-vibe", "#fb923c", ["--agent", "auto-approve"]),
70
+ agent("qwen", "Qwen Code", "qwen", "https://github.com/QwenLM/qwen-code", "#a78bfa", ["--approval-mode", "yolo"]),
71
+ agent("hermes", "Hermes", "hermes", "https://hermes-agent.nousresearch.com/docs/", "#94a3b8", ["--yolo"]),
72
+ agent("mimo-code", "MiMo Code", "mimo", "https://mimo.xiaomi.com/coder", "#94a3b8"),
73
+ agent("trae", "Trae", "traecli", "https://docs.trae.cn/cli_get-started-with-trae-cli", "#34d399", ["--yolo"]),
74
+ agent("kiro", "Kiro", "kiro-cli", "https://kiro.dev/docs/cli/", "#a78bfa", ["--trust-all-tools"]),
75
+ agent("aug", "Auggie", "auggie", "https://docs.augmentcode.com/cli/overview", "#94a3b8"),
76
+ agent("autohand", "Autohand Code", "autohand", "https://github.com/autohandai/code-cli", "#94a3b8", ["--unrestricted"]),
77
+ agent("cline", "Cline", "cline", "https://docs.cline.bot/cline-cli/overview", "#94a3b8", ["--auto-approve", "true"]),
78
+ agent("codebuff", "Codebuff", "codebuff", "https://www.codebuff.com/docs/help/quick-start", "#94a3b8"),
79
+ agent("continue", "Continue", "cn", "https://docs.continue.dev/guides/cli", "#94a3b8", ["--allow", "*"]),
80
+ agent("rovo", "Rovo Dev", "rovo", "https://support.atlassian.com/rovo/docs/install-and-run-rovo-dev-cli-on-your-device/", "#4285f4", ["--yolo"]),
81
+ agent("devin", "Devin", "devin", "https://devin.ai/cli", "#34d399", [
82
+ "--permission-mode",
83
+ "bypass",
84
+ "--respect-workspace-trust",
85
+ "false"
86
+ ]),
87
+ agent("openclaw", "OpenClaw", "openclaw", "https://github.com/openclaw/openclaw", "#ef4444")
88
+ ];
89
+ const KNOWN_AGENT_IDS = KNOWN_AGENTS.map((entry) => entry.id);
90
+ const BY_ID = new Map(KNOWN_AGENTS.map((entry) => [entry.id, entry]));
91
+ /** @returns the known agent with this id, or undefined (a custom agent, the terminal, or nothing). */
92
+ function knownAgent(id) {
93
+ return BY_ID.get(id);
94
+ }
95
+ //#endregion
96
+ //#region src/pty/contract.ts
97
+ /** Allowlisted ACRYL Workspace PTY commands and loopback routes. */
98
+ /** The terminal, then every agent ACRYL knows by name (`agents/known-agents.ts` owns that list). */
99
+ const WORKSPACE_PTY_COMMAND_IDS = ["shell", ...KNOWN_AGENT_IDS];
100
+ const WORKSPACE_PTY_PATH = "/api/acryl-workspace/pty";
101
+ const WORKSPACE_PTY_INPUT_PATH = "/api/acryl-workspace/pty/input";
102
+ const WORKSPACE_PTY_RESIZE_PATH = "/api/acryl-workspace/pty/resize";
103
+ const WORKSPACE_PTY_CLOSE_PATH = "/api/acryl-workspace/pty/close";
104
+ /** WebSocket: live output down, keystrokes and size up, in order. Query: `id`, `since` (cursor already shown). */
105
+ const WORKSPACE_PTY_STREAM_PATH = "/api/acryl-workspace/pty/stream";
106
+ const COMMAND_IDS = new Set(WORKSPACE_PTY_COMMAND_IDS);
107
+ /** @param value - unknown command id from JSON. */
108
+ function isWorkspacePtyCommandId(value) {
109
+ return typeof value === "string" && COMMAND_IDS.has(value);
110
+ }
111
+ function isRecord$4(value) {
112
+ return value !== null && typeof value === "object" && !Array.isArray(value);
113
+ }
114
+ /** @param text - one text frame from the client; null when it is not a well-formed message. */
115
+ function parsePtyClientMessage(text) {
116
+ let value;
117
+ try {
118
+ value = JSON.parse(text);
119
+ } catch {
120
+ return null;
121
+ }
122
+ if (!isRecord$4(value)) return null;
123
+ if (value.t === "in" && typeof value.data === "string" && value.data.length <= 262144 && Object.keys(value).length === 2) return {
124
+ t: "in",
125
+ data: value.data
126
+ };
127
+ if (value.t === "resize" && Object.keys(value).length === 3 && typeof value.cols === "number" && typeof value.rows === "number" && Number.isInteger(value.cols) && Number.isInteger(value.rows) && value.cols >= 2 && value.cols <= 500 && value.rows >= 1 && value.rows <= 200) return {
128
+ t: "resize",
129
+ cols: value.cols,
130
+ rows: value.rows
131
+ };
132
+ return null;
133
+ }
134
+ /** The colours a badge may use, so a definition can never carry arbitrary CSS. */
135
+ const BADGE_COLORS = [
136
+ "#94a3b8",
137
+ "#d97757",
138
+ "#10a37f",
139
+ "#4285f4",
140
+ "#a78bfa",
141
+ "#34d399",
142
+ "#f59e0b",
143
+ "#ef4444",
144
+ "#38bdf8",
145
+ "#fb923c"
146
+ ];
147
+ /** Thrown for a definition that breaks a rule; the message is fit to show the user. */
148
+ var AgentDefinitionError = class extends Error {
149
+ constructor(message) {
150
+ super(message);
151
+ this.name = "AgentDefinitionError";
152
+ }
153
+ };
154
+ const ID_PATTERN = /^[a-z][a-z0-9-]{1,31}$/;
155
+ /** A bare name or an absolute path; no whitespace, quotes, or shell metacharacters. */
156
+ const COMMAND_PATTERN = /^(?:\/[A-Za-z0-9._@+:%~\-/]+|[A-Za-z0-9._@+-]+)$/;
157
+ const BUILTIN = new Set(WORKSPACE_PTY_COMMAND_IDS);
158
+ function isBuiltinAgentId(id) {
159
+ return BUILTIN.has(id);
160
+ }
161
+ function isRecord$3(value) {
162
+ return value !== null && typeof value === "object" && !Array.isArray(value);
163
+ }
164
+ /** @param value - untrusted JSON. @returns a command that is an absolute path or a bare program name. @throws AgentDefinitionError. */
165
+ function parseAgentCommand(value) {
166
+ if (typeof value !== "string" || !COMMAND_PATTERN.test(value) || value.includes("..")) throw new AgentDefinitionError("the command must be an absolute path or a bare program name, without spaces or shell characters (put options in the arguments)");
167
+ return value;
168
+ }
169
+ /** @param value - untrusted JSON; absent means no arguments. @throws AgentDefinitionError. */
170
+ function parseAgentArgs(value) {
171
+ const list = value === void 0 ? [] : value;
172
+ if (!Array.isArray(list) || list.length > 16 || !list.every((arg) => typeof arg === "string" && arg.length <= 200 && !arg.includes("\0"))) throw new AgentDefinitionError(`up to ${String(16)} arguments of up to ${String(200)} characters each`);
173
+ return list;
174
+ }
175
+ /** @param value - untrusted JSON. @throws AgentDefinitionError with a user-facing message. */
176
+ function parseCustomAgent(value) {
177
+ if (!isRecord$3(value)) throw new AgentDefinitionError("an agent needs an id, a name, a command and a badge");
178
+ const extra = Object.keys(value).filter((key) => ![
179
+ "id",
180
+ "label",
181
+ "command",
182
+ "args",
183
+ "badge"
184
+ ].includes(key));
185
+ if (extra.length > 0) throw new AgentDefinitionError(`unknown field: ${extra[0] ?? ""}`);
186
+ const { id, label, command, args, badge } = value;
187
+ if (typeof id !== "string" || !ID_PATTERN.test(id)) throw new AgentDefinitionError("the id must be 2 to 32 characters: lowercase letters, digits and dashes, starting with a letter");
188
+ if (isBuiltinAgentId(id)) throw new AgentDefinitionError(`"${id}" is a built-in agent`);
189
+ if (typeof label !== "string" || label.trim() === "" || [...label.trim()].length > 40) throw new AgentDefinitionError(`the name must be 1 to ${String(40)} characters`);
190
+ const commandText = parseAgentCommand(command);
191
+ const argList = parseAgentArgs(args);
192
+ if (!isRecord$3(badge) || typeof badge.letter !== "string" || [...badge.letter].length !== 1 || !BADGE_COLORS.includes(badge.color)) throw new AgentDefinitionError("the badge needs one character and one of the offered colours");
193
+ return {
194
+ id,
195
+ label: label.trim(),
196
+ command: commandText,
197
+ args: argList,
198
+ badge: {
199
+ letter: badge.letter,
200
+ color: badge.color
201
+ }
202
+ };
203
+ }
204
+ //#endregion
205
+ //#region src/agents/contract.ts
206
+ /** GET the catalog; POST `{ agent }` to add one. */
207
+ const WORKSPACE_AGENTS_PATH = "/api/acryl-workspace/agents";
208
+ /** POST `{ id }` to remove one. */
209
+ const WORKSPACE_AGENTS_REMOVE_PATH = "/api/acryl-workspace/agents/remove";
210
+ /** GET the settings view; POST a {@link PreferencesPatch} to change one thing. Both answer with the whole view. */
211
+ const WORKSPACE_AGENT_SETTINGS_PATH = "/api/acryl-workspace/agents/settings";
212
+ //#endregion
213
+ //#region src/agents/launch.ts
214
+ const DEFAULT_OVERRIDE = {
215
+ enabled: true,
216
+ args: []
217
+ };
218
+ /** @returns the launch for a known agent: `yolo` adds the agent's own skip-approvals flags first. */
219
+ function planKnownLaunch(agent, override, mode, statusHooks = false) {
220
+ const yolo = mode === "yolo";
221
+ const env = yolo ? agent.yoloEnv : void 0;
222
+ return {
223
+ command: override.command ?? agent.command,
224
+ args: [...yolo ? agent.yoloArgs : [], ...override.args],
225
+ ...env === void 0 ? {} : { env },
226
+ ...statusHooks && agent.statusHooks !== void 0 ? { statusHooks: agent.statusHooks } : {}
227
+ };
228
+ }
229
+ /** The command line for a person to read, with any environment first (`GOOSE_MODE=auto goose`). */
230
+ function describeLaunch(launch) {
231
+ const quote = (part) => /^[A-Za-z0-9._@+:%~/=,*-]+$/.test(part) ? part : JSON.stringify(part);
232
+ return [
233
+ ...Object.entries(launch.env ?? {}).map(([name, value]) => `${name}=${quote(value)}`),
234
+ launch.command,
235
+ ...launch.args
236
+ ].map(quote).join(" ");
237
+ }
238
+ //#endregion
239
+ //#region src/agents/preferences.ts
240
+ /**
241
+ * The user's agent preferences: the permission mode, the default agent, and per-agent overrides. Pure rules for
242
+ * reading the stored file and for applying one change at a time; the file itself is a port (`file-store.ts`).
243
+ */
244
+ /** Manual is the default: an agent that skips approvals is something the user turns on. */
245
+ const DEFAULT_PREFERENCES = {
246
+ permissions: "manual",
247
+ defaultAgent: "auto",
248
+ overrides: {},
249
+ statusHooks: true
250
+ };
251
+ function isRecord$2(value) {
252
+ return value !== null && typeof value === "object" && !Array.isArray(value);
253
+ }
254
+ const isMode = (value) => value === "yolo" || value === "manual";
255
+ function parseOverride(value) {
256
+ if (!isRecord$2(value)) throw new AgentDefinitionError("an override is an object");
257
+ const { enabled, command, args } = value;
258
+ if (enabled !== void 0 && typeof enabled !== "boolean") throw new AgentDefinitionError("enabled is true or false");
259
+ return {
260
+ enabled: enabled ?? true,
261
+ ...command === void 0 ? {} : { command: parseAgentCommand(command) },
262
+ args: parseAgentArgs(args)
263
+ };
264
+ }
265
+ /** @param value - the parsed stored JSON. A damaged file gives the defaults; one bad override is dropped. */
266
+ function parseStoredPreferences(value) {
267
+ if (!isRecord$2(value)) return DEFAULT_PREFERENCES;
268
+ const overrides = {};
269
+ if (isRecord$2(value.overrides)) for (const [id, raw] of Object.entries(value.overrides)) try {
270
+ overrides[id] = parseOverride(raw);
271
+ } catch {}
272
+ return {
273
+ permissions: isMode(value.permissions) ? value.permissions : DEFAULT_PREFERENCES.permissions,
274
+ defaultAgent: typeof value.defaultAgent === "string" && value.defaultAgent !== "" ? value.defaultAgent : DEFAULT_PREFERENCES.defaultAgent,
275
+ overrides,
276
+ statusHooks: typeof value.statusHooks === "boolean" ? value.statusHooks : DEFAULT_PREFERENCES.statusHooks
277
+ };
278
+ }
279
+ /** @param value - untrusted JSON from the route. @throws AgentDefinitionError with a message fit to show. */
280
+ function parsePreferencesPatch(value) {
281
+ if (!isRecord$2(value)) throw new AgentDefinitionError("invalid agent settings request");
282
+ const extra = Object.keys(value).find((key) => key !== "permissions" && key !== "defaultAgent" && key !== "agent" && key !== "statusHooks");
283
+ if (extra !== void 0) throw new AgentDefinitionError(`unknown field: ${extra}`);
284
+ const patch = {};
285
+ if (value.permissions !== void 0) {
286
+ if (!isMode(value.permissions)) throw new AgentDefinitionError("permissions is yolo or manual");
287
+ patch.permissions = value.permissions;
288
+ }
289
+ if (value.defaultAgent !== void 0) {
290
+ if (typeof value.defaultAgent !== "string" || value.defaultAgent === "" || value.defaultAgent.length > 40) throw new AgentDefinitionError("defaultAgent is auto, none or an agent id");
291
+ patch.defaultAgent = value.defaultAgent;
292
+ }
293
+ if (value.statusHooks !== void 0) {
294
+ if (typeof value.statusHooks !== "boolean") throw new AgentDefinitionError("statusHooks is true or false");
295
+ patch.statusHooks = value.statusHooks;
296
+ }
297
+ if (value.agent !== void 0) {
298
+ const agent = value.agent;
299
+ if (!isRecord$2(agent) || typeof agent.id !== "string" || agent.id === "" || agent.id.length > 40) throw new AgentDefinitionError("an agent change needs an id");
300
+ const unknown = Object.keys(agent).find((key) => ![
301
+ "id",
302
+ "enabled",
303
+ "command",
304
+ "args"
305
+ ].includes(key));
306
+ if (unknown !== void 0) throw new AgentDefinitionError(`unknown field: ${unknown}`);
307
+ if (agent.enabled !== void 0 && typeof agent.enabled !== "boolean") throw new AgentDefinitionError("enabled is true or false");
308
+ patch.agent = {
309
+ id: agent.id,
310
+ ...agent.enabled === void 0 ? {} : { enabled: agent.enabled },
311
+ ...agent.command === void 0 ? {} : { command: agent.command === null ? null : parseAgentCommand(agent.command) },
312
+ ...agent.args === void 0 ? {} : { args: parseAgentArgs(agent.args) }
313
+ };
314
+ }
315
+ return patch;
316
+ }
317
+ /**
318
+ * @param current - the preferences now.
319
+ * @param patch - one validated change.
320
+ * @param isAgent - whether an id names an agent the Host knows (built in or custom).
321
+ * @throws AgentDefinitionError for an unknown agent.
322
+ */
323
+ function applyPreferencesPatch(current, patch, isAgent) {
324
+ let next = current;
325
+ if (patch.permissions !== void 0) next = {
326
+ ...next,
327
+ permissions: patch.permissions
328
+ };
329
+ if (patch.statusHooks !== void 0) next = {
330
+ ...next,
331
+ statusHooks: patch.statusHooks
332
+ };
333
+ if (patch.defaultAgent !== void 0) {
334
+ if (patch.defaultAgent !== "auto" && patch.defaultAgent !== "none" && !isAgent(patch.defaultAgent)) throw new AgentDefinitionError(`"${patch.defaultAgent}" is not an agent`);
335
+ next = {
336
+ ...next,
337
+ defaultAgent: patch.defaultAgent
338
+ };
339
+ }
340
+ if (patch.agent !== void 0) {
341
+ const { id, enabled, command, args } = patch.agent;
342
+ if (!isAgent(id)) throw new AgentDefinitionError(`"${id}" is not an agent`);
343
+ const before = next.overrides[id] ?? DEFAULT_OVERRIDE;
344
+ const { command: oldCommand, ...rest } = before;
345
+ const commandPart = command === void 0 ? oldCommand === void 0 ? {} : { command: oldCommand } : command === null ? {} : { command };
346
+ next = {
347
+ ...next,
348
+ overrides: {
349
+ ...next.overrides,
350
+ [id]: {
351
+ ...rest,
352
+ enabled: enabled ?? before.enabled,
353
+ args: args ?? before.args,
354
+ ...commandPart
355
+ }
356
+ }
357
+ };
358
+ }
359
+ return next;
360
+ }
361
+ //#endregion
362
+ //#region src/agents/route.ts
363
+ /** The custom agent catalog and the agent settings, for the app's own page only. */
364
+ /**
365
+ * GET `agents` (the catalog) and POST `agents` `{ agent }` to add one, a refusal being a 400 whose message says what to fix; POST `agents/remove`
366
+ * `{ id }` (idempotent); GET `agents/settings` (with a fresh check of which programs are installed) and POST one change, answered with the whole view.
367
+ */
368
+ function agentRoutes(catalog, settings, reportError) {
369
+ return new Acryl().get(WORKSPACE_AGENTS_PATH, ownPage, (c) => c.json({ agents: catalog.list() })).post(WORKSPACE_AGENTS_PATH, ownPage, jsonBody(), async (c) => {
370
+ const body = await readJson(c);
371
+ if (!isRecord$5(body) || Object.keys(body).length !== 1 || !("agent" in body)) return c.json(failure("invalid agent request"), 400);
372
+ try {
373
+ await catalog.add(body.agent);
374
+ return c.json({ agents: catalog.list() });
375
+ } catch (cause) {
376
+ if (cause instanceof AgentDefinitionError) return c.json(failure(cause.message), 400);
377
+ reportError("add agent", cause);
378
+ return c.json(failure("the agent could not be saved"), 500);
379
+ }
380
+ }).post(WORKSPACE_AGENTS_REMOVE_PATH, ownPage, jsonBody(), async (c) => {
381
+ const body = await readJson(c);
382
+ if (!isRecord$5(body) || Object.keys(body).length !== 1 || typeof body.id !== "string") return c.json(failure("invalid agent request"), 400);
383
+ try {
384
+ await catalog.remove(body.id);
385
+ return c.json({ agents: catalog.list() });
386
+ } catch (cause) {
387
+ reportError("remove agent", cause);
388
+ return c.json(failure("the agent could not be removed"), 500);
389
+ }
390
+ }).get(WORKSPACE_AGENT_SETTINGS_PATH, ownPage, async (c) => c.json(await settings.view())).post(WORKSPACE_AGENT_SETTINGS_PATH, ownPage, jsonBody(), async (c) => {
391
+ const body = await readJson(c);
392
+ try {
393
+ return c.json(await settings.apply(parsePreferencesPatch(body)));
394
+ } catch (cause) {
395
+ if (cause instanceof AgentDefinitionError) return c.json(failure(cause.message), 400);
396
+ reportError("save agent settings", cause);
397
+ return c.json(failure("the settings could not be saved"), 500);
398
+ }
399
+ });
400
+ }
401
+ //#endregion
402
+ //#region src/agents/catalog.ts
403
+ var AgentCatalog = class {
404
+ store;
405
+ commandExists;
406
+ agents = [];
407
+ loaded = false;
408
+ constructor(store, commandExists) {
409
+ this.store = store;
410
+ this.commandExists = commandExists;
411
+ }
412
+ /** Read the stored definitions; a damaged file is ignored (built-in agents keep working). */
413
+ async load() {
414
+ this.loaded = true;
415
+ try {
416
+ const text = await this.store.read();
417
+ const parsed = text === null ? [] : JSON.parse(text);
418
+ if (!Array.isArray(parsed)) return;
419
+ const good = [];
420
+ for (const item of parsed) try {
421
+ const agent = parseCustomAgent(item);
422
+ if (!good.some((existing) => existing.id === agent.id)) good.push(agent);
423
+ } catch {}
424
+ this.agents = good.slice(0, 32);
425
+ } catch {
426
+ this.agents = [];
427
+ }
428
+ }
429
+ list() {
430
+ return this.agents;
431
+ }
432
+ /** @returns what to launch for a custom agent id, or undefined when the id is not one. */
433
+ resolve(id) {
434
+ const agent = this.agents.find((candidate) => candidate.id === id);
435
+ return agent === void 0 ? void 0 : {
436
+ command: agent.command,
437
+ args: agent.args
438
+ };
439
+ }
440
+ /** @throws AgentDefinitionError for an invalid, duplicate, or unrunnable definition. */
441
+ async add(raw) {
442
+ if (!this.loaded) await this.load();
443
+ const agent = parseCustomAgent(raw);
444
+ if (this.agents.some((existing) => existing.id === agent.id)) throw new AgentDefinitionError(`"${agent.id}" already exists`);
445
+ if (this.agents.length >= 32) throw new AgentDefinitionError(`at most ${String(32)} custom agents`);
446
+ if (!await this.commandExists(agent.command)) throw new AgentDefinitionError(`"${agent.command}" was not found on this machine`);
447
+ const next = [...this.agents, agent];
448
+ await this.store.write(JSON.stringify(next, null, 2));
449
+ this.agents = next;
450
+ return agent;
451
+ }
452
+ /** Idempotent. */
453
+ async remove(id) {
454
+ if (!this.loaded) await this.load();
455
+ if (!this.agents.some((agent) => agent.id === id)) return;
456
+ const next = this.agents.filter((agent) => agent.id !== id);
457
+ await this.store.write(JSON.stringify(next, null, 2));
458
+ this.agents = next;
459
+ }
460
+ };
461
+ //#endregion
462
+ //#region src/agents/file-store.ts
463
+ /** The catalog's file in the user's ACRYL home, written atomically. */
464
+ /** The catalog file in the app's ACRYL home (from the `appInstance` service: this package never looks up a home itself). */
465
+ function agentsFile(appHome) {
466
+ return join(appHome, "workspace", "agents.json");
467
+ }
468
+ /** The preferences file, next to the catalog. */
469
+ function agentSettingsFile(appHome) {
470
+ return join(dirname(agentsFile(appHome)), "agent-settings.json");
471
+ }
472
+ function createFileCatalogStore(path) {
473
+ return {
474
+ async read() {
475
+ try {
476
+ return await readFile(path, "utf8");
477
+ } catch (cause) {
478
+ if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ENOENT") return null;
479
+ throw cause;
480
+ }
481
+ },
482
+ async write(text) {
483
+ await mkdir(dirname(path), { recursive: true });
484
+ const temp = `${path}.${randomBytes(6).toString("hex")}.tmp`;
485
+ await writeFile(temp, text, {
486
+ encoding: "utf8",
487
+ mode: 384
488
+ });
489
+ await rename(temp, path);
490
+ }
491
+ };
492
+ }
493
+ //#endregion
494
+ //#region src/agents/settings.ts
495
+ var AgentSettings = class {
496
+ store;
497
+ catalog;
498
+ commandExists;
499
+ preferences = DEFAULT_PREFERENCES;
500
+ loaded = false;
501
+ constructor(store, catalog, commandExists) {
502
+ this.store = store;
503
+ this.catalog = catalog;
504
+ this.commandExists = commandExists;
505
+ }
506
+ /** Read the stored preferences; a damaged file gives the defaults. */
507
+ async load() {
508
+ this.loaded = true;
509
+ try {
510
+ const text = await this.store.read();
511
+ this.preferences = text === null ? DEFAULT_PREFERENCES : parseStoredPreferences(JSON.parse(text));
512
+ } catch {
513
+ this.preferences = DEFAULT_PREFERENCES;
514
+ }
515
+ }
516
+ /** @returns what to run for an agent id (a known agent with the user's settings, or a custom agent), or undefined. */
517
+ resolve(id) {
518
+ const known = knownAgent(id);
519
+ if (known !== void 0) return planKnownLaunch(known, this.preferences.overrides[id] ?? DEFAULT_OVERRIDE, this.preferences.permissions, this.preferences.statusHooks);
520
+ return this.catalog.resolve(id);
521
+ }
522
+ /** @throws AgentDefinitionError for an unknown agent or an invalid value. */
523
+ async apply(patch) {
524
+ if (!this.loaded) await this.load();
525
+ const next = applyPreferencesPatch(this.preferences, patch, (id) => this.isAgent(id));
526
+ await this.store.write(JSON.stringify(next, null, 2));
527
+ this.preferences = next;
528
+ return await this.view();
529
+ }
530
+ /** The list Settings shows: known agents first, then the user's own. Detection is fresh on every call. */
531
+ async view() {
532
+ const { permissions, overrides, statusHooks } = this.preferences;
533
+ const known = await Promise.all(KNOWN_AGENTS.map(async (agent) => {
534
+ const override = overrides[agent.id] ?? DEFAULT_OVERRIDE;
535
+ const launch = planKnownLaunch(agent, override, permissions);
536
+ return {
537
+ id: agent.id,
538
+ label: agent.label,
539
+ kind: "known",
540
+ homepageUrl: agent.homepageUrl,
541
+ defaultCommand: agent.command,
542
+ command: launch.command,
543
+ args: override.args,
544
+ permissionArgs: permissions === "yolo" ? agent.yoloArgs : [],
545
+ permissionEnv: permissions === "yolo" ? agent.yoloEnv ?? {} : {},
546
+ enabled: override.enabled,
547
+ installed: await this.commandExists(launch.command),
548
+ preview: describeLaunch(launch),
549
+ badge: null
550
+ };
551
+ }));
552
+ const custom = await Promise.all(this.catalog.list().map(async (agent) => ({
553
+ id: agent.id,
554
+ label: agent.label,
555
+ kind: "custom",
556
+ homepageUrl: null,
557
+ defaultCommand: agent.command,
558
+ command: agent.command,
559
+ args: agent.args,
560
+ permissionArgs: [],
561
+ permissionEnv: {},
562
+ enabled: (overrides[agent.id] ?? DEFAULT_OVERRIDE).enabled,
563
+ installed: await this.commandExists(agent.command),
564
+ preview: describeLaunch({
565
+ command: agent.command,
566
+ args: agent.args
567
+ }),
568
+ badge: agent.badge
569
+ })));
570
+ const agents = [...known, ...custom];
571
+ const stored = this.preferences.defaultAgent;
572
+ return {
573
+ permissions,
574
+ defaultAgent: stored === "auto" || stored === "none" || agents.some((entry) => entry.id === stored) ? stored : "auto",
575
+ statusHooks,
576
+ agents
577
+ };
578
+ }
579
+ isAgent(id) {
580
+ return knownAgent(id) !== void 0 || this.catalog.list().some((agent) => agent.id === id);
581
+ }
582
+ };
583
+ //#endregion
584
+ //#region src/agents/status/agent-status.ts
585
+ /**
586
+ * What a terminal agent is doing right now, as the agent itself reports it (spec 040 T127).
587
+ *
588
+ * Reading this off the screen would be guessing, so the agents that support hooks tell ACRYL instead: Claude Code
589
+ * runs a small command on "prompt submitted", "tool finished", "needs you" and "turn finished", and that command
590
+ * posts the state here. The store keeps the latest state per terminal and only ever answers for terminals the Host
591
+ * still has.
592
+ */
593
+ /** GET from the page: every live terminal's status. POST from an agent's hook: one report. */
594
+ const WORKSPACE_AGENT_STATUS_PATH = "/api/acryl-workspace/agent-status";
595
+ const AGENT_STATES = [
596
+ "working",
597
+ "waiting",
598
+ "done"
599
+ ];
600
+ var AgentStatusError = class extends Error {
601
+ constructor(message) {
602
+ super(message);
603
+ this.name = "AgentStatusError";
604
+ }
605
+ };
606
+ const isState = (value) => AGENT_STATES.includes(value);
607
+ /** @param body - untrusted JSON from a hook. @throws AgentStatusError. */
608
+ function parseStatusReport(body) {
609
+ if (typeof body !== "object" || body === null || Array.isArray(body)) throw new AgentStatusError("a report is an object");
610
+ const record = body;
611
+ const extra = Object.keys(record).find((key) => key !== "terminal" && key !== "state");
612
+ if (extra !== void 0) throw new AgentStatusError(`unknown field: ${extra}`);
613
+ const { terminal, state } = record;
614
+ if (typeof terminal !== "string" || terminal.length === 0 || terminal.length > 80) throw new AgentStatusError("terminal must be a terminal id");
615
+ if (!isState(state)) throw new AgentStatusError("state is working, waiting or done");
616
+ return {
617
+ terminal,
618
+ state
619
+ };
620
+ }
621
+ var AgentStatusStore = class {
622
+ isLive;
623
+ now;
624
+ statuses = /* @__PURE__ */ new Map();
625
+ /** @param isLive - whether the Host still has a terminal with this id. @param now - the clock. */
626
+ constructor(isLive, now = Date.now) {
627
+ this.isLive = isLive;
628
+ this.now = now;
629
+ }
630
+ /** @returns false when no such terminal exists (a stale or forged report is ignored). */
631
+ report(terminalId, state) {
632
+ if (!this.isLive(terminalId)) return false;
633
+ this.statuses.set(terminalId, {
634
+ terminalId,
635
+ state,
636
+ at: this.now()
637
+ });
638
+ return true;
639
+ }
640
+ /** The latest status of every terminal that still exists; the others are forgotten here. */
641
+ list() {
642
+ for (const id of [...this.statuses.keys()]) if (!this.isLive(id)) this.statuses.delete(id);
643
+ return [...this.statuses.values()];
644
+ }
645
+ };
646
+ //#endregion
647
+ //#region src/agents/status/route.ts
648
+ /** The status route: agents POST what they are doing (bearer token, loopback only); the page GETs the list. */
649
+ /**
650
+ * GET (from the app's own page): every live terminal's latest status.
651
+ * POST (from an agent's hook, a program and not a page): `{ terminal, state }` with `Authorization: Bearer <token>`. The token is known only to
652
+ * terminals ACRYL started for agents, and the request must come from this machine to the app's own loopback address.
653
+ */
654
+ function agentStatusRoutes(token, store, reportError) {
655
+ const fromAgent = [loopbackOnly({
656
+ mutations: "none",
657
+ hostnames: ["127.0.0.1"]
658
+ }), bearerAuth({
659
+ token,
660
+ noAuthenticationHeader: { message: failure("a bearer token is required") },
661
+ invalidAuthenticationHeader: { message: failure("invalid authorization header") },
662
+ invalidToken: { message: failure("wrong token") }
663
+ })];
664
+ return new Acryl().get(WORKSPACE_AGENT_STATUS_PATH, ownPage, (c) => c.json({ statuses: store.list() })).post(WORKSPACE_AGENT_STATUS_PATH, ...fromAgent, jsonBody(), async (c) => {
665
+ const body = await readJson(c);
666
+ if (body === INVALID_JSON) return c.json(failure("invalid report"), 400);
667
+ try {
668
+ const report = parseStatusReport(body);
669
+ return c.json({ ok: store.report(report.terminal, report.state) });
670
+ } catch (cause) {
671
+ if (cause instanceof AgentStatusError) return c.json(failure(cause.message), 400);
672
+ reportError("record agent status", cause);
673
+ return c.json(failure("the report could not be recorded"), 500);
674
+ }
675
+ });
676
+ }
677
+ //#endregion
678
+ //#region src/capabilities/contract.ts
679
+ /** What the Host composition can do for the page, so the page offers only what will work. */
680
+ const WORKSPACE_CAPABILITIES_PATH = "/api/acryl-workspace/capabilities";
681
+ //#endregion
682
+ //#region src/capabilities/route.ts
683
+ /** What the running composition offers, for the app's own page only. */
684
+ /**
685
+ * GET the capabilities. `read` is asked on every request, so a chat that was switched on or off in the Loader since the page loaded is
686
+ * reported as it is now: the truth is the composition, not a flag copied from a Blueprint.
687
+ */
688
+ function capabilityRoutes(read) {
689
+ return new Acryl().get(WORKSPACE_CAPABILITIES_PATH, ownPage, (c) => c.json(read()));
690
+ }
691
+ //#endregion
692
+ //#region src/files/contract.ts
693
+ /** Loopback routes and JSON shapes for browsing, reading and saving files inside a git worktree. */
694
+ const WORKSPACE_FILES_TREE_PATH = "/api/acryl-workspace/files/tree";
695
+ const WORKSPACE_FILES_READ_PATH = "/api/acryl-workspace/files/read";
696
+ const WORKSPACE_FILES_WRITE_PATH = "/api/acryl-workspace/files/write";
697
+ const WORKSPACE_FILES_ENTRY_PATH = "/api/acryl-workspace/files/entry";
698
+ function isRecord$1(value) {
699
+ return value !== null && typeof value === "object" && !Array.isArray(value);
700
+ }
701
+ /** Validate an untrusted request body into a change, or null when it is not one. */
702
+ function parseFileEntryChange(value) {
703
+ if (!isRecord$1(value)) return null;
704
+ const keys = Object.keys(value).filter((key) => key !== "path").sort().join(",");
705
+ if (value.op === "create" && keys === "file,kind,op" && typeof value.file === "string" && (value.kind === "file" || value.kind === "dir")) return {
706
+ op: "create",
707
+ kind: value.kind,
708
+ file: value.file
709
+ };
710
+ if (value.op === "rename" && keys === "file,op,to" && typeof value.file === "string" && typeof value.to === "string") return {
711
+ op: "rename",
712
+ file: value.file,
713
+ to: value.to
714
+ };
715
+ if (value.op === "delete" && keys === "file,op" && typeof value.file === "string") return {
716
+ op: "delete",
717
+ file: value.file
718
+ };
719
+ return null;
720
+ }
721
+ //#endregion
722
+ //#region src/files/service.ts
723
+ /**
724
+ * Browsing, reading and saving files inside one git worktree.
725
+ *
726
+ * This is the only part of the package that writes user files, so every path is confined: the worktree
727
+ * must be the root of a git worktree (checked by the injected resolver), a file path is relative and
728
+ * free of `..` and `.git` segments, and the real path (after symlinks) must stay inside the worktree.
729
+ * Saves are atomic (temp file then rename) and refuse to overwrite a file that changed on disk since it
730
+ * was read.
731
+ */
732
+ var WorkspaceFilesError = class extends Error {
733
+ kind;
734
+ constructor(message, kind) {
735
+ super(message);
736
+ this.kind = kind;
737
+ this.name = "WorkspaceFilesError";
738
+ }
739
+ };
740
+ const MAX_ENTRIES = 3e3;
741
+ const BINARY_SNIFF_BYTES = 8192;
742
+ var WorkspaceFiles = class {
743
+ options;
744
+ constructor(options) {
745
+ this.options = options;
746
+ }
747
+ async tree(worktree, dir) {
748
+ const root = await this.options.resolveWorktree(worktree);
749
+ const target = dir === "" ? root : await confine(root, dir);
750
+ let dirents;
751
+ try {
752
+ if (!(await stat(target)).isDirectory()) throw new Error("not a directory");
753
+ dirents = await readdir(target, { withFileTypes: true });
754
+ } catch {
755
+ throw new WorkspaceFilesError("that directory cannot be read", "not-found");
756
+ }
757
+ const entries = [];
758
+ for (const dirent of dirents) {
759
+ if (dirent.name === ".git") continue;
760
+ if (dirent.isDirectory()) entries.push({
761
+ name: dirent.name,
762
+ kind: "dir"
763
+ });
764
+ else if (dirent.isFile()) entries.push({
765
+ name: dirent.name,
766
+ kind: "file"
767
+ });
768
+ else if (dirent.isSymbolicLink()) {
769
+ const kind = await symlinkKind(root, join(target, dirent.name));
770
+ if (kind !== null) entries.push({
771
+ name: dirent.name,
772
+ kind
773
+ });
774
+ }
775
+ }
776
+ entries.sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name, "en", { sensitivity: "base" }) : a.kind === "dir" ? -1 : 1);
777
+ const shown = entries.slice(0, MAX_ENTRIES);
778
+ const pathOf = (entry) => `${dir === "" ? "" : `${dir}/`}${entry.name}${entry.kind === "dir" ? "/" : ""}`;
779
+ const ignored = this.options.ignored === void 0 ? /* @__PURE__ */ new Set() : await this.options.ignored(root, shown.map(pathOf));
780
+ return {
781
+ path: root,
782
+ dir,
783
+ entries: ignored.size === 0 ? shown : shown.map((entry) => ignored.has(pathOf(entry)) ? {
784
+ ...entry,
785
+ ignored: true
786
+ } : entry),
787
+ truncated: entries.length > MAX_ENTRIES
788
+ };
789
+ }
790
+ async read(worktree, file) {
791
+ const root = await this.options.resolveWorktree(worktree);
792
+ const real = await confine(root, file);
793
+ const info = await statFile(real);
794
+ if (info.size > 2097152) throw new WorkspaceFilesError("the file is too large to edit here", "too-large");
795
+ const buffer = await readFile(real);
796
+ const binary = buffer.subarray(0, BINARY_SNIFF_BYTES).includes(0);
797
+ return {
798
+ path: root,
799
+ file,
800
+ content: binary ? "" : buffer.toString("utf8"),
801
+ binary,
802
+ size: info.size,
803
+ mtimeMs: info.mtimeMs
804
+ };
805
+ }
806
+ /**
807
+ * Replace an existing file's text.
808
+ * @param expectedMtimeMs - the `mtimeMs` from the read this edit is based on.
809
+ * @throws WorkspaceFilesError `conflict` when the file changed on disk since that read.
810
+ */
811
+ async write(worktree, file, content, expectedMtimeMs) {
812
+ const root = await this.options.resolveWorktree(worktree);
813
+ const real = await confine(root, file);
814
+ const info = await statFile(real);
815
+ if (Buffer.byteLength(content, "utf8") > 2097152) throw new WorkspaceFilesError("the text is too large to save here", "too-large");
816
+ if (info.mtimeMs !== expectedMtimeMs) throw new WorkspaceFilesError("the file changed on disk since you opened it", "conflict");
817
+ const temp = join(dirname(real), `.${basename(real)}.acryl-${randomBytes(6).toString("hex")}.tmp`);
818
+ try {
819
+ await writeFile(temp, content, {
820
+ encoding: "utf8",
821
+ flag: "wx"
822
+ });
823
+ await chmod(temp, info.mode & 4095);
824
+ await rename(temp, real);
825
+ } catch {
826
+ await unlink(temp).catch(() => {});
827
+ throw new WorkspaceFilesError("the file could not be saved", "failed");
828
+ }
829
+ const saved = await stat(real);
830
+ return {
831
+ path: root,
832
+ file,
833
+ size: saved.size,
834
+ mtimeMs: saved.mtimeMs
835
+ };
836
+ }
837
+ /**
838
+ * Create, rename or delete one entry. Never overwrites, never recurses: a delete removes a file or an
839
+ * empty folder only, and a create or rename refuses a name that is already taken.
840
+ */
841
+ async change(worktree, change) {
842
+ const root = await this.options.resolveWorktree(worktree);
843
+ if (change.op === "create") {
844
+ const target = await confineNew(root, change.file);
845
+ try {
846
+ if (change.kind === "dir") await mkdir(target);
847
+ else await writeFile(target, "", { flag: "wx" });
848
+ } catch {
849
+ throw new WorkspaceFilesError("that could not be created", "failed");
850
+ }
851
+ return {
852
+ path: root,
853
+ op: "create",
854
+ file: change.file
855
+ };
856
+ }
857
+ if (change.op === "rename") {
858
+ const source = await confineEntry(root, change.file);
859
+ const target = await confineNew(root, change.to);
860
+ try {
861
+ await rename(source, target);
862
+ } catch {
863
+ throw new WorkspaceFilesError("that could not be renamed", "failed");
864
+ }
865
+ return {
866
+ path: root,
867
+ op: "rename",
868
+ file: change.to
869
+ };
870
+ }
871
+ const target = await confineEntry(root, change.file);
872
+ try {
873
+ if ((await lstat(target)).isDirectory()) await rmdir(target);
874
+ else await unlink(target);
875
+ } catch (cause) {
876
+ const code = typeof cause === "object" && cause !== null && "code" in cause ? cause.code : void 0;
877
+ if (code === "ENOTEMPTY" || code === "EEXIST") throw new WorkspaceFilesError("only an empty folder can be deleted", "conflict");
878
+ throw new WorkspaceFilesError("that could not be deleted", "failed");
879
+ }
880
+ return {
881
+ path: root,
882
+ op: "delete",
883
+ file: null
884
+ };
885
+ }
886
+ };
887
+ async function statFile(real) {
888
+ try {
889
+ const info = await stat(real);
890
+ if (!info.isFile()) throw new Error("not a file");
891
+ return {
892
+ size: info.size,
893
+ mtimeMs: info.mtimeMs,
894
+ mode: info.mode
895
+ };
896
+ } catch {
897
+ throw new WorkspaceFilesError("that file does not exist", "not-found");
898
+ }
899
+ }
900
+ /** A symlink is listed only when it points at a file or directory inside the worktree. */
901
+ async function symlinkKind(root, path) {
902
+ try {
903
+ const real = await realpath(path);
904
+ if (!isInside$1(root, real)) return null;
905
+ const info = await stat(real);
906
+ return info.isDirectory() ? "dir" : info.isFile() ? "file" : null;
907
+ } catch {
908
+ return null;
909
+ }
910
+ }
911
+ function isInside$1(root, real) {
912
+ return real === root || real.startsWith(root.endsWith(sep) ? root : root + sep);
913
+ }
914
+ /**
915
+ * Turn a worktree-relative path into a real path that is guaranteed to be inside `root`.
916
+ * Rejects absolute paths, NUL, `..` and `.git` segments, and symlinks that leave the worktree.
917
+ */
918
+ async function confine(root, relative) {
919
+ if (typeof relative !== "string" || relative.length === 0 || relative.includes("\0") || isAbsolute(relative)) throw new WorkspaceFilesError("path must be relative to the worktree", "invalid");
920
+ const segments = relative.split(/[\\/]+/).filter((segment) => segment.length > 0);
921
+ if (segments.length === 0 || segments.some((segment) => segment === ".." || segment.toLowerCase() === ".git")) throw new WorkspaceFilesError("that path is not allowed", "invalid");
922
+ let real;
923
+ try {
924
+ real = await realpath(join(root, ...segments));
925
+ } catch {
926
+ throw new WorkspaceFilesError("that path does not exist", "not-found");
927
+ }
928
+ if (!isInside$1(root, real)) throw new WorkspaceFilesError("that path leaves the worktree", "invalid");
929
+ return real;
930
+ }
931
+ function segmentsOf(relative) {
932
+ if (typeof relative !== "string" || relative.length === 0 || relative.includes("\0") || isAbsolute(relative)) throw new WorkspaceFilesError("path must be relative to the worktree", "invalid");
933
+ const segments = relative.split(/[\\/]+/).filter((segment) => segment.length > 0);
934
+ if (segments.length === 0 || segments.some((segment) => segment === ".." || segment === "." || segment.toLowerCase() === ".git")) throw new WorkspaceFilesError("that path is not allowed", "invalid");
935
+ return segments;
936
+ }
937
+ /**
938
+ * The real path of an entry that will be created: its folder must exist inside the worktree and the name
939
+ * must be free (a dangling symlink counts as taken).
940
+ */
941
+ async function confineNew(root, relative) {
942
+ const segments = segmentsOf(relative);
943
+ const name = segments[segments.length - 1];
944
+ let parent;
945
+ try {
946
+ parent = await realpath(join(root, ...segments.slice(0, -1)));
947
+ } catch {
948
+ throw new WorkspaceFilesError("the folder does not exist", "not-found");
949
+ }
950
+ if (!isInside$1(root, parent)) throw new WorkspaceFilesError("that path leaves the worktree", "invalid");
951
+ const target = join(parent, name);
952
+ try {
953
+ await lstat(target);
954
+ } catch {
955
+ return target;
956
+ }
957
+ throw new WorkspaceFilesError("something with that name already exists", "conflict");
958
+ }
959
+ /** The path of an existing entry itself: a symlink is renamed or deleted as the link, never followed. */
960
+ async function confineEntry(root, relative) {
961
+ const segments = segmentsOf(relative);
962
+ const name = segments[segments.length - 1];
963
+ let parent;
964
+ try {
965
+ parent = await realpath(join(root, ...segments.slice(0, -1)));
966
+ } catch {
967
+ throw new WorkspaceFilesError("that path does not exist", "not-found");
968
+ }
969
+ if (!isInside$1(root, parent)) throw new WorkspaceFilesError("that path leaves the worktree", "invalid");
970
+ const target = join(parent, name);
971
+ try {
972
+ await lstat(target);
973
+ } catch {
974
+ throw new WorkspaceFilesError("that path does not exist", "not-found");
975
+ }
976
+ return target;
977
+ }
978
+ //#endregion
979
+ //#region src/files/route.ts
980
+ /** The worktree file routes: two reads and two changes, for the app's own page only. */
981
+ const STATUS = {
982
+ invalid: 400,
983
+ "not-found": 404,
984
+ conflict: 409,
985
+ "too-large": 413,
986
+ failed: 500
987
+ };
988
+ function required$1(c, name) {
989
+ const value = c.req.query(name);
990
+ if (value === void 0 || value.length === 0) throw new WorkspaceFilesError(`missing ${name}`, "invalid");
991
+ return value;
992
+ }
993
+ /**
994
+ * GET `tree?path=<worktree>&dir=<relative, empty for the root>` and `read?path=&file=`; POST `write` `{ path, file, content, expectedMtimeMs }`
995
+ * to replace an existing file's text and `entry` `{ path, op: 'create' | 'rename' | 'delete', file, kind?, to? }` for one structural change.
996
+ */
997
+ function filesRoutes(files, reportError) {
998
+ const answer = async (c, operation, compute) => {
999
+ try {
1000
+ return c.json(await compute());
1001
+ } catch (cause) {
1002
+ if (cause instanceof WorkspaceFilesError) return c.json(failure(cause.message), STATUS[cause.kind]);
1003
+ reportError(operation, cause);
1004
+ return c.json(failure("file request failed"), 500);
1005
+ }
1006
+ };
1007
+ return new Acryl().get(WORKSPACE_FILES_TREE_PATH, ownPage, (c) => answer(c, "list files", () => files.tree(required$1(c, "path"), c.req.query("dir") ?? ""))).get(WORKSPACE_FILES_READ_PATH, ownPage, (c) => answer(c, "read file", () => files.read(required$1(c, "path"), required$1(c, "file")))).post(WORKSPACE_FILES_WRITE_PATH, ownPage, jsonBody(2162688), async (c) => {
1008
+ const body = await readJson(c);
1009
+ if (body === INVALID_JSON || !isRecord$5(body) || typeof body.path !== "string" || typeof body.file !== "string" || typeof body.content !== "string" || typeof body.expectedMtimeMs !== "number" || Object.keys(body).length !== 4) return c.json(failure("invalid save request"), 400);
1010
+ const { path, file, content, expectedMtimeMs } = body;
1011
+ return answer(c, "save file", () => files.write(path, file, content, expectedMtimeMs));
1012
+ }).post(WORKSPACE_FILES_ENTRY_PATH, ownPage, jsonBody(), async (c) => {
1013
+ const body = await readJson(c);
1014
+ const change = body === INVALID_JSON ? null : parseFileEntryChange(body);
1015
+ if (change === null || !isRecord$5(body) || typeof body.path !== "string") return c.json(failure("invalid change request"), 400);
1016
+ const { path } = body;
1017
+ return answer(c, "change file", () => files.change(path, change));
1018
+ });
1019
+ }
1020
+ //#endregion
1021
+ //#region src/folder-picker/picker.ts
1022
+ /**
1023
+ * Opens the operating system's own folder chooser and reports the folder picked. The Host serves a
1024
+ * loopback-only Web server (`@acryldev/workspace` refuses to start otherwise), so a dialog raised here is on
1025
+ * the same machine as the person using the page - the reason this is safe to offer at all, unlike a
1026
+ * chooser on a remote server nobody is sitting at.
1027
+ */
1028
+ /** No native chooser exists on this machine (no dialog program installed). */
1029
+ var FolderPickerUnavailableError = class extends Error {
1030
+ constructor() {
1031
+ super("no native folder chooser is available on this machine");
1032
+ this.name = "FolderPickerUnavailableError";
1033
+ }
1034
+ };
1035
+ const defaultRun = (file, args) => new Promise((resolve, reject) => {
1036
+ execFile(file, [...args], { maxBuffer: 1024 * 1024 }, (cause, stdout) => {
1037
+ if (cause === null) resolve(stdout);
1038
+ else reject(cause);
1039
+ });
1040
+ });
1041
+ function exitCode(cause) {
1042
+ return typeof cause === "object" && cause !== null && "code" in cause ? cause.code : void 0;
1043
+ }
1044
+ /** A trailing separator is dropped (the chooser adds one), except for a filesystem root. */
1045
+ function normalizePickedPath(raw) {
1046
+ const text = raw.trim();
1047
+ if (text === "") return null;
1048
+ const stripped = text.replace(/[\\/]+$/, "");
1049
+ return stripped === "" ? text : stripped;
1050
+ }
1051
+ const MAC_SCRIPT = [
1052
+ "try",
1053
+ "POSIX path of (choose folder with prompt \"Choose a workspace folder\")",
1054
+ "on error number -128",
1055
+ "return \"\"",
1056
+ "end try"
1057
+ ];
1058
+ const WINDOWS_SCRIPT = [
1059
+ "Add-Type -AssemblyName System.Windows.Forms",
1060
+ "$d = New-Object System.Windows.Forms.FolderBrowserDialog",
1061
+ "$d.Description = \"Choose a workspace folder\"",
1062
+ "if ($d.ShowDialog() -eq 'OK') { Write-Output $d.SelectedPath }"
1063
+ ].join("; ");
1064
+ /**
1065
+ * @param platform - `process.platform`.
1066
+ * @param run - process runner; injected so the tests never open a dialog.
1067
+ * @returns the absolute path picked, or null when the chooser was cancelled.
1068
+ * @throws FolderPickerUnavailableError when this machine has no chooser program.
1069
+ */
1070
+ async function pickFolderNatively(platform, run = defaultRun) {
1071
+ if (platform === "darwin") return normalizePickedPath(await run("osascript", MAC_SCRIPT.flatMap((line) => ["-e", line])));
1072
+ if (platform === "win32") return normalizePickedPath(await run("powershell.exe", [
1073
+ "-NoProfile",
1074
+ "-STA",
1075
+ "-Command",
1076
+ WINDOWS_SCRIPT
1077
+ ]));
1078
+ for (const [file, args] of [["zenity", [
1079
+ "--file-selection",
1080
+ "--directory",
1081
+ "--title=Choose a workspace folder"
1082
+ ]], ["kdialog", [
1083
+ "--getexistingdirectory",
1084
+ ".",
1085
+ "--title",
1086
+ "Choose a workspace folder"
1087
+ ]]]) try {
1088
+ return normalizePickedPath(await run(file, args));
1089
+ } catch (cause) {
1090
+ if (exitCode(cause) === "ENOENT") continue;
1091
+ return null;
1092
+ }
1093
+ throw new FolderPickerUnavailableError();
1094
+ }
1095
+ /** One chooser at a time: a second request while one is open waits for that answer instead of stacking dialogs. */
1096
+ function singleFlight(task) {
1097
+ let inflight;
1098
+ return () => {
1099
+ inflight ??= task().finally(() => {
1100
+ inflight = void 0;
1101
+ });
1102
+ return inflight;
1103
+ };
1104
+ }
1105
+ //#endregion
1106
+ //#region src/folder-picker/contract.ts
1107
+ /** Same-origin route that opens the operating system's own folder chooser on the machine running the Host. */
1108
+ const WORKSPACE_PICK_FOLDER_PATH = "/api/acryl-workspace/pick-folder";
1109
+ //#endregion
1110
+ //#region src/folder-picker/route.ts
1111
+ /** The native folder chooser, for the app's own page only. */
1112
+ /** POST: open the OS's chooser and answer the folder, or `null` when it was cancelled. */
1113
+ function pickFolderRoutes(pick, reportError) {
1114
+ return new Acryl().post(WORKSPACE_PICK_FOLDER_PATH, ownPage, async (c) => {
1115
+ if (c.req.header("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") return c.json(failure("forbidden"), 403);
1116
+ try {
1117
+ return c.json({ path: await pick() });
1118
+ } catch (cause) {
1119
+ if (cause instanceof FolderPickerUnavailableError) return c.json(failure(cause.message), 501);
1120
+ reportError("open the folder chooser", cause);
1121
+ return c.json(failure("the folder chooser failed"), 500);
1122
+ }
1123
+ });
1124
+ }
1125
+ //#endregion
1126
+ //#region src/git/contract.ts
1127
+ /** Read-only git routes and view types shared by the ACRYL Workspace Host and Client. */
1128
+ const WORKSPACE_GIT_REPO_PATH = "/api/acryl-workspace/git/repo";
1129
+ const WORKSPACE_GIT_STATUS_PATH = "/api/acryl-workspace/git/status";
1130
+ const WORKSPACE_GIT_DIFF_PATH = "/api/acryl-workspace/git/diff";
1131
+ const WORKSPACE_GIT_WORKTREE_PATH = "/api/acryl-workspace/git/worktree";
1132
+ const WORKSPACE_GIT_CHECKS_PATH = "/api/acryl-workspace/git/checks";
1133
+ const WORKSPACE_GIT_SEARCH_PATH = "/api/acryl-workspace/git/search";
1134
+ const WORKSPACE_GIT_STAGE_PATH = "/api/acryl-workspace/git/stage";
1135
+ const WORKSPACE_GIT_UNSTAGE_PATH = "/api/acryl-workspace/git/unstage";
1136
+ const WORKSPACE_GIT_COMMIT_PATH = "/api/acryl-workspace/git/commit";
1137
+ /** The most files one stage or unstage request may name. */
1138
+ const MAX_STAGE_FILES = 1e3;
1139
+ //#endregion
1140
+ //#region src/git/errors.ts
1141
+ /** Errors of the Workspace git modules. */
1142
+ /**
1143
+ * A request the caller got wrong (400), a directory that is not a repository (404), something that
1144
+ * already exists (409), or a git failure (500).
1145
+ */
1146
+ var WorkspaceGitError = class extends Error {
1147
+ kind;
1148
+ constructor(message, kind) {
1149
+ super(message);
1150
+ this.kind = kind;
1151
+ this.name = "WorkspaceGitError";
1152
+ }
1153
+ };
1154
+ //#endregion
1155
+ //#region src/git/guards.ts
1156
+ /** Checks on what a caller may hand to git, before git sees it. */
1157
+ /**
1158
+ * A conservative first filter, before git's own check: letters, digits, `.`, `_`, `-` and `/`
1159
+ * separators, starting with a letter, digit or underscore. It keeps the branch usable as one folder
1160
+ * name and can never look like an option or a path escape.
1161
+ */
1162
+ function assertBranchName(branch) {
1163
+ if (typeof branch !== "string" || branch.length === 0 || branch.length > 200 || !/^[A-Za-z0-9_][A-Za-z0-9._/-]*$/.test(branch) || branch.includes("..") || branch.includes("//") || branch.endsWith("/") || branch.endsWith(".") || branch.endsWith(".lock")) throw new WorkspaceGitError("branch names use letters, digits, \".\", \"_\", \"-\" and \"/\", and start with a letter, digit or \"_\"", "invalid");
1164
+ }
1165
+ function assertFileList(files) {
1166
+ if (!Array.isArray(files) || files.length === 0 || files.length > 1e3) throw new WorkspaceGitError(`name between 1 and ${String(MAX_STAGE_FILES)} files`, "invalid");
1167
+ for (const file of files) assertRelativeFile(file);
1168
+ }
1169
+ function assertRelativeFile(file) {
1170
+ if (typeof file !== "string" || file.length === 0 || file.length > 4096 || file.includes("\0") || file.startsWith("/") || file.startsWith("-") || /(^|[\\/])\.\.([\\/]|$)/.test(file)) throw new WorkspaceGitError("file must be a relative path inside the worktree", "invalid");
1171
+ }
1172
+ //#endregion
1173
+ //#region src/git/parsing.ts
1174
+ /** Parsers for the machine-readable output of `git worktree`, `git diff --numstat` and `git status`. */
1175
+ /** Parse `git worktree list --porcelain`. Git always lists the main worktree first. Git writes `C:/repo` on Windows; paths are returned in the host's own form (`C:\repo`). */
1176
+ function parseWorktrees(text) {
1177
+ const worktrees = [];
1178
+ for (const block of text.split(/\n\n+/)) {
1179
+ let path;
1180
+ let head = "";
1181
+ let branch = null;
1182
+ for (const line of block.split("\n")) if (line.startsWith("worktree ")) path = line.slice(9);
1183
+ else if (line.startsWith("HEAD ")) head = line.slice(5);
1184
+ else if (line.startsWith("branch ")) branch = line.slice(7).replace(/^refs\/heads\//, "");
1185
+ if (path !== void 0) worktrees.push({
1186
+ path: normalize(path),
1187
+ head,
1188
+ branch,
1189
+ main: worktrees.length === 0
1190
+ });
1191
+ }
1192
+ return worktrees;
1193
+ }
1194
+ /** Parse `git diff --numstat -z`. Binary files report `-` and map to null counts. */
1195
+ function parseNumstat(text) {
1196
+ const counts = /* @__PURE__ */ new Map();
1197
+ const tokens = text.split("\0");
1198
+ for (let index = 0; index < tokens.length; index += 1) {
1199
+ const token = tokens[index];
1200
+ if (token === void 0 || token === "") continue;
1201
+ const match = /^(\d+|-)\t(\d+|-)\t([\s\S]*)$/.exec(token);
1202
+ if (match === null) continue;
1203
+ let path = match[3] ?? "";
1204
+ if (path === "") {
1205
+ path = tokens[index + 2] ?? "";
1206
+ index += 2;
1207
+ }
1208
+ counts.set(path, {
1209
+ added: match[1] === "-" ? null : Number(match[1]),
1210
+ removed: match[2] === "-" ? null : Number(match[2])
1211
+ });
1212
+ }
1213
+ return counts;
1214
+ }
1215
+ function classify(x, y) {
1216
+ if (x === "?" && y === "?") return {
1217
+ code: "?",
1218
+ staged: false
1219
+ };
1220
+ if (x === "U" || y === "U" || x === "A" && y === "A" || x === "D" && y === "D") return {
1221
+ code: "U",
1222
+ staged: false
1223
+ };
1224
+ const staged = x !== " ";
1225
+ let code;
1226
+ if (x === "A" || x === "C") code = "A";
1227
+ else if (x === "R") code = "R";
1228
+ else code = y !== " " ? y : x;
1229
+ if (code === "T") code = "M";
1230
+ return {
1231
+ code: [
1232
+ "M",
1233
+ "A",
1234
+ "D",
1235
+ "R"
1236
+ ].includes(code) ? code : "M",
1237
+ staged
1238
+ };
1239
+ }
1240
+ /** Parse `git status --porcelain=v1 -z`, attaching line counts where git reported them. */
1241
+ function parsePorcelain(text, counts) {
1242
+ const changes = [];
1243
+ const tokens = text.split("\0");
1244
+ for (let index = 0; index < tokens.length; index += 1) {
1245
+ const token = tokens[index];
1246
+ if (token === void 0 || token.length < 4) continue;
1247
+ const x = token[0] ?? " ";
1248
+ const y = token[1] ?? " ";
1249
+ if (x === "!" && y === "!") continue;
1250
+ const path = token.slice(3);
1251
+ let oldPath;
1252
+ if (x === "R" || x === "C" || y === "R" || y === "C") {
1253
+ oldPath = tokens[index + 1];
1254
+ index += 1;
1255
+ }
1256
+ const { code, staged } = classify(x, y);
1257
+ const count = counts.get(path);
1258
+ changes.push({
1259
+ path,
1260
+ code,
1261
+ staged,
1262
+ added: count?.added ?? null,
1263
+ removed: count?.removed ?? null,
1264
+ ...oldPath === void 0 ? {} : { oldPath }
1265
+ });
1266
+ }
1267
+ return changes;
1268
+ }
1269
+ //#endregion
1270
+ //#region src/git/runner.ts
1271
+ /**
1272
+ * The confined way to run git: an argument array (never a shell), a timeout, an output cap, and a record
1273
+ * of every in-flight process so disposal can abort and reap them. Set `GIT_OPTIONAL_LOCKS=0` so a status
1274
+ * poll never takes the index lock an agent's own `git` call may need.
1275
+ */
1276
+ const DEFAULT_MAX_OUTPUT_BYTES = 1024 * 1024;
1277
+ const DEFAULT_TIMEOUT_MS = 1e4;
1278
+ const GLOBAL_ARGS = [
1279
+ "-c",
1280
+ "core.quotepath=false",
1281
+ "-c",
1282
+ "color.ui=false",
1283
+ "-c",
1284
+ "core.fsmonitor=false"
1285
+ ];
1286
+ function emptyResult() {
1287
+ return {
1288
+ stdout: "",
1289
+ truncated: false
1290
+ };
1291
+ }
1292
+ var GitRunner = class {
1293
+ gitPath;
1294
+ maxOutputBytes;
1295
+ timeoutMs;
1296
+ inflight = /* @__PURE__ */ new Set();
1297
+ disposed = false;
1298
+ constructor(options = {}) {
1299
+ this.gitPath = options.gitPath ?? "git";
1300
+ this.maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
1301
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1302
+ }
1303
+ /** Abort every in-flight `git` process and wait for each to exit. Later calls reject. */
1304
+ async dispose() {
1305
+ this.disposed = true;
1306
+ const pending = [...this.inflight];
1307
+ for (const entry of pending) entry.abort();
1308
+ await Promise.all(pending.map((entry) => entry.done));
1309
+ }
1310
+ async resolveDirectory(path) {
1311
+ if (typeof path !== "string" || path.length === 0 || path.includes("\0") || !isAbsolute(path)) throw new WorkspaceGitError("path must be an absolute directory", "invalid");
1312
+ let real;
1313
+ try {
1314
+ real = await realpath(path);
1315
+ if (!(await stat(real)).isDirectory()) throw new Error("not a directory");
1316
+ } catch {
1317
+ throw new WorkspaceGitError("path is not an existing directory", "invalid");
1318
+ }
1319
+ return real;
1320
+ }
1321
+ run(args, cwd, acceptExit, timeoutMs) {
1322
+ if (this.disposed) return Promise.reject(new WorkspaceGitError("git service is disposed", "failed"));
1323
+ const controller = new AbortController();
1324
+ let settle;
1325
+ const entry = {
1326
+ abort: () => {
1327
+ controller.abort();
1328
+ },
1329
+ done: new Promise((resolve) => {
1330
+ settle = resolve;
1331
+ })
1332
+ };
1333
+ this.inflight.add(entry);
1334
+ const env = {
1335
+ ...process.env,
1336
+ GIT_OPTIONAL_LOCKS: "0",
1337
+ GIT_TERMINAL_PROMPT: "0",
1338
+ GIT_PAGER: "cat",
1339
+ LC_ALL: "C"
1340
+ };
1341
+ delete env.GIT_DIR;
1342
+ delete env.GIT_WORK_TREE;
1343
+ delete env.GIT_INDEX_FILE;
1344
+ return new Promise((resolve, reject) => {
1345
+ const child = execFile(this.gitPath, [...GLOBAL_ARGS, ...args], {
1346
+ cwd,
1347
+ env,
1348
+ encoding: "utf8",
1349
+ maxBuffer: this.maxOutputBytes,
1350
+ timeout: timeoutMs ?? this.timeoutMs,
1351
+ signal: controller.signal
1352
+ }, (failure, stdout, stderr) => {
1353
+ if (failure === null) {
1354
+ resolve({
1355
+ stdout,
1356
+ truncated: false
1357
+ });
1358
+ return;
1359
+ }
1360
+ const info = failure;
1361
+ if (info.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
1362
+ resolve({
1363
+ stdout: info.stdout ?? stdout,
1364
+ truncated: true
1365
+ });
1366
+ return;
1367
+ }
1368
+ if (typeof info.code === "number" && info.code === acceptExit) {
1369
+ resolve({
1370
+ stdout,
1371
+ truncated: false
1372
+ });
1373
+ return;
1374
+ }
1375
+ if (/not a git repository/i.test(stderr)) {
1376
+ reject(new WorkspaceGitError("not a git repository", "not-repo"));
1377
+ return;
1378
+ }
1379
+ reject(new WorkspaceGitError(`git ${args[0] ?? ""} failed`, "failed"));
1380
+ });
1381
+ const finished = () => {
1382
+ this.inflight.delete(entry);
1383
+ settle();
1384
+ };
1385
+ child.once("close", finished);
1386
+ child.once("error", finished);
1387
+ });
1388
+ }
1389
+ };
1390
+ //#endregion
1391
+ //#region src/git/changes.ts
1392
+ var WorkspaceChanges = class {
1393
+ git;
1394
+ maxChanges;
1395
+ constructor(git, maxChanges) {
1396
+ this.git = git;
1397
+ this.maxChanges = maxChanges;
1398
+ }
1399
+ /**
1400
+ * Changed files in one worktree, versus HEAD.
1401
+ * @param path - absolute worktree directory.
1402
+ */
1403
+ async status(path) {
1404
+ const dir = await this.git.resolveDirectory(path);
1405
+ const [porcelain, numstat, branch] = await Promise.all([
1406
+ this.git.run([
1407
+ "status",
1408
+ "--porcelain=v1",
1409
+ "-z",
1410
+ "--untracked-files=all"
1411
+ ], dir),
1412
+ this.git.run([
1413
+ "diff",
1414
+ "--numstat",
1415
+ "-z",
1416
+ "HEAD",
1417
+ "--"
1418
+ ], dir).catch(emptyResult),
1419
+ this.git.run(["branch", "--show-current"], dir).catch(emptyResult)
1420
+ ]);
1421
+ const counts = parseNumstat(numstat.stdout);
1422
+ const all = parsePorcelain(porcelain.stdout, counts);
1423
+ const truncated = porcelain.truncated || all.length > this.maxChanges;
1424
+ const name = branch.stdout.trim();
1425
+ return {
1426
+ path: dir,
1427
+ branch: name === "" ? null : name,
1428
+ changes: all.slice(0, this.maxChanges),
1429
+ truncated
1430
+ };
1431
+ }
1432
+ /**
1433
+ * Unified diff of one file against HEAD (untracked files diff against nothing).
1434
+ * @param path - absolute worktree directory.
1435
+ * @param file - path relative to that worktree.
1436
+ */
1437
+ async diff(path, file) {
1438
+ const dir = await this.git.resolveDirectory(path);
1439
+ assertRelativeFile(file);
1440
+ const untracked = (await this.git.run([
1441
+ "ls-files",
1442
+ "--others",
1443
+ "--exclude-standard",
1444
+ "-z",
1445
+ "--",
1446
+ file
1447
+ ], dir)).stdout.length > 0;
1448
+ const flags = [
1449
+ "--no-color",
1450
+ "--no-ext-diff",
1451
+ "--no-textconv"
1452
+ ];
1453
+ let result;
1454
+ if (untracked) result = await this.git.run([
1455
+ "diff",
1456
+ "--no-index",
1457
+ ...flags,
1458
+ "--",
1459
+ "/dev/null",
1460
+ file
1461
+ ], dir, 1);
1462
+ else try {
1463
+ result = await this.git.run([
1464
+ "diff",
1465
+ ...flags,
1466
+ "HEAD",
1467
+ "--",
1468
+ file
1469
+ ], dir);
1470
+ } catch (cause) {
1471
+ if (!(cause instanceof WorkspaceGitError) || cause.kind !== "failed") throw cause;
1472
+ result = await this.git.run([
1473
+ "diff",
1474
+ "--cached",
1475
+ ...flags,
1476
+ "--",
1477
+ file
1478
+ ], dir);
1479
+ }
1480
+ const binary = /^Binary files .* differ$/m.test(result.stdout) || result.stdout.includes("GIT binary patch");
1481
+ return {
1482
+ path: dir,
1483
+ file,
1484
+ text: binary ? "" : result.stdout,
1485
+ binary,
1486
+ truncated: result.truncated
1487
+ };
1488
+ }
1489
+ /**
1490
+ * Stage files (`git add`), then report the worktree's status.
1491
+ * @param path - absolute worktree directory.
1492
+ * @param files - paths relative to that worktree.
1493
+ */
1494
+ async stage(path, files) {
1495
+ const dir = await this.git.resolveDirectory(path);
1496
+ assertFileList(files);
1497
+ await this.git.run([
1498
+ "add",
1499
+ "--",
1500
+ ...files
1501
+ ], dir);
1502
+ return this.status(dir);
1503
+ }
1504
+ /**
1505
+ * Unstage files, keeping their working-tree changes, then report the status. Works before the first commit too.
1506
+ */
1507
+ async unstage(path, files) {
1508
+ const dir = await this.git.resolveDirectory(path);
1509
+ assertFileList(files);
1510
+ try {
1511
+ await this.git.run([
1512
+ "reset",
1513
+ "-q",
1514
+ "HEAD",
1515
+ "--",
1516
+ ...files
1517
+ ], dir);
1518
+ } catch {
1519
+ await this.git.run([
1520
+ "rm",
1521
+ "--cached",
1522
+ "-r",
1523
+ "-q",
1524
+ "--",
1525
+ ...files
1526
+ ], dir);
1527
+ }
1528
+ return this.status(dir);
1529
+ }
1530
+ };
1531
+ //#endregion
1532
+ //#region src/git/checks.ts
1533
+ /** Read-only discovery of the checks a worktree can run: its package.json scripts and package manager. */
1534
+ const MAX_PACKAGE_JSON_BYTES = 256 * 1024;
1535
+ const MAX_SCRIPTS = 60;
1536
+ /** A script name is typed into a shell on the user's behalf, so only plain names are ever offered. */
1537
+ const SAFE_SCRIPT_NAME = /^[A-Za-z0-9][A-Za-z0-9:_.-]{0,63}$/;
1538
+ const PRIMARY = /^(check|verify|ci|test|tests|lint|typecheck|type-check|build|format)([:._-].*)?$/i;
1539
+ const LOCKFILES = [
1540
+ ["pnpm-lock.yaml", "pnpm"],
1541
+ ["yarn.lock", "yarn"],
1542
+ ["bun.lock", "bun"],
1543
+ ["bun.lockb", "bun"],
1544
+ ["package-lock.json", "npm"]
1545
+ ];
1546
+ async function exists(path) {
1547
+ try {
1548
+ await stat(path);
1549
+ return true;
1550
+ } catch {
1551
+ return false;
1552
+ }
1553
+ }
1554
+ /** The manager the project itself uses: its lockfile, else null (the caller then runs plain `npm`). */
1555
+ async function detectManager(dir) {
1556
+ for (const [file, manager] of LOCKFILES) if (await exists(join(dir, file))) return manager;
1557
+ return null;
1558
+ }
1559
+ /** Parse `package.json` scripts; a missing, oversized or malformed file simply means "no scripts". */
1560
+ function parseScripts(text) {
1561
+ let parsed;
1562
+ try {
1563
+ parsed = JSON.parse(text);
1564
+ } catch {
1565
+ return [];
1566
+ }
1567
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return [];
1568
+ const scripts = parsed.scripts;
1569
+ if (typeof scripts !== "object" || scripts === null || Array.isArray(scripts)) return [];
1570
+ const out = [];
1571
+ for (const [name, command] of Object.entries(scripts)) {
1572
+ if (typeof command !== "string" || !SAFE_SCRIPT_NAME.test(name)) continue;
1573
+ out.push({
1574
+ name,
1575
+ command: command.slice(0, 300),
1576
+ primary: PRIMARY.test(name)
1577
+ });
1578
+ }
1579
+ out.sort((a, b) => Number(b.primary) - Number(a.primary));
1580
+ return out.slice(0, MAX_SCRIPTS);
1581
+ }
1582
+ /** @param dir - an already validated absolute worktree directory. */
1583
+ async function readWorktreeChecks(dir) {
1584
+ let scripts = [];
1585
+ try {
1586
+ const file = join(dir, "package.json");
1587
+ if ((await stat(file)).size <= MAX_PACKAGE_JSON_BYTES) scripts = parseScripts(await readFile(file, "utf8"));
1588
+ } catch {
1589
+ scripts = [];
1590
+ }
1591
+ return {
1592
+ path: dir,
1593
+ manager: await detectManager(dir),
1594
+ scripts
1595
+ };
1596
+ }
1597
+ //#endregion
1598
+ //#region src/git/commits.ts
1599
+ const COMMIT_TIMEOUT_MS = 12e4;
1600
+ var WorkspaceCommits = class {
1601
+ git;
1602
+ changes;
1603
+ constructor(git, changes) {
1604
+ this.git = git;
1605
+ this.changes = changes;
1606
+ }
1607
+ /**
1608
+ * Commit what is staged. Refuses an empty message, nothing staged, or a missing git identity with a reason the
1609
+ * user can act on; never pushes, and never bypasses hooks.
1610
+ */
1611
+ async commit(path, message) {
1612
+ const dir = await this.git.resolveDirectory(path);
1613
+ const text = typeof message === "string" ? message.trim() : "";
1614
+ if (text === "" || text.length > 5e3 || text.includes("\0")) throw new WorkspaceGitError("write a commit message (up to 5000 characters)", "invalid");
1615
+ if ((await this.git.run([
1616
+ "diff",
1617
+ "--cached",
1618
+ "--name-only",
1619
+ "-z"
1620
+ ], dir)).stdout === "") throw new WorkspaceGitError("nothing is staged to commit", "conflict");
1621
+ try {
1622
+ await this.git.run(["var", "GIT_AUTHOR_IDENT"], dir);
1623
+ } catch {
1624
+ throw new WorkspaceGitError("git does not know who you are: set user.name and user.email first", "conflict");
1625
+ }
1626
+ try {
1627
+ await this.git.run([
1628
+ "commit",
1629
+ "-q",
1630
+ "-m",
1631
+ text
1632
+ ], dir, void 0, COMMIT_TIMEOUT_MS);
1633
+ } catch {
1634
+ throw new WorkspaceGitError("git could not commit (a commit hook may have refused it)", "conflict");
1635
+ }
1636
+ const [hash, subject] = await Promise.all([this.git.run([
1637
+ "rev-parse",
1638
+ "--short",
1639
+ "HEAD"
1640
+ ], dir), this.git.run([
1641
+ "log",
1642
+ "-1",
1643
+ "--format=%s"
1644
+ ], dir)]);
1645
+ return {
1646
+ hash: hash.stdout.trim(),
1647
+ subject: subject.stdout.trim(),
1648
+ status: await this.changes.status(dir)
1649
+ };
1650
+ }
1651
+ };
1652
+ //#endregion
1653
+ //#region src/git/ignored.ts
1654
+ /**
1655
+ * @param git - the runner.
1656
+ * @param root - absolute worktree root (its real path).
1657
+ * @param paths - entries relative to the root, `/`-separated; a directory ends in `/`, so directory-only patterns (`build/`) apply.
1658
+ * @returns the given paths git ignores; none when git cannot answer (the tree then shows everything undimmed).
1659
+ */
1660
+ async function ignoredPaths(git, root, paths) {
1661
+ if (paths.length === 0) return /* @__PURE__ */ new Set();
1662
+ try {
1663
+ const result = await git.run([
1664
+ "-c",
1665
+ "core.quotePath=false",
1666
+ "check-ignore",
1667
+ "--",
1668
+ ...paths
1669
+ ], root, 1);
1670
+ return new Set(result.stdout.split("\n").filter((path) => path !== ""));
1671
+ } catch {
1672
+ return /* @__PURE__ */ new Set();
1673
+ }
1674
+ }
1675
+ //#endregion
1676
+ //#region src/git/search.ts
1677
+ var WorkspaceSearch = class {
1678
+ git;
1679
+ constructor(git) {
1680
+ this.git = git;
1681
+ }
1682
+ /**
1683
+ * Find files by name, or lines by content, among the tracked and untracked files git does not ignore.
1684
+ * Case-insensitive and literal (the query is never a pattern), so it cannot be a regular-expression trap.
1685
+ * @param path - absolute worktree directory.
1686
+ * @param query - what to look for.
1687
+ */
1688
+ async search(path, query, mode) {
1689
+ const dir = await this.git.resolveDirectory(path);
1690
+ const text = typeof query === "string" ? query.trim() : "";
1691
+ if (text === "" || text.length > 200 || text.includes("\0") || mode !== "name" && mode !== "content") throw new WorkspaceGitError("type something to search for (up to 200 characters)", "invalid");
1692
+ if (mode === "name") {
1693
+ const listed = await this.git.run([
1694
+ "ls-files",
1695
+ "-z",
1696
+ "--cached",
1697
+ "--others",
1698
+ "--exclude-standard"
1699
+ ], dir);
1700
+ const needle = text.toLowerCase();
1701
+ const matches = listed.stdout.split("\0").filter((file) => file !== "" && file.toLowerCase().includes(needle));
1702
+ const inName = (file) => (file.split("/").pop() ?? file).toLowerCase().includes(needle);
1703
+ matches.sort((a, b) => Number(inName(b)) - Number(inName(a)) || a.length - b.length || a.localeCompare(b));
1704
+ return {
1705
+ path: dir,
1706
+ query: text,
1707
+ mode,
1708
+ hits: matches.slice(0, 200).map((file) => ({ file })),
1709
+ truncated: matches.length > 200 || listed.truncated
1710
+ };
1711
+ }
1712
+ const found = await this.git.run([
1713
+ "grep",
1714
+ "-n",
1715
+ "-I",
1716
+ "-i",
1717
+ "-F",
1718
+ "-z",
1719
+ "--untracked",
1720
+ "-e",
1721
+ text,
1722
+ "--"
1723
+ ], dir, 1);
1724
+ const hits = [];
1725
+ let truncated = found.truncated;
1726
+ for (const record of found.stdout.split("\n")) {
1727
+ if (record === "") continue;
1728
+ const [file, line, ...rest] = record.split("\0");
1729
+ if (file === void 0 || line === void 0 || !/^\d+$/.test(line)) continue;
1730
+ if (hits.length >= 200) {
1731
+ truncated = true;
1732
+ break;
1733
+ }
1734
+ hits.push({
1735
+ file,
1736
+ line: Number(line),
1737
+ text: rest.join("\0").slice(0, 300)
1738
+ });
1739
+ }
1740
+ return {
1741
+ path: dir,
1742
+ query: text,
1743
+ mode,
1744
+ hits,
1745
+ truncated
1746
+ };
1747
+ }
1748
+ };
1749
+ //#endregion
1750
+ //#region src/git/worktrees.ts
1751
+ /** Repositories and their worktrees: listing them, confirming a path is one, and creating one. */
1752
+ /** Checking out a large repository can take far longer than a status call. */
1753
+ const WORKTREE_ADD_TIMEOUT_MS = 12e4;
1754
+ async function pathExists(path) {
1755
+ try {
1756
+ await stat(path);
1757
+ return true;
1758
+ } catch {
1759
+ return false;
1760
+ }
1761
+ }
1762
+ var WorkspaceWorktrees = class {
1763
+ git;
1764
+ constructor(git) {
1765
+ this.git = git;
1766
+ }
1767
+ /**
1768
+ * List the repository's worktrees.
1769
+ * @param cwd - any directory inside the repository.
1770
+ * @returns the repository view, or null when `cwd` is not inside a git repository.
1771
+ */
1772
+ async repo(cwd) {
1773
+ const dir = await this.git.resolveDirectory(cwd);
1774
+ let current;
1775
+ try {
1776
+ current = normalize((await this.git.run(["rev-parse", "--show-toplevel"], dir)).stdout.trim());
1777
+ } catch (cause) {
1778
+ if (cause instanceof WorkspaceGitError && cause.kind === "not-repo") return null;
1779
+ throw cause;
1780
+ }
1781
+ const worktrees = parseWorktrees((await this.git.run([
1782
+ "worktree",
1783
+ "list",
1784
+ "--porcelain"
1785
+ ], dir)).stdout);
1786
+ const main = worktrees[0];
1787
+ if (main === void 0) throw new WorkspaceGitError("git listed no worktrees", "failed");
1788
+ return {
1789
+ name: basename(main.path),
1790
+ root: main.path,
1791
+ current,
1792
+ worktrees
1793
+ };
1794
+ }
1795
+ /**
1796
+ * Confirm `path` is the root of a git worktree and return its real path. The file routes use this so
1797
+ * they only ever touch a checkout, never an arbitrary directory.
1798
+ * @throws WorkspaceGitError `invalid` when the path is not a worktree root.
1799
+ */
1800
+ async worktreeRoot(path) {
1801
+ const dir = await this.git.resolveDirectory(path);
1802
+ const top = (await this.git.run(["rev-parse", "--show-toplevel"], dir)).stdout.trim();
1803
+ let real;
1804
+ try {
1805
+ real = await realpath(top);
1806
+ } catch {
1807
+ throw new WorkspaceGitError("path is not a git worktree", "invalid");
1808
+ }
1809
+ if (real !== dir) throw new WorkspaceGitError("path is not the root of a git worktree", "invalid");
1810
+ return dir;
1811
+ }
1812
+ /**
1813
+ * Create a branch and a worktree for it in the repository's sibling `<repo>.worktrees/` folder,
1814
+ * which never dirties the repository. The branch starts at the main worktree's current commit.
1815
+ * @param cwd - any directory inside the repository.
1816
+ * @param branch - the new branch name.
1817
+ */
1818
+ async createWorktree(cwd, branch) {
1819
+ assertBranchName(branch);
1820
+ const view = await this.repo(cwd);
1821
+ if (view === null) throw new WorkspaceGitError("not a git repository", "not-repo");
1822
+ try {
1823
+ await this.git.run([
1824
+ "check-ref-format",
1825
+ "--branch",
1826
+ branch
1827
+ ], view.root);
1828
+ } catch {
1829
+ throw new WorkspaceGitError("that is not a valid branch name", "invalid");
1830
+ }
1831
+ if ((await this.git.run([
1832
+ "branch",
1833
+ "--list",
1834
+ branch
1835
+ ], view.root)).stdout.trim() !== "") throw new WorkspaceGitError(`the branch ${branch} already exists`, "conflict");
1836
+ const parent = join(dirname(view.root), `${basename(view.root)}.worktrees`);
1837
+ const target = join(parent, branch.replace(/\//g, "-"));
1838
+ if (await pathExists(target)) throw new WorkspaceGitError("that worktree folder already exists", "conflict");
1839
+ await mkdir(parent, { recursive: true });
1840
+ await this.git.run([
1841
+ "worktree",
1842
+ "add",
1843
+ "-b",
1844
+ branch,
1845
+ target
1846
+ ], view.root, void 0, WORKTREE_ADD_TIMEOUT_MS);
1847
+ const path = await realpath(target);
1848
+ const after = await this.repo(path);
1849
+ if (after === null) throw new WorkspaceGitError("the new worktree is not readable", "failed");
1850
+ return {
1851
+ path,
1852
+ branch,
1853
+ repo: after
1854
+ };
1855
+ }
1856
+ };
1857
+ //#endregion
1858
+ //#region src/git/service.ts
1859
+ const DEFAULT_MAX_CHANGES = 1e3;
1860
+ var WorkspaceGit = class {
1861
+ runner;
1862
+ worktrees;
1863
+ changes;
1864
+ commits;
1865
+ searcher;
1866
+ constructor(options = {}) {
1867
+ this.runner = new GitRunner(options);
1868
+ this.worktrees = new WorkspaceWorktrees(this.runner);
1869
+ this.changes = new WorkspaceChanges(this.runner, options.maxChanges ?? DEFAULT_MAX_CHANGES);
1870
+ this.commits = new WorkspaceCommits(this.runner, this.changes);
1871
+ this.searcher = new WorkspaceSearch(this.runner);
1872
+ }
1873
+ /** The repository containing `cwd`, or null when it is not inside a git repository. */
1874
+ repo(cwd) {
1875
+ return this.worktrees.repo(cwd);
1876
+ }
1877
+ /** Confirm `path` is the root of a git worktree and return its real path. */
1878
+ worktreeRoot(path) {
1879
+ return this.worktrees.worktreeRoot(path);
1880
+ }
1881
+ /** Create a branch and a worktree for it in the repository's sibling `<repo>.worktrees/` folder. */
1882
+ createWorktree(cwd, branch) {
1883
+ return this.worktrees.createWorktree(cwd, branch);
1884
+ }
1885
+ /** Changed files in one worktree, versus HEAD. */
1886
+ status(path) {
1887
+ return this.changes.status(path);
1888
+ }
1889
+ /** Unified diff of one file against HEAD (untracked files diff against nothing). */
1890
+ diff(path, file) {
1891
+ return this.changes.diff(path, file);
1892
+ }
1893
+ /** Stage files, then report the worktree's status. */
1894
+ stage(path, files) {
1895
+ return this.changes.stage(path, files);
1896
+ }
1897
+ /** Unstage files, keeping their working-tree changes, then report the status. */
1898
+ unstage(path, files) {
1899
+ return this.changes.unstage(path, files);
1900
+ }
1901
+ /** Commit what is staged; never pushes. */
1902
+ commit(path, message) {
1903
+ return this.commits.commit(path, message);
1904
+ }
1905
+ /** Find files by name, or lines by content, literally and case-insensitively. */
1906
+ search(path, query, mode) {
1907
+ return this.searcher.search(path, query, mode);
1908
+ }
1909
+ /** Which of the given worktree-relative paths git ignores (a directory ends in `/`); none when git cannot say. */
1910
+ ignored(root, paths) {
1911
+ return ignoredPaths(this.runner, root, paths);
1912
+ }
1913
+ /** The scripts a worktree can run as checks, and its package manager. */
1914
+ async checks(path) {
1915
+ return readWorktreeChecks(await this.runner.resolveDirectory(path));
1916
+ }
1917
+ /** Abort every in-flight `git` process and wait for each to exit. Later calls reject. */
1918
+ dispose() {
1919
+ return this.runner.dispose();
1920
+ }
1921
+ };
1922
+ //#endregion
1923
+ //#region src/git/route.ts
1924
+ /** The workspace git routes: five reads, and the writes the Changes panel makes (worktree, stage, unstage, commit), for the app's own page only. */
1925
+ function required(c, name) {
1926
+ const value = c.req.query(name);
1927
+ if (value === void 0 || value.length === 0) throw new WorkspaceGitError(`missing ${name}`, "invalid");
1928
+ return value;
1929
+ }
1930
+ function parseFiles(body) {
1931
+ if (Object.keys(body).length !== 2 || typeof body.path !== "string" || !Array.isArray(body.files)) return void 0;
1932
+ if (!body.files.every((file) => typeof file === "string")) return void 0;
1933
+ return {
1934
+ path: body.path,
1935
+ files: body.files
1936
+ };
1937
+ }
1938
+ function parseWorktree(body) {
1939
+ if (Object.keys(body).length !== 2 || typeof body.cwd !== "string" || typeof body.branch !== "string") return void 0;
1940
+ return {
1941
+ cwd: body.cwd,
1942
+ branch: body.branch
1943
+ };
1944
+ }
1945
+ function parseCommit(body) {
1946
+ if (Object.keys(body).length !== 2 || typeof body.path !== "string" || typeof body.message !== "string") return void 0;
1947
+ return {
1948
+ path: body.path,
1949
+ message: body.message
1950
+ };
1951
+ }
1952
+ /**
1953
+ * GET `repo?cwd=`, `status?path=`, `checks?path=`, `search?path=&q=&mode=name|content` and `diff?path=&file=`; POST `worktree` `{ cwd, branch }`
1954
+ * (create a branch and its worktree), `stage` and `unstage` `{ path, files }`, and `commit` `{ path, message }` (never pushes).
1955
+ */
1956
+ function gitRoutes(git, reportError) {
1957
+ const answer = async (c, operation, compute) => {
1958
+ try {
1959
+ const view = await compute();
1960
+ if (view === null) return c.json(failure("not a git repository"), 404);
1961
+ return c.json(view);
1962
+ } catch (cause) {
1963
+ if (cause instanceof WorkspaceGitError) {
1964
+ if (cause.kind === "invalid") return c.json(failure(cause.message), 400);
1965
+ if (cause.kind === "conflict") return c.json(failure(cause.message), 409);
1966
+ if (cause.kind === "not-repo") return c.json(failure("not a git repository"), 404);
1967
+ }
1968
+ reportError(operation, cause);
1969
+ return c.json(failure("git request failed"), 500);
1970
+ }
1971
+ };
1972
+ /** A small JSON body, parsed strictly, then one git write answered with its result. */
1973
+ const write = (operation, invalid, parse, compute) => async (c) => {
1974
+ const body = await readJson(c);
1975
+ const input = body === INVALID_JSON || !isRecord$5(body) ? void 0 : parse(body);
1976
+ if (input === void 0) return c.json(failure(invalid), 400);
1977
+ return answer(c, operation, () => compute(input));
1978
+ };
1979
+ return new Acryl().get(WORKSPACE_GIT_REPO_PATH, ownPage, (c) => answer(c, "read git repo", async () => ({ repo: await git.repo(required(c, "cwd")) }))).get(WORKSPACE_GIT_STATUS_PATH, ownPage, (c) => answer(c, "read git status", () => git.status(required(c, "path")))).get(WORKSPACE_GIT_CHECKS_PATH, ownPage, (c) => answer(c, "read checks", () => git.checks(required(c, "path")))).get(WORKSPACE_GIT_SEARCH_PATH, ownPage, (c) => answer(c, "search", () => git.search(required(c, "path"), required(c, "q"), c.req.query("mode") === "content" ? "content" : "name"))).get(WORKSPACE_GIT_DIFF_PATH, ownPage, (c) => answer(c, "read git diff", () => git.diff(required(c, "path"), required(c, "file")))).post(WORKSPACE_GIT_WORKTREE_PATH, ownPage, jsonBody(), write("create git worktree", "invalid worktree request", parseWorktree, (input) => git.createWorktree(input.cwd, input.branch))).post(WORKSPACE_GIT_STAGE_PATH, ownPage, jsonBody(), write("stage", "invalid stage request", parseFiles, (input) => git.stage(input.path, input.files))).post(WORKSPACE_GIT_UNSTAGE_PATH, ownPage, jsonBody(), write("unstage", "invalid unstage request", parseFiles, (input) => git.unstage(input.path, input.files))).post(WORKSPACE_GIT_COMMIT_PATH, ownPage, jsonBody(), write("commit", "invalid commit request", parseCommit, (input) => git.commit(input.path, input.message)));
1980
+ }
1981
+ //#endregion
1982
+ //#region src/projects/contract.ts
1983
+ /**
1984
+ * The project registry's wire contract. A project is a folder the user added to ACRYL; ACRYL owns the list (it lives in the ACRYL home through
1985
+ * `@acryldev/settings`), and the DeepSeek Harness chat's workspaces follow it one way: a chat registers the folder it runs in when it starts, never the other
1986
+ * way round.
1987
+ */
1988
+ const WORKSPACE_PROJECTS_PATH = "/api/acryl-workspace/projects";
1989
+ /** A server-sent event stream of the registry's view: one message now, then one per change (an agent's tool call, another window). */
1990
+ const WORKSPACE_PROJECTS_EVENTS_PATH = "/api/acryl-workspace/projects/events";
1991
+ const WORKSPACE_KINDS = [
1992
+ "individual",
1993
+ "shared",
1994
+ "remote"
1995
+ ];
1996
+ /** The workspace every app has: it cannot be deleted, and the folders added before workspaces existed are its projects. */
1997
+ const DEFAULT_WORKSPACE_ID = "default";
1998
+ var ProjectRequestError = class extends Error {
1999
+ constructor(message) {
2000
+ super(message);
2001
+ this.name = "ProjectRequestError";
2002
+ }
2003
+ };
2004
+ const MAX_ADOPTED = 500;
2005
+ function isRecord(value) {
2006
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2007
+ }
2008
+ function only(record, allowed) {
2009
+ const extra = Object.keys(record).find((key) => key !== "op" && !allowed.includes(key));
2010
+ if (extra !== void 0) throw new ProjectRequestError(`unknown field "${extra}"`);
2011
+ }
2012
+ function pathOf(value) {
2013
+ if (typeof value !== "string" || value.trim() === "" || value.length > 4096) throw new ProjectRequestError("path must be the absolute path of a folder");
2014
+ return value;
2015
+ }
2016
+ /** @throws ProjectRequestError naming what is wrong; nothing is coerced. */
2017
+ function parseProjectRequest(value) {
2018
+ if (!isRecord(value) || typeof value.op !== "string") throw new ProjectRequestError("the request must be an object with an op");
2019
+ switch (value.op) {
2020
+ case "add":
2021
+ case "remove":
2022
+ only(value, ["path"]);
2023
+ return {
2024
+ op: value.op,
2025
+ path: pathOf(value.path)
2026
+ };
2027
+ case "adopt":
2028
+ only(value, ["paths"]);
2029
+ if (!Array.isArray(value.paths) || value.paths.length > MAX_ADOPTED) throw new ProjectRequestError(`paths must be a list of at most ${String(MAX_ADOPTED)} folders`);
2030
+ return {
2031
+ op: "adopt",
2032
+ paths: value.paths.map(pathOf)
2033
+ };
2034
+ case "create-workspace": {
2035
+ only(value, [
2036
+ "name",
2037
+ "kind",
2038
+ "remote"
2039
+ ]);
2040
+ if (typeof value.kind !== "string" || !WORKSPACE_KINDS.includes(value.kind)) throw new ProjectRequestError(`kind must be one of ${WORKSPACE_KINDS.join(", ")}`);
2041
+ const remote = value.remote === void 0 ? void 0 : remoteOf(value.remote);
2042
+ return {
2043
+ op: "create-workspace",
2044
+ name: textOf(value.name, "name"),
2045
+ kind: value.kind,
2046
+ ...remote === void 0 ? {} : { remote }
2047
+ };
2048
+ }
2049
+ case "switch-workspace":
2050
+ case "delete-workspace":
2051
+ only(value, ["id"]);
2052
+ return {
2053
+ op: value.op,
2054
+ id: textOf(value.id, "id")
2055
+ };
2056
+ case "rename-workspace":
2057
+ only(value, ["id", "name"]);
2058
+ return {
2059
+ op: "rename-workspace",
2060
+ id: textOf(value.id, "id"),
2061
+ name: textOf(value.name, "name")
2062
+ };
2063
+ default: throw new ProjectRequestError(`unknown op "${value.op}"`);
2064
+ }
2065
+ }
2066
+ function textOf(value, field) {
2067
+ if (typeof value !== "string" || value.length > 200) throw new ProjectRequestError(`${field} must be a short text`);
2068
+ return value;
2069
+ }
2070
+ function remoteOf(value) {
2071
+ if (!isRecord(value)) throw new ProjectRequestError("remote must be an object with a host");
2072
+ const extra = Object.keys(value).find((key) => ![
2073
+ "host",
2074
+ "user",
2075
+ "path"
2076
+ ].includes(key));
2077
+ if (extra !== void 0) throw new ProjectRequestError(`unknown remote field "${extra}"`);
2078
+ return {
2079
+ host: textOf(value.host, "remote.host"),
2080
+ ...value.user === void 0 ? {} : { user: textOf(value.user, "remote.user") },
2081
+ ...value.path === void 0 ? {} : { path: textOf(value.path, "remote.path") }
2082
+ };
2083
+ }
2084
+ //#endregion
2085
+ //#region src/projects/registry.ts
2086
+ /**
2087
+ * The project registry: the folders the user added, grouped into workspaces (spec 043), in one `@acryldev/settings` section, changed one write at a time.
2088
+ * A workspace is a named set of projects the sidebar shows as a whole; Default always exists and starts with every project added before workspaces
2089
+ * existed. A project can be in several workspaces; removing it from one never touches the others or the disk.
2090
+ */
2091
+ const PROJECTS_NAMESPACE = "workspace";
2092
+ const WorkspaceSchema = z.object({
2093
+ id: z.string().required(),
2094
+ name: z.string().required(),
2095
+ kind: z.union([
2096
+ "individual",
2097
+ "shared",
2098
+ "remote"
2099
+ ]).default("individual"),
2100
+ projects: z.array(z.string()).default([]),
2101
+ remote: z.object({
2102
+ host: z.string(),
2103
+ user: z.string(),
2104
+ path: z.string()
2105
+ })
2106
+ });
2107
+ /** The section's schema: the workspaces with their folders, the one shown, and whether the pre-existing folders were taken over. */
2108
+ const ProjectsSchema = z.object({
2109
+ projects: z.array(z.string()).default([]).description("Folders added before workspaces existed; moved into the Default workspace."),
2110
+ adopted: z.boolean().default(false).description("Projects registered before ACRYL owned the list were taken over once."),
2111
+ workspaces: z.array(WorkspaceSchema).default([]).description("Workspaces: named sets of projects, Default first."),
2112
+ current: z.string().default(DEFAULT_WORKSPACE_ID).description("The workspace the sidebar shows.")
2113
+ });
2114
+ /** A request the registry refuses (an unknown workspace, a duplicate name, deleting Default). */
2115
+ var WorkspaceError = class extends Error {
2116
+ constructor(message) {
2117
+ super(message);
2118
+ this.name = "WorkspaceError";
2119
+ }
2120
+ };
2121
+ const MAX_NAME_LENGTH = 60;
2122
+ var ProjectFolderError = class extends Error {
2123
+ constructor(message) {
2124
+ super(message);
2125
+ this.name = "ProjectFolderError";
2126
+ }
2127
+ };
2128
+ /** The canonical form of a project folder: absolute, no trailing separator. @throws ProjectFolderError for anything that is not an existing folder. */
2129
+ function normalizeProjectFolder(path) {
2130
+ if (!isAbsolute(path)) throw new ProjectFolderError(`${path} is not an absolute path`);
2131
+ const folder = resolve(path);
2132
+ let stat;
2133
+ try {
2134
+ stat = statSync(folder);
2135
+ } catch {
2136
+ throw new ProjectFolderError(`${folder} does not exist`);
2137
+ }
2138
+ if (!stat.isDirectory()) throw new ProjectFolderError(`${folder} is not a folder`);
2139
+ return folder;
2140
+ }
2141
+ var ProjectRegistry = class {
2142
+ scope;
2143
+ listeners = /* @__PURE__ */ new Set();
2144
+ constructor(scope) {
2145
+ this.scope = scope;
2146
+ }
2147
+ /** Observe every saved change, whoever made it (a page, an agent's tool). @returns disposer. */
2148
+ onChange(listener) {
2149
+ this.listeners.add(listener);
2150
+ return () => {
2151
+ this.listeners.delete(listener);
2152
+ };
2153
+ }
2154
+ view() {
2155
+ const section = this.scope.get();
2156
+ const workspaces = this.workspaces();
2157
+ const current = this.current(workspaces);
2158
+ return {
2159
+ paths: [...current.projects],
2160
+ adopted: section.adopted,
2161
+ workspaces: workspaces.map(summary),
2162
+ current: current.id
2163
+ };
2164
+ }
2165
+ /** Add a folder to the workspace shown. */
2166
+ async add(path) {
2167
+ const folder = normalizeProjectFolder(path);
2168
+ const workspaces = this.workspaces();
2169
+ const current = this.current(workspaces);
2170
+ if (current.projects.includes(folder)) return this.view();
2171
+ return this.save(workspaces.map((workspace) => workspace.id === current.id ? {
2172
+ ...workspace,
2173
+ projects: [...workspace.projects, folder]
2174
+ } : workspace), current.id);
2175
+ }
2176
+ /** Remove a folder from the workspace shown. Removing a folder that is not listed is not an error: the list is what the caller wanted. */
2177
+ async remove(path) {
2178
+ const folder = resolve(path);
2179
+ const workspaces = this.workspaces();
2180
+ const current = this.current(workspaces);
2181
+ if (!current.projects.includes(folder)) return this.view();
2182
+ return this.save(workspaces.map((workspace) => workspace.id === current.id ? {
2183
+ ...workspace,
2184
+ projects: workspace.projects.filter((candidate) => candidate !== folder)
2185
+ } : workspace), current.id);
2186
+ }
2187
+ /** Take over folders registered elsewhere, once, into Default. Folders that no longer exist are skipped, not fatal. */
2188
+ async adopt(paths) {
2189
+ if (this.scope.get().adopted) return this.view();
2190
+ const workspaces = this.workspaces();
2191
+ const merged = [...this.defaultOf(workspaces).projects];
2192
+ for (const path of paths) try {
2193
+ const folder = normalizeProjectFolder(path);
2194
+ if (!merged.includes(folder)) merged.push(folder);
2195
+ } catch {}
2196
+ return this.save(workspaces.map((workspace) => workspace.id === "default" ? {
2197
+ ...workspace,
2198
+ projects: merged
2199
+ } : workspace), this.current(workspaces).id, true);
2200
+ }
2201
+ /** Create a workspace and show it. @throws WorkspaceError for an empty or taken name, or a remote one without a host. */
2202
+ async createWorkspace(input) {
2203
+ const workspaces = this.workspaces();
2204
+ const name = this.validName(input.name, workspaces);
2205
+ const remote = input.kind === "remote" ? validRemote(input.remote) : void 0;
2206
+ const record = {
2207
+ id: `ws-${randomUUID().slice(0, 8)}`,
2208
+ name,
2209
+ kind: input.kind,
2210
+ projects: [],
2211
+ ...remote === void 0 ? {} : { remote }
2212
+ };
2213
+ return this.save([...workspaces, record], record.id);
2214
+ }
2215
+ /** Show another workspace. */
2216
+ async switchWorkspace(id) {
2217
+ const workspaces = this.workspaces();
2218
+ this.find(workspaces, id);
2219
+ return this.save(workspaces, id);
2220
+ }
2221
+ async renameWorkspace(id, name) {
2222
+ const workspaces = this.workspaces();
2223
+ this.find(workspaces, id);
2224
+ const valid = this.validName(name, workspaces.filter((workspace) => workspace.id !== id));
2225
+ return this.save(workspaces.map((workspace) => workspace.id === id ? {
2226
+ ...workspace,
2227
+ name: valid
2228
+ } : workspace), this.current(workspaces).id);
2229
+ }
2230
+ /** Delete a workspace (never Default). Its projects stay in other workspaces and on disk; the sidebar shows Default if it was shown. */
2231
+ async deleteWorkspace(id) {
2232
+ if (id === "default") throw new WorkspaceError("The Default workspace cannot be deleted.");
2233
+ const workspaces = this.workspaces();
2234
+ this.find(workspaces, id);
2235
+ const current = this.current(workspaces).id;
2236
+ return this.save(workspaces.filter((workspace) => workspace.id !== id), current === id ? DEFAULT_WORKSPACE_ID : current);
2237
+ }
2238
+ /** The workspaces, Default first; before the first workspace write, Default is built from the pre-workspace folder list. */
2239
+ workspaces() {
2240
+ const section = this.scope.get();
2241
+ const stored = section.workspaces.map(({ remote, ...workspace }) => ({
2242
+ ...workspace,
2243
+ projects: [...workspace.projects],
2244
+ ...workspace.kind === "remote" && remote !== void 0 && typeof remote.host === "string" && remote.host !== "" ? { remote } : {}
2245
+ }));
2246
+ if (stored.some((workspace) => workspace.id === "default")) return stored;
2247
+ return [{
2248
+ id: DEFAULT_WORKSPACE_ID,
2249
+ name: "Default",
2250
+ kind: "individual",
2251
+ projects: [...section.projects]
2252
+ }, ...stored];
2253
+ }
2254
+ current(workspaces) {
2255
+ const id = this.scope.get().current;
2256
+ return workspaces.find((workspace) => workspace.id === id) ?? this.defaultOf(workspaces);
2257
+ }
2258
+ defaultOf(workspaces) {
2259
+ const found = workspaces.find((workspace) => workspace.id === DEFAULT_WORKSPACE_ID);
2260
+ if (found === void 0) throw new WorkspaceError("The Default workspace is missing.");
2261
+ return found;
2262
+ }
2263
+ find(workspaces, id) {
2264
+ const found = workspaces.find((workspace) => workspace.id === id);
2265
+ if (found === void 0) throw new WorkspaceError(`There is no workspace "${id}".`);
2266
+ return found;
2267
+ }
2268
+ validName(raw, others) {
2269
+ const name = raw.trim();
2270
+ if (name === "") throw new WorkspaceError("A workspace needs a name.");
2271
+ if (name.length > MAX_NAME_LENGTH) throw new WorkspaceError(`A workspace name has at most ${String(MAX_NAME_LENGTH)} characters.`);
2272
+ if (others.some((workspace) => workspace.name.toLowerCase() === name.toLowerCase())) throw new WorkspaceError(`There is already a workspace called "${name}".`);
2273
+ return name;
2274
+ }
2275
+ /** One write: the workspaces become the only list (the pre-workspace one is emptied, its folders now in Default). */
2276
+ async save(workspaces, current, adopted) {
2277
+ await this.scope.update({
2278
+ workspaces: [...workspaces],
2279
+ current,
2280
+ projects: [],
2281
+ ...adopted === void 0 ? {} : { adopted }
2282
+ });
2283
+ const view = this.view();
2284
+ for (const listener of [...this.listeners]) listener(view);
2285
+ return view;
2286
+ }
2287
+ };
2288
+ function summary(workspace) {
2289
+ return {
2290
+ id: workspace.id,
2291
+ name: workspace.name,
2292
+ kind: workspace.kind,
2293
+ projects: [...workspace.projects],
2294
+ ...workspace.remote === void 0 ? {} : { remote: { ...workspace.remote } }
2295
+ };
2296
+ }
2297
+ function validRemote(remote) {
2298
+ const host = remote?.host.trim() ?? "";
2299
+ if (host === "") throw new WorkspaceError("A remote workspace needs the SSH host.");
2300
+ const user = remote?.user?.trim();
2301
+ const path = remote?.path?.trim();
2302
+ return {
2303
+ host,
2304
+ ...user === void 0 || user === "" ? {} : { user },
2305
+ ...path === void 0 || path === "" ? {} : { path }
2306
+ };
2307
+ }
2308
+ //#endregion
2309
+ //#region src/projects/route.ts
2310
+ /** The project registry, for the app's own page only: the list, its changes, and a stream of the list as it changes. */
2311
+ /** A comment line this often keeps an idle event stream open through proxies and the browser's own timeout. */
2312
+ const KEEP_ALIVE_MS = 25e3;
2313
+ function createKeepAlive(intervalMs = KEEP_ALIVE_MS) {
2314
+ const listeners = /* @__PURE__ */ new Set();
2315
+ const timer = setInterval(() => {
2316
+ for (const listener of listeners) listener();
2317
+ }, intervalMs);
2318
+ timer.unref();
2319
+ return {
2320
+ onBeat(listener) {
2321
+ listeners.add(listener);
2322
+ return () => {
2323
+ listeners.delete(listener);
2324
+ };
2325
+ },
2326
+ stop() {
2327
+ clearInterval(timer);
2328
+ listeners.clear();
2329
+ }
2330
+ };
2331
+ }
2332
+ function change(registry, request) {
2333
+ switch (request.op) {
2334
+ case "add": return registry.add(request.path);
2335
+ case "remove": return registry.remove(request.path);
2336
+ case "adopt": return registry.adopt(request.paths);
2337
+ case "create-workspace": return registry.createWorkspace(request);
2338
+ case "switch-workspace": return registry.switchWorkspace(request.id);
2339
+ case "rename-workspace": return registry.renameWorkspace(request.id, request.name);
2340
+ case "delete-workspace": return registry.deleteWorkspace(request.id);
2341
+ }
2342
+ }
2343
+ /**
2344
+ * GET `projects` (the list) and POST `{ op, ... }` to add, remove or adopt, a refusal being a 400 whose message says what to fix. GET
2345
+ * `projects/events` is a server-sent event stream, so every page follows a change it did not make (an agent's workspace tool, another window):
2346
+ * one `data:` message with the whole view on connect and after each change. A stream ends when its page goes away or this plugin unloads.
2347
+ */
2348
+ function projectRoutes(registry, keepAlive, reportError) {
2349
+ return new Acryl().get(WORKSPACE_PROJECTS_PATH, ownPage, (c) => c.json({
2350
+ ok: true,
2351
+ view: registry.view()
2352
+ })).post(WORKSPACE_PROJECTS_PATH, ownPage, jsonBody(), async (c) => {
2353
+ const body = await readJson(c);
2354
+ if (body === INVALID_JSON) return c.json({
2355
+ ok: false,
2356
+ code: "invalid",
2357
+ message: "invalid request body"
2358
+ }, 400);
2359
+ try {
2360
+ const view = await change(registry, parseProjectRequest(body));
2361
+ return c.json({
2362
+ ok: true,
2363
+ view
2364
+ });
2365
+ } catch (cause) {
2366
+ if (cause instanceof ProjectRequestError) return c.json({
2367
+ ok: false,
2368
+ code: "invalid",
2369
+ message: cause.message
2370
+ }, 400);
2371
+ if (cause instanceof ProjectFolderError) return c.json({
2372
+ ok: false,
2373
+ code: "not-a-folder",
2374
+ message: cause.message
2375
+ }, 400);
2376
+ if (cause instanceof WorkspaceError) return c.json({
2377
+ ok: false,
2378
+ code: "workspace",
2379
+ message: cause.message
2380
+ }, 400);
2381
+ reportError("change the project list", cause);
2382
+ return c.json(failure("the project list could not be saved"), 500);
2383
+ }
2384
+ }).get(WORKSPACE_PROJECTS_EVENTS_PATH, ownPage, (c) => streamSSE(c, async (stream) => {
2385
+ const ended = new Promise((resolve) => {
2386
+ stream.onAbort(resolve);
2387
+ });
2388
+ let queue = Promise.resolve();
2389
+ const enqueue = (write) => {
2390
+ queue = queue.then(write).catch(() => {});
2391
+ };
2392
+ const send = (view) => {
2393
+ enqueue(() => stream.writeSSE({ data: JSON.stringify(view) }));
2394
+ };
2395
+ send(registry.view());
2396
+ const stopFollowing = registry.onChange(send);
2397
+ const stopBeating = keepAlive.onBeat(() => {
2398
+ enqueue(() => stream.write(": keep-alive\n\n"));
2399
+ });
2400
+ try {
2401
+ await ended;
2402
+ } finally {
2403
+ stopBeating();
2404
+ stopFollowing();
2405
+ }
2406
+ }));
2407
+ }
2408
+ //#endregion
2409
+ //#region src/projects/tools.ts
2410
+ const WORKSPACE_LIST_TOOL = "acryl_workspace_list";
2411
+ const WORKSPACE_SWITCH_TOOL = "acryl_workspace_switch";
2412
+ const WORKSPACE_CREATE_TOOL = "acryl_workspace_create";
2413
+ const WORKSPACE_ADD_PROJECT_TOOL = "acryl_workspace_add_project";
2414
+ const WORKSPACES_SCHEMA = {
2415
+ type: "object",
2416
+ additionalProperties: false,
2417
+ properties: {
2418
+ current: {
2419
+ type: "string",
2420
+ required: true
2421
+ },
2422
+ workspaces: {
2423
+ type: "array",
2424
+ required: true,
2425
+ items: {
2426
+ type: "object",
2427
+ additionalProperties: false,
2428
+ properties: {
2429
+ id: {
2430
+ type: "string",
2431
+ required: true
2432
+ },
2433
+ name: {
2434
+ type: "string",
2435
+ required: true
2436
+ },
2437
+ kind: {
2438
+ type: "string",
2439
+ required: true
2440
+ },
2441
+ projects: {
2442
+ type: "array",
2443
+ required: true,
2444
+ items: { type: "string" }
2445
+ },
2446
+ remote: {
2447
+ type: "object",
2448
+ additionalProperties: false,
2449
+ properties: {
2450
+ host: {
2451
+ type: "string",
2452
+ required: true
2453
+ },
2454
+ user: { type: "string" },
2455
+ path: { type: "string" }
2456
+ }
2457
+ }
2458
+ }
2459
+ }
2460
+ }
2461
+ }
2462
+ };
2463
+ const value = (view) => ({
2464
+ current: view.current,
2465
+ workspaces: view.workspaces
2466
+ });
2467
+ /** What the model reads: one line per workspace, the shown one marked. */
2468
+ function renderWorkspaces(view) {
2469
+ return view.workspaces.map((workspace) => {
2470
+ const projects = workspace.projects.length === 0 ? "no projects" : workspace.projects.join(", ");
2471
+ const remote = workspace.remote === void 0 ? "" : ` (SSH ${workspace.remote.user === void 0 ? "" : `${workspace.remote.user}@`}${workspace.remote.host})`;
2472
+ return `${workspace.id === view.current ? "* " : " "}${workspace.name} [${workspace.id}, ${workspace.kind}]${remote}: ${projects}`;
2473
+ }).join("\n");
2474
+ }
2475
+ function isKind(candidate) {
2476
+ return WORKSPACE_KINDS.includes(candidate);
2477
+ }
2478
+ /** Words for the approval prompt. */
2479
+ function describeWorkspaceChange(name, args, view) {
2480
+ const a = typeof args === "object" && args !== null ? args : {};
2481
+ if (name === "acryl_workspace_create") return `Create the workspace "${String(a.name)}" (${String(a.kind ?? "individual")}) and show it`;
2482
+ const shown = view.workspaces.find((workspace) => workspace.id === view.current)?.name ?? view.current;
2483
+ return `Add the folder ${String(a.path)} to the workspace "${shown}"`;
2484
+ }
2485
+ /** Register the four tools and the approval for the two that add something. @returns disposer. */
2486
+ function registerWorkspaceTools(ctx, registry) {
2487
+ const output = {
2488
+ schema: WORKSPACES_SCHEMA,
2489
+ render: (_args, view) => [{
2490
+ type: "text",
2491
+ text: renderWorkspaces(view)
2492
+ }]
2493
+ };
2494
+ const disposers = [
2495
+ defineAcrylTool({
2496
+ name: WORKSPACE_LIST_TOOL,
2497
+ description: "List the workspaces (sets of project folders in the sidebar), their projects, and the shown one (*).",
2498
+ parameters: {},
2499
+ output,
2500
+ execute: () => value(registry.view())
2501
+ }),
2502
+ defineAcrylTool({
2503
+ name: WORKSPACE_SWITCH_TOOL,
2504
+ description: "Show another workspace by id (from acryl_workspace_list).",
2505
+ parameters: { id: {
2506
+ type: "string",
2507
+ required: true
2508
+ } },
2509
+ output,
2510
+ execute: async (args) => value(await registry.switchWorkspace(args.id))
2511
+ }),
2512
+ defineAcrylTool({
2513
+ name: WORKSPACE_CREATE_TOOL,
2514
+ description: "Create a workspace and show it. kind: individual (default), shared (projects share context) or remote (SSH: host, optional user and path).",
2515
+ parameters: {
2516
+ name: {
2517
+ type: "string",
2518
+ required: true
2519
+ },
2520
+ kind: { type: "string" },
2521
+ host: { type: "string" },
2522
+ user: { type: "string" },
2523
+ path: { type: "string" }
2524
+ },
2525
+ output,
2526
+ execute: async (args) => {
2527
+ const kind = args.kind ?? "individual";
2528
+ if (!isKind(kind)) throw new Error(`unknown workspace kind "${kind}"; use individual, shared or remote`);
2529
+ const remote = kind === "remote" ? {
2530
+ host: args.host ?? "",
2531
+ ...args.user === void 0 ? {} : { user: args.user },
2532
+ ...args.path === void 0 ? {} : { path: args.path }
2533
+ } : void 0;
2534
+ return value(await registry.createWorkspace({
2535
+ name: args.name,
2536
+ kind,
2537
+ ...remote === void 0 ? {} : { remote }
2538
+ }));
2539
+ }
2540
+ }),
2541
+ defineAcrylTool({
2542
+ name: WORKSPACE_ADD_PROJECT_TOOL,
2543
+ description: "Add a folder (absolute path) as a project of the shown workspace.",
2544
+ parameters: { path: {
2545
+ type: "string",
2546
+ required: true
2547
+ } },
2548
+ output,
2549
+ execute: async (args) => value(await registry.add(args.path))
2550
+ })
2551
+ ].map((tool) => ctx.acrylTools.register(tool));
2552
+ const removePolicy = ctx.acrylTools.policy(async (exec, next) => {
2553
+ const decision = await next();
2554
+ if (exec.name !== "acryl_workspace_create" && exec.name !== "acryl_workspace_add_project" || decision.kind === "deny") return decision;
2555
+ return {
2556
+ kind: "ask",
2557
+ reason: describeWorkspaceChange(exec.name, exec.arguments, registry.view())
2558
+ };
2559
+ });
2560
+ return () => {
2561
+ removePolicy();
2562
+ for (const dispose of disposers.reverse()) dispose();
2563
+ };
2564
+ }
2565
+ //#endregion
2566
+ //#region src/pty/node-pty-spawn.ts
2567
+ /** The adapter that starts a real process behind a terminal with node-pty (a native module). */
2568
+ const spawnNodePty = (command, args, options) => spawn$1(command, [...args], {
2569
+ cwd: options.cwd,
2570
+ env: options.env,
2571
+ name: options.name,
2572
+ cols: options.cols,
2573
+ rows: options.rows
2574
+ });
2575
+ //#endregion
2576
+ //#region src/pty/route.ts
2577
+ /** The workspace terminal routes: start, snapshot, input, resize and close, for the app's own page only. The output streams over the PTY WebSocket. */
2578
+ const START_KEYS = /* @__PURE__ */ new Set([
2579
+ "commandId",
2580
+ "cwd",
2581
+ "cols",
2582
+ "rows"
2583
+ ]);
2584
+ /**
2585
+ * GET `pty?id=` (the session's snapshot) and POST `pty` `{ commandId, cwd?, cols?, rows? }` (start one); POST `input` `{ id, data }`, `resize`
2586
+ * `{ id, cols, rows }` and `close` `{ id }` (idempotent) for a live session.
2587
+ */
2588
+ function ptyRoutes(registry, reportError) {
2589
+ return new Acryl().get(WORKSPACE_PTY_PATH, ownPage, (c) => {
2590
+ const id = c.req.query("id");
2591
+ if (id === void 0 || id.length === 0) return c.json(failure("invalid workspace PTY request"), 400);
2592
+ try {
2593
+ return c.json(registry.read(id));
2594
+ } catch (cause) {
2595
+ reportError("read workspace PTY", cause);
2596
+ return c.json(failure("unknown workspace PTY session"), 404);
2597
+ }
2598
+ }).post(WORKSPACE_PTY_PATH, ownPage, jsonBody(), async (c) => {
2599
+ const body = await readJson(c);
2600
+ if (body === INVALID_JSON || !isRecord$5(body) || Object.keys(body).some((key) => !START_KEYS.has(key)) || typeof body.commandId !== "string" || body.commandId.length === 0 || body.commandId.length > 32 || body.cwd !== void 0 && (typeof body.cwd !== "string" || body.cwd.length === 0)) return c.json(failure("invalid workspace PTY request"), 400);
2601
+ const size = typeof body.cols === "number" && typeof body.rows === "number" ? {
2602
+ cols: body.cols,
2603
+ rows: body.rows
2604
+ } : void 0;
2605
+ if ((body.cols !== void 0 || body.rows !== void 0) && size === void 0) return c.json(failure("invalid workspace PTY request"), 400);
2606
+ try {
2607
+ return c.json(await registry.start(body.commandId, body.cwd, size));
2608
+ } catch (cause) {
2609
+ reportError("start workspace PTY", cause);
2610
+ return c.json(failure(cause instanceof Error ? cause.message : "workspace PTY spawn failed"), 500);
2611
+ }
2612
+ }).post(WORKSPACE_PTY_INPUT_PATH, ownPage, jsonBody(), async (c) => {
2613
+ const body = await readJson(c);
2614
+ if (!isRecord$5(body) || typeof body.id !== "string" || typeof body.data !== "string" || Object.keys(body).length !== 2) return c.json(failure("invalid workspace PTY input"), 400);
2615
+ try {
2616
+ registry.write(body.id, body.data);
2617
+ return c.json({ accepted: true });
2618
+ } catch (cause) {
2619
+ reportError("write workspace PTY", cause);
2620
+ return c.json(failure("unknown workspace PTY session"), 404);
2621
+ }
2622
+ }).post(WORKSPACE_PTY_RESIZE_PATH, ownPage, jsonBody(), async (c) => {
2623
+ const body = await readJson(c);
2624
+ if (!isRecord$5(body) || typeof body.id !== "string" || typeof body.cols !== "number" || typeof body.rows !== "number" || !Number.isInteger(body.cols) || !Number.isInteger(body.rows) || body.cols < 2 || body.cols > 500 || body.rows < 1 || body.rows > 200 || Object.keys(body).length !== 3) return c.json(failure("invalid workspace PTY resize"), 400);
2625
+ try {
2626
+ registry.resize(body.id, body.cols, body.rows);
2627
+ return c.json({ accepted: true });
2628
+ } catch (cause) {
2629
+ reportError("resize workspace PTY", cause);
2630
+ return c.json(failure("unknown workspace PTY session"), 404);
2631
+ }
2632
+ }).post(WORKSPACE_PTY_CLOSE_PATH, ownPage, jsonBody(), async (c) => {
2633
+ const body = await readJson(c);
2634
+ if (!isRecord$5(body) || typeof body.id !== "string" || Object.keys(body).length !== 1) return c.json(failure("invalid workspace PTY close"), 400);
2635
+ try {
2636
+ await registry.close(body.id);
2637
+ return c.json({ accepted: true });
2638
+ } catch (cause) {
2639
+ reportError("close workspace PTY", cause);
2640
+ return c.json(failure("workspace PTY could not be closed"), 500);
2641
+ }
2642
+ });
2643
+ }
2644
+ //#endregion
2645
+ //#region src/agents/status/claude-hooks.ts
2646
+ /** The environment a status-reporting terminal is started with. */
2647
+ const STATUS_ENV = {
2648
+ terminal: "ACRYL_TERMINAL_ID",
2649
+ url: "ACRYL_STATUS_URL",
2650
+ token: "ACRYL_STATUS_TOKEN"
2651
+ };
2652
+ const report = (state) => `curl -fsS -m 2 -X POST "$${STATUS_ENV.url}" -H "authorization: Bearer $${STATUS_ENV.token}" -H "content-type: application/json" -d '{"terminal":"'"$${STATUS_ENV.terminal}"'","state":"${state}"}' >/dev/null 2>&1 || true`;
2653
+ const hook = (state, matcher) => [{
2654
+ ...matcher === void 0 ? {} : { matcher },
2655
+ hooks: [{
2656
+ type: "command",
2657
+ command: report(state)
2658
+ }]
2659
+ }];
2660
+ /** @returns the JSON text for `claude --settings`. */
2661
+ function claudeStatusSettings() {
2662
+ return JSON.stringify({ hooks: {
2663
+ UserPromptSubmit: hook("working"),
2664
+ PostToolUse: hook("working", "*"),
2665
+ Notification: hook("waiting"),
2666
+ Stop: hook("done")
2667
+ } });
2668
+ }
2669
+ /** The extra launch arguments for an agent that reports through hooks. */
2670
+ function statusHookArgs(kind) {
2671
+ return kind === "claude" ? ["--settings", claudeStatusSettings()] : [];
2672
+ }
2673
+ //#endregion
2674
+ //#region src/pty/scrollback.ts
2675
+ const DEFAULT_LIMIT = 1024 * 1024;
2676
+ /** After a cut, look this far for a line break so the tail does not start in the middle of a line. */
2677
+ const LINE_SEARCH = 4096;
2678
+ var Scrollback = class {
2679
+ limit;
2680
+ tail = "";
2681
+ start = 0;
2682
+ constructor(limit = DEFAULT_LIMIT) {
2683
+ this.limit = limit;
2684
+ }
2685
+ /** Total characters ever appended. */
2686
+ get cursor() {
2687
+ return this.start + this.tail.length;
2688
+ }
2689
+ append(chunk) {
2690
+ if (chunk.length === 0) return;
2691
+ this.tail += chunk;
2692
+ if (this.tail.length <= this.limit) return;
2693
+ let cut = this.tail.length - this.limit;
2694
+ const lineBreak = this.tail.indexOf("\n", cut);
2695
+ if (lineBreak !== -1 && lineBreak - cut < LINE_SEARCH) cut = lineBreak + 1;
2696
+ this.tail = this.tail.slice(cut);
2697
+ this.start += cut;
2698
+ }
2699
+ /** @param since - the cursor the client reached, or 0 for a fresh attach. */
2700
+ replay(since) {
2701
+ if (since >= this.start && since <= this.cursor) return {
2702
+ data: this.tail.slice(since - this.start),
2703
+ cursor: this.cursor,
2704
+ replace: false
2705
+ };
2706
+ return {
2707
+ data: this.tail,
2708
+ cursor: this.cursor,
2709
+ replace: true
2710
+ };
2711
+ }
2712
+ };
2713
+ //#endregion
2714
+ //#region src/pty/screen-model.ts
2715
+ /**
2716
+ * The Host's own picture of one terminal's screen.
2717
+ *
2718
+ * It is fed the same bytes the process writes, so at any moment it can say exactly what is on screen
2719
+ * (including a full-screen program's alternate screen, colours, and cursor position). A view that attaches
2720
+ * late, reconnects after a long gap, or reloads is given that picture instead of a replay of raw history,
2721
+ * which cannot reproduce a screen that was drawn by cursor movement.
2722
+ */
2723
+ const { Terminal } = headlessModule;
2724
+ const { SerializeAddon } = serializeModule;
2725
+ const SCROLLBACK_LINES = 5e3;
2726
+ var ScreenModel = class {
2727
+ terminal;
2728
+ serializer = new SerializeAddon();
2729
+ applied = 0;
2730
+ constructor(cols, rows) {
2731
+ this.terminal = new Terminal({
2732
+ cols,
2733
+ rows,
2734
+ scrollback: SCROLLBACK_LINES,
2735
+ allowProposedApi: true
2736
+ });
2737
+ this.terminal.loadAddon(this.serializer);
2738
+ }
2739
+ /** @param endCursor - the output cursor after this chunk, so a snapshot can say how far it reaches. */
2740
+ write(chunk, endCursor) {
2741
+ this.terminal.write(chunk, () => {
2742
+ this.applied = endCursor;
2743
+ });
2744
+ }
2745
+ resize(cols, rows) {
2746
+ this.terminal.resize(cols, rows);
2747
+ }
2748
+ snapshot() {
2749
+ return {
2750
+ screen: this.serializer.serialize(),
2751
+ cursor: this.applied
2752
+ };
2753
+ }
2754
+ dispose() {
2755
+ this.terminal.dispose();
2756
+ }
2757
+ };
2758
+ //#endregion
2759
+ //#region src/pty/service.ts
2760
+ /** Host-owned ACRYL Workspace PTY sessions. UI observes; this module owns lifetime. */
2761
+ const KILL_GRACE_MS = 1e3;
2762
+ const DEFAULT_COLS = 120;
2763
+ const DEFAULT_ROWS = 40;
2764
+ const PROBE_TIMEOUT_MS = 3e3;
2765
+ /** What `shell args` printed on stdout, or `undefined` when it failed, timed out or could not start. Never blocks the event loop. */
2766
+ function probe(shell, args, env) {
2767
+ return new Promise((resolve) => {
2768
+ let out = "";
2769
+ let child;
2770
+ try {
2771
+ child = spawn(shell, args, {
2772
+ env,
2773
+ stdio: [
2774
+ "ignore",
2775
+ "pipe",
2776
+ "ignore"
2777
+ ],
2778
+ timeout: PROBE_TIMEOUT_MS,
2779
+ windowsHide: true
2780
+ });
2781
+ } catch {
2782
+ resolve(void 0);
2783
+ return;
2784
+ }
2785
+ child.stdout?.setEncoding("utf8");
2786
+ child.stdout?.on("data", (chunk) => {
2787
+ out += chunk;
2788
+ });
2789
+ child.on("error", () => {
2790
+ resolve(void 0);
2791
+ });
2792
+ child.on("close", (code) => {
2793
+ resolve(code === 0 ? out : void 0);
2794
+ });
2795
+ });
2796
+ }
2797
+ async function lookUpSpawnDirs(env, platform) {
2798
+ const dirs = [];
2799
+ const add = (raw) => {
2800
+ if (raw === void 0) return;
2801
+ for (const dir of raw.split(platform === "win32" ? ";" : ":")) if (dir.length > 0 && !dirs.includes(dir)) dirs.push(dir);
2802
+ };
2803
+ add(env.PATH);
2804
+ const shell = env.SHELL ?? (platform === "win32" ? env.ComSpec ?? "cmd.exe" : "/bin/sh");
2805
+ const probes = platform === "win32" ? [[
2806
+ "/d",
2807
+ "/s",
2808
+ "/c",
2809
+ "echo %PATH%"
2810
+ ]] : [["-lic", "echo $PATH"], ["-lc", "echo $PATH"]];
2811
+ for (const args of probes) {
2812
+ const out = await probe(shell, args, env);
2813
+ if (out === void 0) continue;
2814
+ add(out.trimEnd());
2815
+ if (dirs.length > 0) break;
2816
+ }
2817
+ return Object.freeze(dirs);
2818
+ }
2819
+ /** One lookup per shell, home and PATH for the life of the process, so a reload of the plugin does not ask the shell again. */
2820
+ const spawnDirsCache = /* @__PURE__ */ new Map();
2821
+ /**
2822
+ * A Finder-launched macOS app gets a minimal PATH (`/usr/bin:/bin:…`), so a
2823
+ * bare agent name such as `claude` fails to spawn even when it is installed.
2824
+ * Resolve bare commands to an absolute executable by merging `env.PATH` with
2825
+ * the user's login-shell PATH. The login shell is asked asynchronously (an
2826
+ * interactive zsh takes about a second, which must not stall the Host), once
2827
+ * per shell, home and PATH; callers wait for the answer.
2828
+ */
2829
+ function workspacePtySpawnDirs(env, platform) {
2830
+ const key = [
2831
+ platform,
2832
+ env.SHELL ?? env.ComSpec ?? "",
2833
+ env.HOME ?? env.USERPROFILE ?? "",
2834
+ env.PATH ?? ""
2835
+ ].join("\0");
2836
+ let dirs = spawnDirsCache.get(key);
2837
+ if (dirs === void 0) {
2838
+ dirs = lookUpSpawnDirs(env, platform);
2839
+ spawnDirsCache.set(key, dirs);
2840
+ }
2841
+ return dirs;
2842
+ }
2843
+ /**
2844
+ * Return an absolute executable path for `command`, or `undefined` when none of
2845
+ * `dirs` contains an executable `command`. Absolute/relative paths pass through.
2846
+ */
2847
+ function resolveWorkspacePtyCommand(command, dirs, platform) {
2848
+ if (isAbsolute(command) || command.includes("/") || command.includes("\\")) return command;
2849
+ const names = platform === "win32" ? [
2850
+ command,
2851
+ `${command}.exe`,
2852
+ `${command}.cmd`,
2853
+ `${command}.bat`
2854
+ ] : [command];
2855
+ for (const dir of dirs) for (const name of names) try {
2856
+ const candidate = join(dir, name);
2857
+ const stat = statSync(candidate);
2858
+ if (stat.isFile() && (platform === "win32" || (stat.mode & 73) !== 0)) return candidate;
2859
+ } catch {}
2860
+ }
2861
+ /** The spawn cwd: process.cwd() when it exists, else the user's home directory. */
2862
+ function defaultSpawnCwd() {
2863
+ try {
2864
+ if (statSync(process.cwd()).isDirectory()) return process.cwd();
2865
+ } catch {}
2866
+ return homedir();
2867
+ }
2868
+ /**
2869
+ * Resolve argv for one allowlisted workspace command.
2870
+ * @param commandId - catalog id from the tab.
2871
+ * @param platform - Host process.platform.
2872
+ * @param env - environment used to pick SHELL / ComSpec.
2873
+ */
2874
+ function planWorkspacePtyCommand(commandId, platform, env) {
2875
+ if (commandId === "shell") {
2876
+ if (platform === "win32") return {
2877
+ command: env.ComSpec ?? "cmd.exe",
2878
+ args: []
2879
+ };
2880
+ return {
2881
+ command: env.SHELL ?? "/bin/sh",
2882
+ args: []
2883
+ };
2884
+ }
2885
+ return {
2886
+ command: commandId,
2887
+ args: []
2888
+ };
2889
+ }
2890
+ /**
2891
+ * The environment a terminal process starts with: a real terminal type, true color, and a UTF-8 locale
2892
+ * (an app launched from Finder has none, which makes shells and TUIs draw wrong glyphs).
2893
+ */
2894
+ function terminalEnvironment(env) {
2895
+ const locale = env.LC_ALL ?? env.LC_CTYPE ?? env.LANG;
2896
+ return {
2897
+ ...env,
2898
+ TERM: env.TERM ?? "xterm-256color",
2899
+ COLORTERM: env.COLORTERM ?? "truecolor",
2900
+ TERM_PROGRAM: "ACRYL",
2901
+ ...locale === void 0 || !/utf-?8/i.test(locale) ? { LANG: "en_US.UTF-8" } : {}
2902
+ };
2903
+ }
2904
+ function isExistingAbsoluteDirectory(path) {
2905
+ if (path.length === 0 || path.includes("\0") || !isAbsolute(path)) return false;
2906
+ try {
2907
+ return statSync(path).isDirectory();
2908
+ } catch {
2909
+ return false;
2910
+ }
2911
+ }
2912
+ /** Table of live native PTY sessions for one ACRYL Workspace Host fiber. */
2913
+ var WorkspacePtyRegistry = class {
2914
+ sessions = /* @__PURE__ */ new Map();
2915
+ spawnImpl;
2916
+ env;
2917
+ cwd;
2918
+ platform;
2919
+ createId;
2920
+ /** The search path for bare commands; the login shell's answer arrives after the registry is built (see {@link workspacePtySpawnDirs}). */
2921
+ spawnDirs;
2922
+ agents;
2923
+ agentStatus;
2924
+ launchContext;
2925
+ /** Set by {@link disposeAll}: a start still waiting for the search path then spawns nothing. */
2926
+ disposed = false;
2927
+ constructor(options) {
2928
+ this.spawnImpl = options.spawn;
2929
+ this.env = options.env ?? process.env;
2930
+ this.cwd = options.cwd ?? defaultSpawnCwd();
2931
+ this.platform = options.platform ?? process.platform;
2932
+ this.createId = options.createId ?? (() => `pty_${randomUUID()}`);
2933
+ this.spawnDirs = workspacePtySpawnDirs(this.env, this.platform);
2934
+ this.agents = options.agents;
2935
+ this.agentStatus = options.agentStatus;
2936
+ this.launchContext = options.launchContext;
2937
+ }
2938
+ /**
2939
+ * Start one allowlisted command inside a real terminal.
2940
+ * @param commandId - catalog id from the Terminal/agent tab.
2941
+ * @param cwd - optional working directory (a worktree); must be an existing absolute directory.
2942
+ */
2943
+ async start(commandId, cwd, size) {
2944
+ const known = isWorkspacePtyCommandId(commandId) ? knownAgent(commandId) : void 0;
2945
+ const agentPlan = commandId === "shell" ? void 0 : this.agents?.resolve(commandId) ?? (known === void 0 ? void 0 : {
2946
+ command: known.command,
2947
+ args: []
2948
+ });
2949
+ if (commandId !== "shell" && agentPlan === void 0) throw new Error("@acryldev/workspace: unknown workspace PTY command");
2950
+ if (cwd !== void 0 && !isExistingAbsoluteDirectory(cwd)) throw new Error("@acryldev/workspace: workspace PTY cwd must be an existing absolute directory");
2951
+ const cols = size?.cols ?? DEFAULT_COLS;
2952
+ const rows = size?.rows ?? DEFAULT_ROWS;
2953
+ if (!Number.isInteger(cols) || !Number.isInteger(rows) || cols < 2 || cols > 500 || rows < 1 || rows > 200) throw new Error("@acryldev/workspace: workspace PTY size is out of range");
2954
+ const plan = agentPlan ?? planWorkspacePtyCommand("shell", this.platform, this.env);
2955
+ const dirs = await this.spawnDirs;
2956
+ if (this.disposed) throw new Error("@acryldev/workspace: workspace PTY registry is disposed");
2957
+ const id = this.createId();
2958
+ let process;
2959
+ try {
2960
+ const resolved = resolveWorkspacePtyCommand(plan.command, dirs, this.platform);
2961
+ if (resolved === void 0 && !plan.command.includes("/") && !plan.command.includes("\\")) throw new Error(`workspace PTY command not found in PATH: ${plan.command}`);
2962
+ const reporting = plan.statusHooks !== void 0 && this.agentStatus !== void 0;
2963
+ const shared = commandId === "shell" ? void 0 : this.launchContext?.launchFor(commandId, cwd ?? this.cwd);
2964
+ const args = [
2965
+ ...reporting && plan.statusHooks !== void 0 ? statusHookArgs(plan.statusHooks) : [],
2966
+ ...shared?.args ?? [],
2967
+ ...plan.args
2968
+ ];
2969
+ const reportingEnv = reporting && this.agentStatus !== void 0 ? {
2970
+ [STATUS_ENV.terminal]: id,
2971
+ [STATUS_ENV.url]: this.agentStatus.url,
2972
+ [STATUS_ENV.token]: this.agentStatus.token
2973
+ } : {};
2974
+ process = this.spawnImpl(resolved ?? plan.command, args, {
2975
+ cwd: cwd ?? this.cwd,
2976
+ env: {
2977
+ ...terminalEnvironment(this.env),
2978
+ ...plan.env,
2979
+ ...shared?.env,
2980
+ ...reportingEnv
2981
+ },
2982
+ name: "xterm-256color",
2983
+ cols,
2984
+ rows
2985
+ });
2986
+ } catch (cause) {
2987
+ throw new Error(`@acryldev/workspace: workspace PTY spawn failed: ${cause instanceof Error ? cause.message : String(cause)}`);
2988
+ }
2989
+ const subscriptions = [];
2990
+ const session = {
2991
+ id,
2992
+ process,
2993
+ subscriptions,
2994
+ status: "running",
2995
+ scrollback: new Scrollback(),
2996
+ screen: new ScreenModel(cols, rows),
2997
+ listeners: /* @__PURE__ */ new Set(),
2998
+ exitCode: null,
2999
+ error: null
3000
+ };
3001
+ subscriptions.push(process.onData((chunk) => {
3002
+ session.scrollback.append(chunk);
3003
+ session.screen.write(chunk, session.scrollback.cursor);
3004
+ const event = {
3005
+ kind: "data",
3006
+ data: chunk,
3007
+ cursor: session.scrollback.cursor
3008
+ };
3009
+ for (const listener of [...session.listeners]) listener(event);
3010
+ }));
3011
+ subscriptions.push(process.onExit(({ exitCode, signal }) => {
3012
+ session.status = "exited";
3013
+ session.exitCode = exitCode;
3014
+ if (session.error === null && signal !== void 0 && signal !== 0) session.error = `signal ${String(signal)}`;
3015
+ const event = {
3016
+ kind: "exit",
3017
+ exitCode: session.exitCode,
3018
+ error: session.error
3019
+ };
3020
+ for (const listener of [...session.listeners]) listener(event);
3021
+ }));
3022
+ this.sessions.set(id, session);
3023
+ return this.view(session);
3024
+ }
3025
+ /** True when a live terminal has this id. */
3026
+ has(id) {
3027
+ return this.sessions.has(id);
3028
+ }
3029
+ /** True when `command` is an absolute executable file or a program on the search path. */
3030
+ async canRun(command) {
3031
+ if (isAbsolute(command)) try {
3032
+ const info = statSync(command);
3033
+ return info.isFile() && (this.platform === "win32" || (info.mode & 73) !== 0);
3034
+ } catch {
3035
+ return false;
3036
+ }
3037
+ return resolveWorkspacePtyCommand(command, await this.spawnDirs, this.platform) !== void 0;
3038
+ }
3039
+ /** Write exact terminal input bytes. */
3040
+ write(id, data) {
3041
+ const session = this.require(id);
3042
+ if (session.status !== "running") throw new Error("@acryldev/workspace: workspace PTY is not running");
3043
+ session.process.write(data);
3044
+ }
3045
+ /** Resize one live terminal. */
3046
+ resize(id, cols, rows) {
3047
+ const session = this.require(id);
3048
+ if (session.status !== "running") return;
3049
+ session.process.resize(cols, rows);
3050
+ session.screen.resize(cols, rows);
3051
+ }
3052
+ /**
3053
+ * Follow one session live. `replay` is what the subscriber has not seen yet (from `since`, or the kept
3054
+ * tail when it missed more than is kept); everything after it arrives through `listener`, in order,
3055
+ * with nothing lost or repeated in between.
3056
+ * @param since - the cursor the subscriber already reached, 0 for a first attach.
3057
+ */
3058
+ subscribe(id, since, listener) {
3059
+ const session = this.require(id);
3060
+ session.listeners.add(listener);
3061
+ return {
3062
+ replay: this.replayFor(session, since),
3063
+ status: session.status,
3064
+ exitCode: session.exitCode,
3065
+ error: session.error,
3066
+ dispose: () => {
3067
+ session.listeners.delete(listener);
3068
+ }
3069
+ };
3070
+ }
3071
+ /**
3072
+ * A subscriber that can resume from its cursor gets just what it missed. Any other (first attach,
3073
+ * reload, a gap larger than the kept tail) gets the screen as it is now, then what was written since.
3074
+ */
3075
+ replayFor(session, since) {
3076
+ if (since > 0) {
3077
+ const direct = session.scrollback.replay(since);
3078
+ if (!direct.replace) return direct;
3079
+ }
3080
+ const { screen, cursor } = session.screen.snapshot();
3081
+ const tail = session.scrollback.replay(cursor);
3082
+ return tail.replace ? tail : {
3083
+ data: screen + tail.data,
3084
+ cursor: tail.cursor,
3085
+ replace: true
3086
+ };
3087
+ }
3088
+ /** Snapshot one session for the renderer. */
3089
+ read(id) {
3090
+ return this.view(this.require(id));
3091
+ }
3092
+ /** Stop one session. Idempotent. */
3093
+ async close(id) {
3094
+ const session = this.sessions.get(id);
3095
+ if (session === void 0) return;
3096
+ await stopPty(session);
3097
+ for (const subscription of session.subscriptions) subscription.dispose();
3098
+ session.screen.dispose();
3099
+ this.sessions.delete(id);
3100
+ }
3101
+ /** Stop every session owned by this fiber. */
3102
+ async disposeAll() {
3103
+ this.disposed = true;
3104
+ const ids = [...this.sessions.keys()];
3105
+ await Promise.all(ids.map(async (id) => this.close(id)));
3106
+ }
3107
+ require(id) {
3108
+ const session = this.sessions.get(id);
3109
+ if (session === void 0) throw new Error("@acryldev/workspace: unknown workspace PTY session");
3110
+ return session;
3111
+ }
3112
+ view(session) {
3113
+ return {
3114
+ id: session.id,
3115
+ status: session.status,
3116
+ output: session.scrollback.replay(0).data,
3117
+ exitCode: session.exitCode,
3118
+ error: session.error
3119
+ };
3120
+ }
3121
+ };
3122
+ async function stopPty(session) {
3123
+ if (session.status !== "running") return;
3124
+ await new Promise((resolve) => {
3125
+ let done = false;
3126
+ const finish = () => {
3127
+ if (done) return;
3128
+ done = true;
3129
+ clearTimeout(timer);
3130
+ exitSubscription.dispose();
3131
+ resolve();
3132
+ };
3133
+ const exitSubscription = session.process.onExit(finish);
3134
+ const timer = setTimeout(() => {
3135
+ try {
3136
+ session.process.kill("SIGKILL");
3137
+ } catch {}
3138
+ finish();
3139
+ }, KILL_GRACE_MS);
3140
+ timer.unref?.();
3141
+ try {
3142
+ session.process.kill();
3143
+ } catch {
3144
+ finish();
3145
+ }
3146
+ });
3147
+ }
3148
+ //#endregion
3149
+ //#region src/pty/stream.ts
3150
+ /**
3151
+ * The live terminal stream: one WebSocket per open terminal view, on the framework's router.
3152
+ *
3153
+ * Output goes down and keystrokes and size changes go up over one ordered connection, so nothing is
3154
+ * polled, nothing is re-sent, and two keystrokes can never arrive swapped. The route is an ordinary router
3155
+ * route: the own-page rule that guards the HTTP routes runs before the upgrade, with the exact `Origin` a
3156
+ * socket must show (a WebSocket is not covered by the same-origin policy on its own), and a refusal is a
3157
+ * plain status before any handshake. The framework's hub owns the sockets: it pings them, ends dead peers,
3158
+ * and closes them with 1001 when the plugin unloads.
3159
+ */
3160
+ /** Output is sent in batches this far apart, so a burst of small writes becomes one frame. */
3161
+ const BATCH_MS = 4;
3162
+ /** When the socket already holds this much unsent data, wait instead of piling on. */
3163
+ const BACKPRESSURE_BYTES = 1024 * 1024;
3164
+ /** A client this far behind is dropped; it reconnects and resumes from its cursor. */
3165
+ const MAX_PENDING_CHARS = 8 * 1024 * 1024;
3166
+ /** A well-formed attach request: the session and the cursor its view already shows. */
3167
+ const validAttach = async (c, next) => {
3168
+ const id = c.req.query("id");
3169
+ const since = c.req.query("since") ?? "0";
3170
+ if (id === void 0 || id.length === 0 || !/^\d{1,15}$/.test(since)) return c.json(failure("invalid terminal stream request"), 400);
3171
+ await next();
3172
+ };
3173
+ /** One open view of session `id`, from cursor `since`: the replay, then live output; its input is written to the session. */
3174
+ function attach(registry, id, since) {
3175
+ let subscription;
3176
+ let pending = "";
3177
+ let pendingCursor = 0;
3178
+ let timer;
3179
+ return {
3180
+ onOpen(_event, ws) {
3181
+ const send = (message) => {
3182
+ if (ws.readyState === 1) ws.send(JSON.stringify(message));
3183
+ };
3184
+ const flush = () => {
3185
+ timer = void 0;
3186
+ if (pending === "") return;
3187
+ if (ws.bufferedAmount > BACKPRESSURE_BYTES) {
3188
+ timer = setTimeout(flush, BATCH_MS * 2);
3189
+ return;
3190
+ }
3191
+ send({
3192
+ t: "out",
3193
+ data: pending,
3194
+ cursor: pendingCursor,
3195
+ replace: false
3196
+ });
3197
+ pending = "";
3198
+ };
3199
+ try {
3200
+ subscription = registry.subscribe(id, since, (event) => {
3201
+ if (event.kind === "data") {
3202
+ pending += event.data;
3203
+ pendingCursor = event.cursor;
3204
+ if (pending.length > MAX_PENDING_CHARS) {
3205
+ ws.close(1013, "too slow");
3206
+ return;
3207
+ }
3208
+ timer ??= setTimeout(flush, BATCH_MS);
3209
+ return;
3210
+ }
3211
+ if (timer !== void 0) clearTimeout(timer);
3212
+ flush();
3213
+ send({
3214
+ t: "exit",
3215
+ exitCode: event.exitCode,
3216
+ error: event.error
3217
+ });
3218
+ });
3219
+ } catch {
3220
+ ws.close(4404, "unknown session");
3221
+ return;
3222
+ }
3223
+ const { replay } = subscription;
3224
+ if (replay.replace || replay.data.length > 0) send({
3225
+ t: "out",
3226
+ data: replay.data,
3227
+ cursor: replay.cursor,
3228
+ replace: replay.replace
3229
+ });
3230
+ if (subscription.status !== "running") send({
3231
+ t: "exit",
3232
+ exitCode: subscription.exitCode,
3233
+ error: subscription.error
3234
+ });
3235
+ },
3236
+ onMessage(event, ws) {
3237
+ if (subscription === void 0) return;
3238
+ const message = typeof event.data === "string" ? parsePtyClientMessage(event.data) : null;
3239
+ if (message === null) {
3240
+ ws.close(1008, "invalid message");
3241
+ return;
3242
+ }
3243
+ try {
3244
+ if (message.t === "in") registry.write(id, message.data);
3245
+ else registry.resize(id, message.cols, message.rows);
3246
+ } catch {}
3247
+ },
3248
+ onClose() {
3249
+ if (timer !== void 0) clearTimeout(timer);
3250
+ subscription?.dispose();
3251
+ }
3252
+ };
3253
+ }
3254
+ /**
3255
+ * GET {@link WORKSPACE_PTY_STREAM_PATH}`?id=&since=` upgraded to the session's stream. `upgrade` is the mounting plugin's
3256
+ * `ctx.routerHttp.upgrades()`, so the sockets belong to it; the path must be one the plugin mounted with `upgrade: [path]`.
3257
+ */
3258
+ function ptyStreamRoutes(registry, upgrade, reportError) {
3259
+ return new Acryl().get(WORKSPACE_PTY_STREAM_PATH, ownPageSocket, validAttach, upgrade((c) => {
3260
+ return {
3261
+ ...attach(registry, c.req.query("id") ?? "", Number(c.req.query("since") ?? "0")),
3262
+ onError: (event) => {
3263
+ reportError("terminal stream", event instanceof ErrorEvent ? event.error : event);
3264
+ }
3265
+ };
3266
+ }, {
3267
+ textOnly: true,
3268
+ onError: (cause) => {
3269
+ reportError("terminal stream", cause);
3270
+ }
3271
+ }));
3272
+ }
3273
+ //#endregion
3274
+ //#region src/shared-context/chat.ts
3275
+ const WORKSPACE_CONTEXT_NAME = "acryl:workspace";
3276
+ /** @returns the prompt block for the session's folder, or '' (no contribution) outside a Shared Context workspace. */
3277
+ function chatContextText(contextFor, assembly) {
3278
+ const cwd = assembly.agent?.session?.header?.cwd;
3279
+ return typeof cwd === "string" && cwd !== "" ? contextFor(cwd)?.prompt ?? "" : "";
3280
+ }
3281
+ /** Register the contribution. @returns disposer. */
3282
+ function registerChatContext(systemPrompt, contextFor) {
3283
+ return systemPrompt.context({
3284
+ name: WORKSPACE_CONTEXT_NAME,
3285
+ order: 130,
3286
+ text: (assembly) => chatContextText(contextFor, assembly)
3287
+ });
3288
+ }
3289
+ //#endregion
3290
+ //#region src/shared-context/launch.ts
3291
+ /**
3292
+ * How a terminal agent started in a Shared Context workspace gets the context, in its own way (spec 043 T010). Only flags each agent
3293
+ * documents and its installed `--help` lists: Claude Code gets the other projects and the workspace folder (`--add-dir`) and the context
3294
+ * (`--append-system-prompt`); Pi gets the context; Codex gets the same folders (`--add-dir`) and the context as developer instructions
3295
+ * (`-c developer_instructions=...`, Codex 0.162). Every agent gets `ACRYL_WORKSPACE_CONTEXT`, the generated document's path.
3296
+ *
3297
+ * The workspace folder holds the brief, so any agent can read it and, when asked, write a handoff into it that the next agent, of any
3298
+ * kind, is started with. That is how a session moves between agents without adapting one agent to another.
3299
+ */
3300
+ /** The environment variable naming the workspace's generated context document. */
3301
+ const WORKSPACE_CONTEXT_ENV = "ACRYL_WORKSPACE_CONTEXT";
3302
+ /** @returns the arguments and environment a known agent is started with in a shared workspace. */
3303
+ function contextLaunch(agentId, context) {
3304
+ const env = { [WORKSPACE_CONTEXT_ENV]: context.documentPath };
3305
+ const folders = [...context.otherProjects, context.workspaceFolder];
3306
+ switch (agentId) {
3307
+ case "claude": return {
3308
+ args: [
3309
+ "--add-dir",
3310
+ ...folders,
3311
+ "--append-system-prompt",
3312
+ context.prompt
3313
+ ],
3314
+ env
3315
+ };
3316
+ case "pi": return {
3317
+ args: ["--append-system-prompt", context.prompt],
3318
+ env
3319
+ };
3320
+ case "codex": return {
3321
+ args: [
3322
+ ...folders.flatMap((folder) => ["--add-dir", folder]),
3323
+ "-c",
3324
+ `developer_instructions=${JSON.stringify(context.prompt)}`
3325
+ ],
3326
+ env
3327
+ };
3328
+ default: return {
3329
+ args: [],
3330
+ env
3331
+ };
3332
+ }
3333
+ }
3334
+ //#endregion
3335
+ //#region src/shared-context/render.ts
3336
+ /** The prompt block's size, in characters (about 900 tokens). */
3337
+ const CONTEXT_PROMPT_BUDGET = 3200;
3338
+ /** The XML-style tag of the prompt block, in the style of the other ACRYL sections. */
3339
+ const CONTEXT_TAG = "acryl_workspace";
3340
+ function projectLines(projects) {
3341
+ if (projects.length === 0) return ["- (no projects yet)"];
3342
+ return projects.map((project) => `- ${project.name}: ${project.path}${project.instructions.length === 0 ? "" : ` (instructions: ${project.instructions.join(", ")})`}`);
3343
+ }
3344
+ /** The block the DSH chat and terminal agents get. The brief is cut to fit the budget, and says so. */
3345
+ function renderContextPrompt(input, budget = CONTEXT_PROMPT_BUDGET) {
3346
+ const head = [
3347
+ `<${CONTEXT_TAG}>`,
3348
+ `You work in the ACRYL workspace "${input.name}", a shared-context workspace: these projects belong together. Read and search any of them when a task crosses them; follow each project's own instructions when you work in it.`,
3349
+ "Projects:",
3350
+ ...projectLines(input.projects)
3351
+ ];
3352
+ const tail = [`Full context: ${input.documentPath}. The brief is ${input.briefPath} (the user's; edit it only when asked).`, `</${CONTEXT_TAG}>`];
3353
+ const brief = input.brief.trim();
3354
+ if (brief === "") return [...head, ...tail].join("\n");
3355
+ const room = budget - [
3356
+ ...head,
3357
+ "Brief:",
3358
+ ...tail
3359
+ ].join("\n").length - 1;
3360
+ const note = "\n(brief cut here; the rest is in the file)";
3361
+ if (room <= 82) return [...head, ...tail].join("\n");
3362
+ const cut = brief.length <= room ? brief : `${brief.slice(0, room - 42).trimEnd()}${note}`;
3363
+ return [
3364
+ ...head,
3365
+ "Brief:",
3366
+ cut,
3367
+ ...tail
3368
+ ].join("\n");
3369
+ }
3370
+ /** The whole document written to `WORKSPACE.md`: the brief in full. */
3371
+ function renderContextDocument(input) {
3372
+ const brief = input.brief.trim();
3373
+ return [
3374
+ `# Workspace: ${input.name}`,
3375
+ "",
3376
+ "Generated by ACRYL for every agent working in this shared-context workspace. Do not edit: it is rewritten when the workspace changes.",
3377
+ `The brief is ${input.briefPath}.`,
3378
+ "",
3379
+ "## Projects",
3380
+ "",
3381
+ ...projectLines(input.projects),
3382
+ "",
3383
+ "## Brief",
3384
+ "",
3385
+ brief === "" ? "(none yet)" : brief,
3386
+ ""
3387
+ ].join("\n");
3388
+ }
3389
+ //#endregion
3390
+ //#region src/shared-context/service.ts
3391
+ /**
3392
+ * `SharedContext`: which Shared Context workspace a folder works in, and what an agent there is told (spec 043 T009). It keeps
3393
+ * `<home>/workspaces/<id>/WORKSPACE.md` current for every shared workspace and holds each workspace's brief (`BRIEF.md`, the user's).
3394
+ * Provided as the `acrylSharedContext` service, so another mechanism can replace it (FR-005).
3395
+ */
3396
+ /** The service name other plugins read. */
3397
+ const SHARED_CONTEXT_SERVICE = "acrylSharedContext";
3398
+ /** A brief longer than this is refused: it is a page of notes, not a store. */
3399
+ const MAX_BRIEF_CHARS = 1e5;
3400
+ const INSTRUCTION_FILES = [
3401
+ "CLAUDE.md",
3402
+ "AGENTS.md",
3403
+ "README.md"
3404
+ ];
3405
+ /** `path` is `folder` or below it, with either separator. */
3406
+ function isInside(path, folder) {
3407
+ if (path === folder) return true;
3408
+ const base = folder.replace(/[\\/]+$/u, "");
3409
+ return path.startsWith(`${base}/`) || path.startsWith(`${base}\\`);
3410
+ }
3411
+ /**
3412
+ * The checkout a folder belongs to: the nearest folder above it with `.git`; for a linked worktree (`.git` is a file pointing into
3413
+ * `<main>/.git/worktrees/<name>`), the main checkout. Synchronous and git-free, so a prompt provider can call it. The main checkout is spelled
3414
+ * the way git wrote it (on Windows long names and `/`, turned into native separators here), so compare it with `samePlaceOrInside`, not as text.
3415
+ */
3416
+ function checkoutOf(folder) {
3417
+ for (let current = resolve(folder);; current = dirname(current)) {
3418
+ const marker = join(current, ".git");
3419
+ if (existsSync(marker)) {
3420
+ try {
3421
+ if (statSync(marker).isFile()) {
3422
+ const pointer = /^gitdir:\s*(.+)$/mu.exec(readFileSync(marker, "utf8"))?.[1]?.trim();
3423
+ const at = pointer?.search(/[\\/]\.git[\\/]worktrees[\\/]/u) ?? -1;
3424
+ if (pointer !== void 0 && at > 0) return resolve(pointer.slice(0, at));
3425
+ }
3426
+ } catch {}
3427
+ return current;
3428
+ }
3429
+ if (dirname(current) === current) return void 0;
3430
+ }
3431
+ }
3432
+ /** A path as the file system names it (Windows 8.3 short names, letter case and symlinks resolved); a missing path only resolved. */
3433
+ function canonical(path) {
3434
+ try {
3435
+ return realpathSync.native(path);
3436
+ } catch {
3437
+ return resolve(path);
3438
+ }
3439
+ }
3440
+ /** `path` is `folder` or below it, however each is spelled (see `canonical`). */
3441
+ function samePlaceOrInside(path, folder) {
3442
+ return isInside(path, folder) || isInside(canonical(path), canonical(folder));
3443
+ }
3444
+ var SharedContext = class {
3445
+ deps;
3446
+ constructor(deps) {
3447
+ this.deps = deps;
3448
+ }
3449
+ /** `<home>/workspaces/<id>/`. */
3450
+ folder(id) {
3451
+ return join(this.deps.home, "workspaces", id);
3452
+ }
3453
+ briefPath(id) {
3454
+ return join(this.folder(id), "BRIEF.md");
3455
+ }
3456
+ documentPath(id) {
3457
+ return join(this.folder(id), "WORKSPACE.md");
3458
+ }
3459
+ /**
3460
+ * The Shared Context workspace an agent working in `folder` belongs to: the shown workspace when it is shared and holds the folder, else
3461
+ * the first shared one that does; `undefined` in an Individual Projects workspace (nothing crosses projects there).
3462
+ */
3463
+ forFolder(folder) {
3464
+ const view = this.deps.registry.view();
3465
+ const checkout = checkoutOf(folder);
3466
+ const places = checkout === void 0 ? [folder] : [folder, checkout];
3467
+ const holds = (workspace) => workspace.kind === "shared" && workspace.projects.some((project) => places.some((place) => samePlaceOrInside(place, project)));
3468
+ const shown = view.workspaces.find((workspace) => workspace.id === view.current);
3469
+ if (shown !== void 0 && holds(shown)) return shown;
3470
+ return view.workspaces.find(holds);
3471
+ }
3472
+ /** What an agent working in `folder` is told, or `undefined` outside a Shared Context workspace. */
3473
+ contextFor(folder) {
3474
+ const workspace = this.forFolder(folder);
3475
+ if (workspace === void 0) return void 0;
3476
+ return {
3477
+ workspace,
3478
+ prompt: renderContextPrompt(this.input(workspace)),
3479
+ documentPath: this.documentPath(workspace.id),
3480
+ otherProjects: (start) => {
3481
+ const checkout = checkoutOf(start) ?? start;
3482
+ return workspace.projects.filter((project) => !samePlaceOrInside(start, project) && !samePlaceOrInside(checkout, project));
3483
+ }
3484
+ };
3485
+ }
3486
+ /** What a terminal agent started in `cwd` is given (`WorkspacePtyRegistry`'s launch context): nothing outside a shared workspace. */
3487
+ launchFor(agentId, cwd) {
3488
+ const context = this.contextFor(cwd);
3489
+ if (context === void 0) return void 0;
3490
+ return contextLaunch(agentId, {
3491
+ prompt: context.prompt,
3492
+ documentPath: context.documentPath,
3493
+ otherProjects: context.otherProjects(cwd),
3494
+ workspaceFolder: this.folder(context.workspace.id)
3495
+ });
3496
+ }
3497
+ /** The prompt block for a workspace by id (the tool's answer), or `undefined` when it is not a shared workspace. */
3498
+ promptFor(id) {
3499
+ const workspace = this.deps.registry.view().workspaces.find((candidate) => candidate.id === id);
3500
+ return workspace?.kind === "shared" ? renderContextPrompt(this.input(workspace)) : void 0;
3501
+ }
3502
+ brief(id) {
3503
+ try {
3504
+ return readFileSync(this.briefPath(id), "utf8");
3505
+ } catch {
3506
+ return "";
3507
+ }
3508
+ }
3509
+ /** Save a workspace's brief and rewrite its document. @throws when the workspace does not exist or the brief is too long. */
3510
+ setBrief(id, text) {
3511
+ const workspace = this.deps.registry.view().workspaces.find((candidate) => candidate.id === id);
3512
+ if (workspace === void 0) throw new Error(`there is no workspace ${id}`);
3513
+ if (text.length > 1e5) throw new Error(`the brief is longer than ${String(MAX_BRIEF_CHARS)} characters`);
3514
+ writeAtomically(this.briefPath(id), text);
3515
+ if (workspace.kind === "shared") writeAtomically(this.documentPath(id), renderContextDocument(this.input(workspace)));
3516
+ }
3517
+ /** Rewrite `WORKSPACE.md` for every shared workspace. */
3518
+ writeDocuments(view = this.deps.registry.view()) {
3519
+ for (const workspace of view.workspaces) if (workspace.kind === "shared") writeAtomically(this.documentPath(workspace.id), renderContextDocument(this.input(workspace)));
3520
+ }
3521
+ /** Keep the documents current as the registry changes. @returns disposer, for one owning effect. */
3522
+ start(report) {
3523
+ const write = (view) => {
3524
+ try {
3525
+ this.writeDocuments(view);
3526
+ } catch (cause) {
3527
+ report(cause);
3528
+ }
3529
+ };
3530
+ write();
3531
+ return this.deps.registry.onChange(write);
3532
+ }
3533
+ input(workspace) {
3534
+ return {
3535
+ name: workspace.name,
3536
+ projects: workspace.projects.map((path) => ({
3537
+ name: basename(path),
3538
+ path,
3539
+ instructions: INSTRUCTION_FILES.filter((file) => existsSync(join(path, file)))
3540
+ })),
3541
+ brief: this.brief(workspace.id),
3542
+ documentPath: this.documentPath(workspace.id),
3543
+ briefPath: this.briefPath(workspace.id)
3544
+ };
3545
+ }
3546
+ };
3547
+ function writeAtomically(path, text) {
3548
+ mkdirSync(dirname(path), { recursive: true });
3549
+ const temporary = `${path}.${String(process.pid)}.tmp`;
3550
+ writeFileSync(temporary, text);
3551
+ renameSync(temporary, path);
3552
+ }
3553
+ //#endregion
3554
+ //#region src/shared-context/route.ts
3555
+ /** A workspace's brief (spec 043 T011), for the app's own page only: GET `?id=` reads it, POST `{ id, text }` saves it and rewrites the context document. */
3556
+ const WORKSPACE_BRIEF_PATH = `${WORKSPACE_API_PREFIX}/brief`;
3557
+ const ID = /^[A-Za-z0-9_-]{1,64}$/u;
3558
+ function briefRoutes(shared) {
3559
+ return new Acryl().get(WORKSPACE_BRIEF_PATH, ownPage, (c) => {
3560
+ const id = c.req.query("id") ?? "";
3561
+ if (!ID.test(id)) return c.json({
3562
+ ok: false,
3563
+ message: "a workspace id is required"
3564
+ }, 400);
3565
+ return c.json({
3566
+ ok: true,
3567
+ id,
3568
+ text: shared.brief(id)
3569
+ });
3570
+ }).post(WORKSPACE_BRIEF_PATH, ownPage, bodyLimit({
3571
+ maxSize: 401024,
3572
+ onError: (c) => c.json({
3573
+ ok: false,
3574
+ message: "the brief is too long"
3575
+ }, 413)
3576
+ }), async (c) => {
3577
+ const body = await readJson(c);
3578
+ if (body === INVALID_JSON) return c.json({
3579
+ ok: false,
3580
+ message: "invalid request body"
3581
+ }, 400);
3582
+ const { id, text } = typeof body === "object" && body !== null ? body : {};
3583
+ if (typeof id !== "string" || !ID.test(id) || typeof text !== "string") return c.json({
3584
+ ok: false,
3585
+ message: "send { id, text }"
3586
+ }, 400);
3587
+ try {
3588
+ shared.setBrief(id, text);
3589
+ return c.json({
3590
+ ok: true,
3591
+ id,
3592
+ text
3593
+ });
3594
+ } catch (cause) {
3595
+ return c.json({
3596
+ ok: false,
3597
+ message: cause instanceof Error ? cause.message : String(cause)
3598
+ }, 400);
3599
+ }
3600
+ });
3601
+ }
3602
+ //#endregion
3603
+ //#region src/shared-context/tool.ts
3604
+ const WORKSPACE_CONTEXT_TOOL = "acryl_workspace_context";
3605
+ /** @returns the value for a workspace id, the shown one by default. */
3606
+ function readWorkspaceContext(deps, id) {
3607
+ const view = deps.view();
3608
+ const workspace = id ?? view.current;
3609
+ if (!view.workspaces.some((candidate) => candidate.id === workspace)) throw new Error(`there is no workspace ${workspace}; call acryl_workspace_list`);
3610
+ const text = deps.promptFor(workspace);
3611
+ return text === void 0 ? {
3612
+ workspace,
3613
+ shared: false,
3614
+ text: "This workspace does not share context: its projects are separate."
3615
+ } : {
3616
+ workspace,
3617
+ shared: true,
3618
+ text
3619
+ };
3620
+ }
3621
+ /** @returns disposer. */
3622
+ function registerContextTool(ctx, deps) {
3623
+ return ctx.acrylTools.register(defineAcrylTool({
3624
+ name: WORKSPACE_CONTEXT_TOOL,
3625
+ description: "Read a shared-context workspace's projects and brief (default: the shown workspace).",
3626
+ parameters: { workspace: { type: "string" } },
3627
+ output: {
3628
+ schema: {
3629
+ type: "object",
3630
+ additionalProperties: false,
3631
+ properties: {
3632
+ workspace: {
3633
+ type: "string",
3634
+ required: true
3635
+ },
3636
+ shared: {
3637
+ type: "boolean",
3638
+ required: true
3639
+ },
3640
+ text: {
3641
+ type: "string",
3642
+ required: true
3643
+ }
3644
+ }
3645
+ },
3646
+ render: (_args, value) => [{
3647
+ type: "text",
3648
+ text: value.text
3649
+ }]
3650
+ },
3651
+ execute: (args) => readWorkspaceContext(deps, args.workspace)
3652
+ }));
3653
+ }
3654
+ //#endregion
3655
+ //#region src/index.ts
3656
+ /** Cordis Host plugin: ACRYL Workspace PTY table and loopback routes. */
3657
+ /** Stable Cordis plugin name. */
3658
+ const name = "acryl-workspace";
3659
+ /**
3660
+ * The routes, the terminal's WebSocket among them, are served by the router (`router`, `routerHttp`) under {@link WORKSPACE_API_PREFIX}. The
3661
+ * loopback Web server is still needed for its address (agent hooks report to it). The app instance says where this app keeps its data.
3662
+ */
3663
+ const inject = [
3664
+ "acrylWeb",
3665
+ "appInstance",
3666
+ "acrylSettings",
3667
+ "router",
3668
+ "routerHttp"
3669
+ ];
3670
+ /**
3671
+ * Activate the workspace's Host half: its services and their routes. Disabling the Loader row unmounts the routes and kills leftover PTY sessions.
3672
+ * @param ctx - Host context for this generation.
3673
+ */
3674
+ function apply(ctx, config = {}) {
3675
+ if (ctx.acrylWeb.host !== "127.0.0.1") throw new Error("@acryldev/workspace: requires a loopback Web server");
3676
+ const appPage = typeof config.appPage === "string" && config.appPage.startsWith("/") ? config.appPage : void 0;
3677
+ const rendererOrigin = `http://127.0.0.1:${String(ctx.acrylWeb.port)}`;
3678
+ const reportHostError = (operation, cause) => {
3679
+ ctx.logger.error(`@acryldev/workspace: failed to ${operation}: ${cause instanceof Error ? cause.message : String(cause)}`);
3680
+ };
3681
+ const built = {};
3682
+ ctx.effect(() => {
3683
+ let settings;
3684
+ const statusToken = randomBytes(24).toString("hex");
3685
+ let sharedContext;
3686
+ const workspacePty = new WorkspacePtyRegistry({
3687
+ spawn: spawnNodePty,
3688
+ agents: { resolve: (id) => settings?.resolve(id) },
3689
+ launchContext: { launchFor: (id, cwd) => sharedContext?.launchFor(id, cwd) },
3690
+ agentStatus: {
3691
+ url: `${rendererOrigin}${WORKSPACE_AGENT_STATUS_PATH}`,
3692
+ token: statusToken
3693
+ }
3694
+ });
3695
+ const agentStatus = new AgentStatusStore((id) => workspacePty.has(id));
3696
+ const catalog = new AgentCatalog(createFileCatalogStore(agentsFile(ctx.appInstance.home)), (command) => workspacePty.canRun(command));
3697
+ const agentSettings = new AgentSettings(createFileCatalogStore(agentSettingsFile(ctx.appInstance.home)), catalog, (command) => workspacePty.canRun(command));
3698
+ settings = agentSettings;
3699
+ catalog.load().catch(reportHostError.bind(void 0, "load custom agents"));
3700
+ agentSettings.load().catch(reportHostError.bind(void 0, "load agent settings"));
3701
+ const workspaceGit = new WorkspaceGit();
3702
+ const workspaceFiles = new WorkspaceFiles({
3703
+ resolveWorktree: async (path) => {
3704
+ try {
3705
+ return await workspaceGit.worktreeRoot(path);
3706
+ } catch (cause) {
3707
+ if (cause instanceof WorkspaceGitError && cause.kind === "invalid") throw new WorkspaceFilesError(cause.message, "invalid");
3708
+ throw cause;
3709
+ }
3710
+ },
3711
+ ignored: (root, paths) => workspaceGit.ignored(root, paths)
3712
+ });
3713
+ const releases = [];
3714
+ try {
3715
+ const projects = new ProjectRegistry(ctx.acrylSettings.register(PROJECTS_NAMESPACE, ProjectsSchema));
3716
+ const appRoot = ctx.appInstance.root;
3717
+ const first = (typeof config.openFolder === "string" && config.openFolder !== "" ? config.openFolder : void 0) ?? (typeof appRoot === "string" && projects.view().paths.length === 0 ? appRoot : void 0);
3718
+ if (first !== void 0) projects.add(first).catch((cause) => {
3719
+ reportHostError(`add ${first} as a project`, cause);
3720
+ });
3721
+ const shared = new SharedContext({
3722
+ registry: projects,
3723
+ home: ctx.appInstance.home
3724
+ });
3725
+ sharedContext = shared;
3726
+ releases.push(shared.start((cause) => {
3727
+ reportHostError("write the shared workspace context", cause);
3728
+ }));
3729
+ const withdrawSharedContext = ctx.reflect.provide(SHARED_CONTEXT_SERVICE, shared);
3730
+ releases.push(() => {
3731
+ withdrawSharedContext();
3732
+ });
3733
+ const contextFor = (folder) => sharedContext?.contextFor(folder);
3734
+ const chatContextFiber = ctx.inject(["systemPrompt"], (child) => {
3735
+ const systemPrompt = child.systemPrompt;
3736
+ child.effect(() => registerChatContext(systemPrompt, contextFor), "@acryldev/workspace: shared workspace context for the chat");
3737
+ });
3738
+ releases.push(() => {
3739
+ chatContextFiber.dispose();
3740
+ });
3741
+ const contextToolFiber = ctx.inject(["acrylTools"], (child) => {
3742
+ child.effect(() => registerContextTool(child, {
3743
+ view: () => projects.view(),
3744
+ promptFor: (id) => sharedContext?.promptFor(id)
3745
+ }), "@acryldev/workspace: workspace context tool");
3746
+ });
3747
+ releases.push(() => {
3748
+ contextToolFiber.dispose();
3749
+ });
3750
+ const toolsFiber = ctx.inject(["acrylTools"], (child) => {
3751
+ child.effect(() => registerWorkspaceTools(child, projects), "@acryldev/workspace: workspace agent tools");
3752
+ });
3753
+ releases.push(() => {
3754
+ toolsFiber.dispose();
3755
+ });
3756
+ const keepAlive = createKeepAlive();
3757
+ releases.push(() => {
3758
+ keepAlive.stop();
3759
+ });
3760
+ const services = ctx;
3761
+ const pickFolder = singleFlight(() => pickFolderNatively(process.platform));
3762
+ built.pty = workspacePty;
3763
+ built.routes = [
3764
+ ptyRoutes(workspacePty, reportHostError),
3765
+ agentRoutes(catalog, agentSettings, reportHostError),
3766
+ agentStatusRoutes(statusToken, agentStatus, reportHostError),
3767
+ capabilityRoutes(() => ({
3768
+ chat: services.get("agents") !== void 0,
3769
+ ...appPage === void 0 ? {} : { appPage },
3770
+ ...typeof appRoot === "string" ? {
3771
+ appRoot,
3772
+ appName: basename(appRoot)
3773
+ } : {}
3774
+ })),
3775
+ projectRoutes(projects, keepAlive, reportHostError),
3776
+ briefRoutes(shared),
3777
+ filesRoutes(workspaceFiles, reportHostError),
3778
+ gitRoutes(workspaceGit, reportHostError),
3779
+ pickFolderRoutes(pickFolder, reportHostError)
3780
+ ];
3781
+ } catch (cause) {
3782
+ for (const release of releases.reverse()) release();
3783
+ workspaceGit.dispose();
3784
+ throw cause;
3785
+ }
3786
+ return async () => {
3787
+ for (const release of releases.reverse()) release();
3788
+ await Promise.all([workspacePty.disposeAll(), workspaceGit.dispose()]);
3789
+ };
3790
+ }, "@acryldev/workspace: PTY table, git, files, projects and agents");
3791
+ if (built.routes === void 0 || built.pty === void 0) throw new Error("@acryldev/workspace: the routes were not built");
3792
+ const upgrade = ctx.routerHttp.upgrades();
3793
+ ctx.router.route("/", privateApi$1(...built.routes, ptyStreamRoutes(built.pty, upgrade, reportHostError)));
3794
+ ctx.routerHttp.mount(WORKSPACE_API_PREFIX, { upgrade: [WORKSPACE_PTY_STREAM_PATH] });
3795
+ }
3796
+ //#endregion
3797
+ export { apply, inject, name, registerContextTool, registerWorkspaceTools };
3798
+
3799
+ //# sourceMappingURL=index.js.map