@acryldev/workspace 0.2.0 → 0.2.2

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 (56) hide show
  1. package/lib/index.js +8 -7
  2. package/lib/index.js.map +1 -1
  3. package/package.json +7 -7
  4. package/lib/agents/argument-text.d.ts +0 -9
  5. package/lib/agents/contract.d.ts +0 -50
  6. package/lib/agents/definition.d.ts +0 -38
  7. package/lib/agents/known-agents.d.ts +0 -52
  8. package/lib/agents/launch.d.ts +0 -26
  9. package/lib/agents/preferences.d.ts +0 -40
  10. package/lib/agents/status/agent-status.d.ts +0 -38
  11. package/lib/capabilities/contract.d.ts +0 -17
  12. package/lib/files/contract.d.ts +0 -74
  13. package/lib/folder-picker/contract.d.ts +0 -9
  14. package/lib/git/contract.d.ts +0 -136
  15. package/lib/projects/contract.d.ts +0 -82
  16. package/lib/pty/contract.d.ts +0 -52
  17. /package/lib/{agents → types/agents}/catalog.d.ts +0 -0
  18. /package/lib/{agents → types/agents}/file-store.d.ts +0 -0
  19. /package/lib/{agents → types/agents}/route.d.ts +0 -0
  20. /package/lib/{agents → types/agents}/settings.d.ts +0 -0
  21. /package/lib/{agents → types/agents}/status/claude-hooks.d.ts +0 -0
  22. /package/lib/{agents → types/agents}/status/route.d.ts +0 -0
  23. /package/lib/{capabilities → types/capabilities}/route.d.ts +0 -0
  24. /package/lib/{files → types/files}/route.d.ts +0 -0
  25. /package/lib/{files → types/files}/service.d.ts +0 -0
  26. /package/lib/{folder-picker → types/folder-picker}/picker.d.ts +0 -0
  27. /package/lib/{folder-picker → types/folder-picker}/route.d.ts +0 -0
  28. /package/lib/{git → types/git}/changes.d.ts +0 -0
  29. /package/lib/{git → types/git}/checks.d.ts +0 -0
  30. /package/lib/{git → types/git}/commits.d.ts +0 -0
  31. /package/lib/{git → types/git}/errors.d.ts +0 -0
  32. /package/lib/{git → types/git}/guards.d.ts +0 -0
  33. /package/lib/{git → types/git}/ignored.d.ts +0 -0
  34. /package/lib/{git → types/git}/parsing.d.ts +0 -0
  35. /package/lib/{git → types/git}/route.d.ts +0 -0
  36. /package/lib/{git → types/git}/runner.d.ts +0 -0
  37. /package/lib/{git → types/git}/search.d.ts +0 -0
  38. /package/lib/{git → types/git}/service.d.ts +0 -0
  39. /package/lib/{git → types/git}/worktrees.d.ts +0 -0
  40. /package/lib/{index.d.ts → types/index.d.ts} +0 -0
  41. /package/lib/{private-route.d.ts → types/private-route.d.ts} +0 -0
  42. /package/lib/{projects → types/projects}/registry.d.ts +0 -0
  43. /package/lib/{projects → types/projects}/route.d.ts +0 -0
  44. /package/lib/{projects → types/projects}/tools.d.ts +0 -0
  45. /package/lib/{pty → types/pty}/node-pty-spawn.d.ts +0 -0
  46. /package/lib/{pty → types/pty}/route.d.ts +0 -0
  47. /package/lib/{pty → types/pty}/screen-model.d.ts +0 -0
  48. /package/lib/{pty → types/pty}/scrollback.d.ts +0 -0
  49. /package/lib/{pty → types/pty}/service.d.ts +0 -0
  50. /package/lib/{pty → types/pty}/stream.d.ts +0 -0
  51. /package/lib/{shared-context → types/shared-context}/chat.d.ts +0 -0
  52. /package/lib/{shared-context → types/shared-context}/launch.d.ts +0 -0
  53. /package/lib/{shared-context → types/shared-context}/render.d.ts +0 -0
  54. /package/lib/{shared-context → types/shared-context}/route.d.ts +0 -0
  55. /package/lib/{shared-context → types/shared-context}/service.d.ts +0 -0
  56. /package/lib/{shared-context → types/shared-context}/tool.d.ts +0 -0
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["privateApi","privateRoutes","isRecord","isRecord","isRecord","isRecord","isRecord","isRecord","isInside","required","isRecord","isRecord","spawnPty","isRecord","privateApi"],"sources":["../src/private-route.ts","../src/agents/known-agents.ts","../src/pty/contract.ts","../src/agents/definition.ts","../src/agents/contract.ts","../src/agents/launch.ts","../src/agents/preferences.ts","../src/agents/route.ts","../src/agents/catalog.ts","../src/agents/file-store.ts","../src/agents/settings.ts","../src/agents/status/agent-status.ts","../src/agents/status/route.ts","../src/capabilities/contract.ts","../src/capabilities/route.ts","../src/files/contract.ts","../src/files/service.ts","../src/files/route.ts","../src/folder-picker/picker.ts","../src/folder-picker/contract.ts","../src/folder-picker/route.ts","../src/git/contract.ts","../src/git/errors.ts","../src/git/guards.ts","../src/git/parsing.ts","../src/git/runner.ts","../src/git/changes.ts","../src/git/checks.ts","../src/git/commits.ts","../src/git/ignored.ts","../src/git/search.ts","../src/git/worktrees.ts","../src/git/service.ts","../src/git/route.ts","../src/projects/contract.ts","../src/projects/registry.ts","../src/projects/route.ts","../src/projects/tools.ts","../src/pty/node-pty-spawn.ts","../src/pty/route.ts","../src/agents/status/claude-hooks.ts","../src/pty/scrollback.ts","../src/pty/screen-model.ts","../src/pty/service.ts","../src/pty/stream.ts","../src/shared-context/chat.ts","../src/shared-context/launch.ts","../src/shared-context/render.ts","../src/shared-context/service.ts","../src/shared-context/route.ts","../src/shared-context/tool.ts","../src/index.ts"],"sourcesContent":["/**\n * What every workspace route shares, on the router: the private-route rules of `@acryldev/loopback-http/router` (only the app's own page\n * may call it, answers are never cached or sniffed, a JSON body is small) under the workspace's one prefix. Each domain folder builds its\n * routes with these and `index.ts` mounts them under {@link WORKSPACE_API_PREFIX}.\n */\n\nimport type { Acryl } from '@acryldev/blends'\nimport { privateApi as privateRoutes } from '@acryldev/loopback-http/router'\n\nexport { INVALID_JSON, jsonBody, ownPage, ownPageSocket, readJson, type ReportError } from '@acryldev/loopback-http/router'\n\n/** Every workspace route lives below this path; it is the one prefix the plugin mounts on the Web server. */\nexport const WORKSPACE_API_PREFIX = '/api/acryl-workspace'\n\n/** The workspace's routes as one app, the shared rules scoped to {@link WORKSPACE_API_PREFIX}. */\nexport function privateApi(...routes: readonly Acryl[]): Acryl {\n return privateRoutes(WORKSPACE_API_PREFIX, ...routes)\n}\n\nexport function failure(message: string): { readonly error: string } {\n return { error: message }\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n","/**\n * The coding agents ACRYL knows by name: what to run, which flags mean \"do not ask me\", and where to install\n * them. This is the single source for the \"+\" menu, the launcher and Settings > Agents; the closed list of\n * ids is also the Host's allowlist of what a terminal tab may start.\n *\n * The launch commands, permission flags and install pages follow the public documentation of each agent\n * (the shape of the list is inspired by Orca's agent catalog, MIT licensed).\n */\n\n/** The permission mode a launch uses. `yolo` adds the agent's own \"skip approvals\" flags; `manual` adds none. */\nexport type PermissionMode = 'yolo' | 'manual'\n\nexport interface KnownAgent {\n readonly id: string\n readonly label: string\n /** The executable looked up on PATH. */\n readonly command: string\n /** Added to a launch in `yolo` mode, one argument per entry. */\n readonly yoloArgs: readonly string[]\n /** Environment added to a launch in `yolo` mode. */\n readonly yoloEnv?: Readonly<Record<string, string>>\n /** Where the agent's install instructions live. */\n readonly homepageUrl: string\n /** How this agent reports what it is doing, when it can (hooks): its own launch settings carry the reporting. */\n readonly statusHooks?: 'claude'\n /** The letter and colour of its tab icon when no drawn mark exists. */\n readonly badge: { readonly letter: string; readonly color: string }\n}\n\nconst agent = (\n id: string, label: string, command: string, homepageUrl: string, color: string,\n yoloArgs: readonly string[] = [], yoloEnv?: Readonly<Record<string, string>>,\n): KnownAgent => ({\n id, label, command, homepageUrl, yoloArgs, ...(yoloEnv === undefined ? {} : { yoloEnv }),\n badge: { letter: [...label][0]?.toUpperCase() ?? '?', color },\n})\n\n/** In the order the lists show them. Ids of agents that shipped earlier keep their spelling. */\nexport const KNOWN_AGENTS = [\n { ...agent('claude', 'Claude', 'claude', 'https://code.claude.com/docs', '#d97757', ['--dangerously-skip-permissions']), statusHooks: 'claude' as const },\n agent('codex', 'Codex', 'codex', 'https://github.com/openai/codex', '#10a37f', ['--dangerously-bypass-approvals-and-sandbox']),\n agent('grok', 'Grok', 'grok', 'https://x.ai/cli', '#94a3b8', ['--permission-mode', 'bypassPermissions']),\n agent('copilot', 'GitHub Copilot', 'copilot', 'https://docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli', '#a78bfa', ['--yolo']),\n agent('opencode', 'OpenCode', 'opencode', 'https://opencode.ai/docs/cli/', '#94a3b8'),\n agent('ante', 'Ante', 'ante', 'https://github.com/AntigmaLabs/ante-preview', '#fb923c', ['--yolo']),\n agent('pi', 'Pi', 'pi', 'https://pi.dev', '#a78bfa'),\n agent('omp', 'OMP', 'omp', 'https://omp.sh', '#a78bfa'),\n agent('gemini', 'Gemini', 'gemini', 'https://github.com/google-gemini/gemini-cli', '#4285f4', ['--yolo']),\n agent('antigravity', 'Antigravity', 'agy', 'https://antigravity.google/docs/cli-overview', '#4285f4', ['--dangerously-skip-permissions']),\n agent('aider', 'Aider', 'aider', 'https://aider.chat/docs/', '#34d399', ['--yes-always']),\n agent('goose', 'Goose', 'goose', 'https://block.github.io/goose/docs/quickstart/', '#f59e0b', [], { GOOSE_MODE: 'auto' }),\n agent('amp', 'Amp', 'amp', 'https://ampcode.com/manual#install', '#ef4444', ['--dangerously-allow-all']),\n agent('kilo', 'Kilocode', 'kilo', 'https://kilo.ai/docs/cli', '#f59e0b'),\n agent('crush', 'Charm', 'crush', 'https://github.com/charmbracelet/crush', '#a78bfa', ['--yolo']),\n agent('command-code', 'Command Code', 'command-code', 'https://commandcode.ai/docs/quickstart', '#94a3b8', ['--yolo']),\n agent('cursor', 'Cursor', 'cursor-agent', 'https://cursor.com/cli', '#94a3b8', ['--yolo']),\n agent('droid', 'Droid', 'droid', 'https://docs.factory.ai/cli/getting-started/quickstart', '#94a3b8', ['--auto', 'high']),\n agent('kimi', 'Kimi', 'kimi', 'https://www.kimi.com/code/docs/en/kimi-code-cli/getting-started.html', '#38bdf8', ['--yolo']),\n agent('mistral-vibe', 'Mistral Vibe', 'vibe', 'https://github.com/mistralai/mistral-vibe', '#fb923c', ['--agent', 'auto-approve']),\n agent('qwen', 'Qwen Code', 'qwen', 'https://github.com/QwenLM/qwen-code', '#a78bfa', ['--approval-mode', 'yolo']),\n agent('hermes', 'Hermes', 'hermes', 'https://hermes-agent.nousresearch.com/docs/', '#94a3b8', ['--yolo']),\n agent('mimo-code', 'MiMo Code', 'mimo', 'https://mimo.xiaomi.com/coder', '#94a3b8'),\n agent('trae', 'Trae', 'traecli', 'https://docs.trae.cn/cli_get-started-with-trae-cli', '#34d399', ['--yolo']),\n agent('kiro', 'Kiro', 'kiro-cli', 'https://kiro.dev/docs/cli/', '#a78bfa', ['--trust-all-tools']),\n agent('aug', 'Auggie', 'auggie', 'https://docs.augmentcode.com/cli/overview', '#94a3b8'),\n agent('autohand', 'Autohand Code', 'autohand', 'https://github.com/autohandai/code-cli', '#94a3b8', ['--unrestricted']),\n agent('cline', 'Cline', 'cline', 'https://docs.cline.bot/cline-cli/overview', '#94a3b8', ['--auto-approve', 'true']),\n agent('codebuff', 'Codebuff', 'codebuff', 'https://www.codebuff.com/docs/help/quick-start', '#94a3b8'),\n agent('continue', 'Continue', 'cn', 'https://docs.continue.dev/guides/cli', '#94a3b8', ['--allow', '*']),\n agent('rovo', 'Rovo Dev', 'rovo', 'https://support.atlassian.com/rovo/docs/install-and-run-rovo-dev-cli-on-your-device/', '#4285f4', ['--yolo']),\n agent('devin', 'Devin', 'devin', 'https://devin.ai/cli', '#34d399', ['--permission-mode', 'bypass', '--respect-workspace-trust', 'false']),\n agent('openclaw', 'OpenClaw', 'openclaw', 'https://github.com/openclaw/openclaw', '#ef4444'),\n] as const satisfies readonly KnownAgent[]\n\nexport type KnownAgentId = (typeof KNOWN_AGENTS)[number]['id']\n\nexport const KNOWN_AGENT_IDS: readonly KnownAgentId[] = KNOWN_AGENTS.map(entry => entry.id)\n\nconst BY_ID = new Map<string, KnownAgent>(KNOWN_AGENTS.map(entry => [entry.id, entry]))\n\n/** @returns the known agent with this id, or undefined (a custom agent, the terminal, or nothing). */\nexport function knownAgent(id: string): KnownAgent | undefined {\n return BY_ID.get(id)\n}\n","/** Allowlisted ACRYL Workspace PTY commands and loopback routes. */\n\nimport { KNOWN_AGENT_IDS, type KnownAgentId } from '../agents/known-agents.ts'\n\n/** The terminal, then every agent ACRYL knows by name (`agents/known-agents.ts` owns that list). */\nexport const WORKSPACE_PTY_COMMAND_IDS = ['shell', ...KNOWN_AGENT_IDS] as const\n\nexport type WorkspacePtyCommandId = 'shell' | KnownAgentId\n\nexport const WORKSPACE_PTY_PATH = '/api/acryl-workspace/pty'\nexport const WORKSPACE_PTY_INPUT_PATH = '/api/acryl-workspace/pty/input'\nexport const WORKSPACE_PTY_RESIZE_PATH = '/api/acryl-workspace/pty/resize'\nexport const WORKSPACE_PTY_CLOSE_PATH = '/api/acryl-workspace/pty/close'\n/** WebSocket: live output down, keystrokes and size up, in order. Query: `id`, `since` (cursor already shown). */\nexport const WORKSPACE_PTY_STREAM_PATH = '/api/acryl-workspace/pty/stream'\n\nconst COMMAND_IDS = new Set<string>(WORKSPACE_PTY_COMMAND_IDS)\n\n/** @param value - unknown command id from JSON. */\nexport function isWorkspacePtyCommandId(value: unknown): value is WorkspacePtyCommandId {\n return typeof value === 'string' && COMMAND_IDS.has(value)\n}\n\nexport type WorkspacePtyStatus = 'starting' | 'running' | 'exited' | 'error'\n\nexport interface WorkspacePtyView {\n readonly id: string\n readonly status: WorkspacePtyStatus\n readonly output: string\n readonly exitCode: number | null\n readonly error: string | null\n}\n\n/** What the Host sends over the stream. */\nexport type PtyServerMessage =\n /** Output. `replace` clears the client's terminal first (it missed more than the Host kept). */\n | { readonly t: 'out'; readonly data: string; readonly cursor: number; readonly replace: boolean }\n | { readonly t: 'exit'; readonly exitCode: number | null; readonly error: string | null }\n\n/** What the client sends over the stream. */\nexport type PtyClientMessage =\n | { readonly t: 'in'; readonly data: string }\n | { readonly t: 'resize'; readonly cols: number; readonly rows: number }\n\nexport const MAX_PTY_INPUT_CHARS = 256 * 1024\nexport const MAX_PTY_COLS = 500\nexport const MAX_PTY_ROWS = 200\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** @param text - one text frame from the client; null when it is not a well-formed message. */\nexport function parsePtyClientMessage(text: string): PtyClientMessage | null {\n let value: unknown\n try {\n value = JSON.parse(text)\n } catch {\n return null\n }\n if (!isRecord(value)) return null\n if (value.t === 'in' && typeof value.data === 'string' && value.data.length <= MAX_PTY_INPUT_CHARS && Object.keys(value).length === 2) {\n return { t: 'in', data: value.data }\n }\n if (value.t === 'resize' && Object.keys(value).length === 3\n && typeof value.cols === 'number' && typeof value.rows === 'number'\n && Number.isInteger(value.cols) && Number.isInteger(value.rows)\n && value.cols >= 2 && value.cols <= MAX_PTY_COLS && value.rows >= 1 && value.rows <= MAX_PTY_ROWS) {\n return { t: 'resize', cols: value.cols, rows: value.rows }\n }\n return null\n}\n\n/** @param text - one text frame from the Host; throws on anything unexpected. */\nexport function parsePtyServerMessage(text: string): PtyServerMessage {\n const value: unknown = JSON.parse(text)\n if (isRecord(value)) {\n if (value.t === 'out' && typeof value.data === 'string' && typeof value.cursor === 'number' && typeof value.replace === 'boolean') {\n return { t: 'out', data: value.data, cursor: value.cursor, replace: value.replace }\n }\n if (value.t === 'exit' && (value.exitCode === null || typeof value.exitCode === 'number') && (value.error === null || typeof value.error === 'string')) {\n return { t: 'exit', exitCode: value.exitCode, error: value.error }\n }\n }\n throw new Error('@acryldev/workspace: invalid terminal stream message')\n}\n\n/** Any agent id the Host may be asked to start: a built-in one or one from the user's catalog. */\nexport type AgentId = string\n","/**\n * A custom coding agent: something the user added to the \"+\" menu. Pure rules, shared by the Host (which\n * enforces them) and the page (which uses the same rules to explain a refusal before asking).\n *\n * The Host starts an agent only by its id from the catalog, so what a definition may contain is the whole\n * safety story: a bare executable name or absolute path, an argument list that never goes through a shell,\n * and nothing else. See `specs/040-agentic-multiplexer-ade/design-phase-9.md`.\n */\n\nimport { WORKSPACE_PTY_COMMAND_IDS } from '../pty/contract.ts'\n\nexport const MAX_CUSTOM_AGENTS = 32\nexport const MAX_AGENT_ARGS = 16\nexport const MAX_AGENT_ARG_LENGTH = 200\nexport const MAX_AGENT_LABEL = 40\n\n/** The colours a badge may use, so a definition can never carry arbitrary CSS. */\nexport const BADGE_COLORS = ['#94a3b8', '#d97757', '#10a37f', '#4285f4', '#a78bfa', '#34d399', '#f59e0b', '#ef4444', '#38bdf8', '#fb923c'] as const\n\nexport interface AgentBadge {\n readonly letter: string\n readonly color: (typeof BADGE_COLORS)[number]\n}\n\nexport interface CustomAgent {\n readonly id: string\n readonly label: string\n /** An absolute path, or a bare executable name found on the Host's PATH. */\n readonly command: string\n /** Passed as an argument array to the process; never interpreted by a shell. */\n readonly args: readonly string[]\n readonly badge: AgentBadge\n}\n\n/** Thrown for a definition that breaks a rule; the message is fit to show the user. */\nexport class AgentDefinitionError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'AgentDefinitionError'\n }\n}\n\nconst ID_PATTERN = /^[a-z][a-z0-9-]{1,31}$/\n/** A bare name or an absolute path; no whitespace, quotes, or shell metacharacters. */\nconst COMMAND_PATTERN = /^(?:\\/[A-Za-z0-9._@+:%~\\-/]+|[A-Za-z0-9._@+-]+)$/\nconst BUILTIN = new Set<string>(WORKSPACE_PTY_COMMAND_IDS)\n\nexport function isBuiltinAgentId(id: string): boolean {\n return BUILTIN.has(id)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** @param value - untrusted JSON. @returns a command that is an absolute path or a bare program name. @throws AgentDefinitionError. */\nexport function parseAgentCommand(value: unknown): string {\n if (typeof value !== 'string' || !COMMAND_PATTERN.test(value) || value.includes('..')) {\n 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)')\n }\n return value\n}\n\n/** @param value - untrusted JSON; absent means no arguments. @throws AgentDefinitionError. */\nexport function parseAgentArgs(value: unknown): readonly string[] {\n const list = value === undefined ? [] : value\n if (!Array.isArray(list) || list.length > MAX_AGENT_ARGS\n || !list.every((arg): arg is string => typeof arg === 'string' && arg.length <= MAX_AGENT_ARG_LENGTH && !arg.includes('\\0'))) {\n throw new AgentDefinitionError(`up to ${String(MAX_AGENT_ARGS)} arguments of up to ${String(MAX_AGENT_ARG_LENGTH)} characters each`)\n }\n return list\n}\n\n/** @param value - untrusted JSON. @throws AgentDefinitionError with a user-facing message. */\nexport function parseCustomAgent(value: unknown): CustomAgent {\n if (!isRecord(value)) throw new AgentDefinitionError('an agent needs an id, a name, a command and a badge')\n const extra = Object.keys(value).filter(key => !['id', 'label', 'command', 'args', 'badge'].includes(key))\n if (extra.length > 0) throw new AgentDefinitionError(`unknown field: ${extra[0] ?? ''}`)\n const { id, label, command, args, badge } = value\n 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')\n if (isBuiltinAgentId(id)) throw new AgentDefinitionError(`\"${id}\" is a built-in agent`)\n if (typeof label !== 'string' || label.trim() === '' || [...label.trim()].length > MAX_AGENT_LABEL) throw new AgentDefinitionError(`the name must be 1 to ${String(MAX_AGENT_LABEL)} characters`)\n const commandText = parseAgentCommand(command)\n const argList = parseAgentArgs(args)\n if (!isRecord(badge) || typeof badge.letter !== 'string' || [...badge.letter].length !== 1\n || !(BADGE_COLORS as readonly unknown[]).includes(badge.color)) {\n throw new AgentDefinitionError('the badge needs one character and one of the offered colours')\n }\n return { id, label: label.trim(), command: commandText, args: argList, badge: { letter: badge.letter, color: badge.color as AgentBadge['color'] } }\n}\n","/** Loopback routes and JSON shapes for the custom agent catalog. */\n\nimport { parseCustomAgent, type CustomAgent } from './definition.ts'\n\n/** GET the catalog; POST `{ agent }` to add one. */\nexport const WORKSPACE_AGENTS_PATH = '/api/acryl-workspace/agents'\n/** POST `{ id }` to remove one. */\nexport const WORKSPACE_AGENTS_REMOVE_PATH = '/api/acryl-workspace/agents/remove'\n\nexport interface AgentsView {\n readonly agents: readonly CustomAgent[]\n}\n\n/** @param value - unknown JSON from the agents routes. */\nexport function parseAgentsView(value: unknown): AgentsView {\n if (typeof value !== 'object' || value === null || !('agents' in value) || !Array.isArray(value.agents)) {\n throw new Error('invalid agents response')\n }\n return { agents: value.agents.map(item => parseCustomAgent(item)) }\n}\n\n/** GET the settings view; POST a {@link PreferencesPatch} to change one thing. Both answer with the whole view. */\nexport const WORKSPACE_AGENT_SETTINGS_PATH = '/api/acryl-workspace/agents/settings'\n\n/** One row of Settings > Agents. */\nexport interface AgentSettingsEntry {\n readonly id: string\n readonly label: string\n readonly kind: 'known' | 'custom'\n /** The agent's install page (known agents only). */\n readonly homepageUrl: string | null\n /** The executable the agent ships with. */\n readonly defaultCommand: string\n /** What runs: the user's replacement when set, otherwise {@link defaultCommand}. */\n readonly command: string\n /** The user's extra arguments (known agents), or the definition's own arguments (custom agents). */\n readonly args: readonly string[]\n /** What the permission mode adds right now. */\n readonly permissionArgs: readonly string[]\n readonly permissionEnv: Readonly<Record<string, string>>\n readonly enabled: boolean\n /** The executable was found on this machine. */\n readonly installed: boolean\n /** The exact command line a new tab runs. */\n readonly preview: string\n /** Custom agents only: the badge chosen when it was added. */\n readonly badge: { readonly letter: string; readonly color: string } | null\n}\n\nexport interface AgentSettingsView {\n readonly permissions: 'yolo' | 'manual'\n /** `auto`, `none`, or the id of an existing agent. */\n readonly defaultAgent: string\n /** Agents that support hooks report working, waiting and done (the attention queue). */\n readonly statusHooks: boolean\n readonly agents: readonly AgentSettingsEntry[]\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nconst isStringArray = (value: unknown): value is string[] => Array.isArray(value) && value.every(item => typeof item === 'string')\n\nfunction parseEntry(value: unknown): AgentSettingsEntry {\n if (!isObject(value)) throw new Error('invalid agent settings entry')\n const { id, label, kind, homepageUrl, defaultCommand, command, args, permissionArgs, permissionEnv, enabled, installed, preview, badge } = value\n if (typeof id !== 'string' || typeof label !== 'string' || (kind !== 'known' && kind !== 'custom')\n || (homepageUrl !== null && typeof homepageUrl !== 'string') || typeof defaultCommand !== 'string' || typeof command !== 'string'\n || !isStringArray(args) || !isStringArray(permissionArgs) || !isObject(permissionEnv)\n || !Object.values(permissionEnv).every(item => typeof item === 'string')\n || typeof enabled !== 'boolean' || typeof installed !== 'boolean' || typeof preview !== 'string') {\n throw new Error('invalid agent settings entry')\n }\n const parsedBadge = isObject(badge) && typeof badge.letter === 'string' && typeof badge.color === 'string' ? { letter: badge.letter, color: badge.color } : null\n return { id, label, kind, homepageUrl, defaultCommand, command, args, permissionArgs, permissionEnv: permissionEnv as Record<string, string>, enabled, installed, preview, badge: parsedBadge }\n}\n\n/** @param value - unknown JSON from the settings route. */\nexport function parseAgentSettingsView(value: unknown): AgentSettingsView {\n if (!isObject(value) || (value.permissions !== 'yolo' && value.permissions !== 'manual') || typeof value.defaultAgent !== 'string' || typeof value.statusHooks !== 'boolean' || !Array.isArray(value.agents)) {\n throw new Error('invalid agent settings response')\n }\n return { permissions: value.permissions, defaultAgent: value.defaultAgent, statusHooks: value.statusHooks, agents: value.agents.map(parseEntry) }\n}\n","/**\n * What a terminal tab actually runs for an agent: the command, the arguments and the environment, from the\n * agent's own definition, the user's overrides and the permission mode. Pure: no disk, no process table.\n */\n\nimport type { KnownAgent, PermissionMode } from './known-agents.ts'\n\n/** What the user changed for one agent in Settings. */\nexport interface AgentOverride {\n /** Listed in the \"+\" menu. Off hides it; it can still be opened from an existing tab. */\n readonly enabled: boolean\n /** Replaces the agent's own executable (an absolute path or a bare name). */\n readonly command?: string\n /** Added after the permission flags, one argument per entry. */\n readonly args: readonly string[]\n}\n\nexport const DEFAULT_OVERRIDE: AgentOverride = { enabled: true, args: [] }\n\nexport interface AgentLaunch {\n readonly command: string\n readonly args: readonly string[]\n readonly env?: Readonly<Record<string, string>>\n /** This launch reports its state through hooks of this kind; the Host adds the reporting at start. */\n readonly statusHooks?: 'claude'\n}\n\n/** @returns the launch for a known agent: `yolo` adds the agent's own skip-approvals flags first. */\nexport function planKnownLaunch(agent: KnownAgent, override: AgentOverride, mode: PermissionMode, statusHooks = false): AgentLaunch {\n const yolo = mode === 'yolo'\n const env = yolo ? agent.yoloEnv : undefined\n return {\n command: override.command ?? agent.command,\n args: [...(yolo ? agent.yoloArgs : []), ...override.args],\n ...(env === undefined ? {} : { env }),\n ...(statusHooks && agent.statusHooks !== undefined ? { statusHooks: agent.statusHooks } : {}),\n }\n}\n\n/** The command line for a person to read, with any environment first (`GOOSE_MODE=auto goose`). */\nexport function describeLaunch(launch: AgentLaunch): string {\n const quote = (part: string): string => (/^[A-Za-z0-9._@+:%~/=,*-]+$/.test(part) ? part : JSON.stringify(part))\n const env = Object.entries(launch.env ?? {}).map(([name, value]) => `${name}=${quote(value)}`)\n return [...env, launch.command, ...launch.args].map(quote).join(' ')\n}\n","/**\n * The user's agent preferences: the permission mode, the default agent, and per-agent overrides. Pure rules for\n * reading the stored file and for applying one change at a time; the file itself is a port (`file-store.ts`).\n */\n\nimport { AgentDefinitionError, parseAgentArgs, parseAgentCommand } from './definition.ts'\nimport { DEFAULT_OVERRIDE, type AgentOverride } from './launch.ts'\nimport type { PermissionMode } from './known-agents.ts'\n\n/** `auto`: follow what was opened last. `none`: a blank terminal. Otherwise an agent id. */\nexport type DefaultAgent = string\n\nexport interface AgentPreferences {\n readonly permissions: PermissionMode\n readonly defaultAgent: DefaultAgent\n readonly overrides: Readonly<Record<string, AgentOverride>>\n /** Agents that support hooks report working, waiting and done to ACRYL (the attention queue). */\n readonly statusHooks: boolean\n}\n\n/** Manual is the default: an agent that skips approvals is something the user turns on. */\nexport const DEFAULT_PREFERENCES: AgentPreferences = { permissions: 'manual', defaultAgent: 'auto', overrides: {}, statusHooks: true }\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nconst isMode = (value: unknown): value is PermissionMode => value === 'yolo' || value === 'manual'\n\nfunction parseOverride(value: unknown): AgentOverride {\n if (!isRecord(value)) throw new AgentDefinitionError('an override is an object')\n const { enabled, command, args } = value\n if (enabled !== undefined && typeof enabled !== 'boolean') throw new AgentDefinitionError('enabled is true or false')\n return {\n enabled: enabled ?? true,\n ...(command === undefined ? {} : { command: parseAgentCommand(command) }),\n args: parseAgentArgs(args),\n }\n}\n\n/** @param value - the parsed stored JSON. A damaged file gives the defaults; one bad override is dropped. */\nexport function parseStoredPreferences(value: unknown): AgentPreferences {\n if (!isRecord(value)) return DEFAULT_PREFERENCES\n const overrides: Record<string, AgentOverride> = {}\n if (isRecord(value.overrides)) {\n for (const [id, raw] of Object.entries(value.overrides)) {\n try { overrides[id] = parseOverride(raw) } catch { /* one bad entry does not take the others down */ }\n }\n }\n return {\n permissions: isMode(value.permissions) ? value.permissions : DEFAULT_PREFERENCES.permissions,\n defaultAgent: typeof value.defaultAgent === 'string' && value.defaultAgent !== '' ? value.defaultAgent : DEFAULT_PREFERENCES.defaultAgent,\n overrides,\n statusHooks: typeof value.statusHooks === 'boolean' ? value.statusHooks : DEFAULT_PREFERENCES.statusHooks,\n }\n}\n\n/** One change from Settings. `command: null` clears the override. */\nexport interface PreferencesPatch {\n readonly permissions?: PermissionMode\n readonly defaultAgent?: DefaultAgent\n readonly statusHooks?: boolean\n readonly agent?: {\n readonly id: string\n readonly enabled?: boolean\n readonly command?: string | null\n readonly args?: readonly string[]\n }\n}\n\n/** @param value - untrusted JSON from the route. @throws AgentDefinitionError with a message fit to show. */\nexport function parsePreferencesPatch(value: unknown): PreferencesPatch {\n if (!isRecord(value)) throw new AgentDefinitionError('invalid agent settings request')\n const extra = Object.keys(value).find(key => key !== 'permissions' && key !== 'defaultAgent' && key !== 'agent' && key !== 'statusHooks')\n if (extra !== undefined) throw new AgentDefinitionError(`unknown field: ${extra}`)\n const patch: { permissions?: PermissionMode; defaultAgent?: DefaultAgent; statusHooks?: boolean; agent?: NonNullable<PreferencesPatch['agent']> } = {}\n if (value.permissions !== undefined) {\n if (!isMode(value.permissions)) throw new AgentDefinitionError('permissions is yolo or manual')\n patch.permissions = value.permissions\n }\n if (value.defaultAgent !== undefined) {\n if (typeof value.defaultAgent !== 'string' || value.defaultAgent === '' || value.defaultAgent.length > 40) throw new AgentDefinitionError('defaultAgent is auto, none or an agent id')\n patch.defaultAgent = value.defaultAgent\n }\n if (value.statusHooks !== undefined) {\n if (typeof value.statusHooks !== 'boolean') throw new AgentDefinitionError('statusHooks is true or false')\n patch.statusHooks = value.statusHooks\n }\n if (value.agent !== undefined) {\n const agent = value.agent\n if (!isRecord(agent) || typeof agent.id !== 'string' || agent.id === '' || agent.id.length > 40) throw new AgentDefinitionError('an agent change needs an id')\n const unknown = Object.keys(agent).find(key => !['id', 'enabled', 'command', 'args'].includes(key))\n if (unknown !== undefined) throw new AgentDefinitionError(`unknown field: ${unknown}`)\n if (agent.enabled !== undefined && typeof agent.enabled !== 'boolean') throw new AgentDefinitionError('enabled is true or false')\n patch.agent = {\n id: agent.id,\n ...(agent.enabled === undefined ? {} : { enabled: agent.enabled }),\n ...(agent.command === undefined ? {} : { command: agent.command === null ? null : parseAgentCommand(agent.command) }),\n ...(agent.args === undefined ? {} : { args: parseAgentArgs(agent.args) }),\n }\n }\n return patch\n}\n\n/**\n * @param current - the preferences now.\n * @param patch - one validated change.\n * @param isAgent - whether an id names an agent the Host knows (built in or custom).\n * @throws AgentDefinitionError for an unknown agent.\n */\nexport function applyPreferencesPatch(current: AgentPreferences, patch: PreferencesPatch, isAgent: (id: string) => boolean): AgentPreferences {\n let next = current\n if (patch.permissions !== undefined) next = { ...next, permissions: patch.permissions }\n if (patch.statusHooks !== undefined) next = { ...next, statusHooks: patch.statusHooks }\n if (patch.defaultAgent !== undefined) {\n if (patch.defaultAgent !== 'auto' && patch.defaultAgent !== 'none' && !isAgent(patch.defaultAgent)) throw new AgentDefinitionError(`\"${patch.defaultAgent}\" is not an agent`)\n next = { ...next, defaultAgent: patch.defaultAgent }\n }\n if (patch.agent !== undefined) {\n const { id, enabled, command, args } = patch.agent\n if (!isAgent(id)) throw new AgentDefinitionError(`\"${id}\" is not an agent`)\n const before = next.overrides[id] ?? DEFAULT_OVERRIDE\n const { command: oldCommand, ...rest } = before\n const commandPart = command === undefined ? (oldCommand === undefined ? {} : { command: oldCommand }) : command === null ? {} : { command }\n next = { ...next, overrides: { ...next.overrides, [id]: { ...rest, enabled: enabled ?? before.enabled, args: args ?? before.args, ...commandPart } } }\n }\n return next\n}\n","/** The custom agent catalog and the agent settings, for the app's own page only. */\n\nimport { Acryl } from '@acryldev/blends'\nimport { failure, isRecord, jsonBody, ownPage, readJson, type ReportError } from '../private-route.ts'\nimport type { AgentCatalog } from './catalog.ts'\nimport { WORKSPACE_AGENT_SETTINGS_PATH, WORKSPACE_AGENTS_PATH, WORKSPACE_AGENTS_REMOVE_PATH } from './contract.ts'\nimport { AgentDefinitionError } from './definition.ts'\nimport { parsePreferencesPatch } from './preferences.ts'\nimport type { AgentSettings } from './settings.ts'\n\n/**\n * 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`\n * `{ id }` (idempotent); GET `agents/settings` (with a fresh check of which programs are installed) and POST one change, answered with the whole view.\n */\nexport function agentRoutes(catalog: AgentCatalog, settings: AgentSettings, reportError: ReportError): Acryl {\n return new Acryl()\n .get(WORKSPACE_AGENTS_PATH, ownPage, c => c.json({ agents: catalog.list() }))\n .post(WORKSPACE_AGENTS_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (!isRecord(body) || Object.keys(body).length !== 1 || !('agent' in body)) return c.json(failure('invalid agent request'), 400)\n try {\n await catalog.add(body.agent)\n return c.json({ agents: catalog.list() })\n } catch (cause) {\n if (cause instanceof AgentDefinitionError) return c.json(failure(cause.message), 400)\n reportError('add agent', cause)\n return c.json(failure('the agent could not be saved'), 500)\n }\n })\n .post(WORKSPACE_AGENTS_REMOVE_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (!isRecord(body) || Object.keys(body).length !== 1 || typeof body.id !== 'string') return c.json(failure('invalid agent request'), 400)\n try {\n await catalog.remove(body.id)\n return c.json({ agents: catalog.list() })\n } catch (cause) {\n reportError('remove agent', cause)\n return c.json(failure('the agent could not be removed'), 500)\n }\n })\n .get(WORKSPACE_AGENT_SETTINGS_PATH, ownPage, async c => c.json(await settings.view()))\n .post(WORKSPACE_AGENT_SETTINGS_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n try {\n return c.json(await settings.apply(parsePreferencesPatch(body)))\n } catch (cause) {\n if (cause instanceof AgentDefinitionError) return c.json(failure(cause.message), 400)\n reportError('save agent settings', cause)\n return c.json(failure('the settings could not be saved'), 500)\n }\n })\n}\n","/**\n * The user's custom agents: the use cases (list, add, remove, resolve) over a store.\n *\n * The store and the check that a command really exists are ports, so these rules run with no disk and no\n * process table. The catalog is the only source of custom agents; a worktree can never contribute one.\n */\n\nimport type { AgentLaunch } from './launch.ts'\nimport { AgentDefinitionError, MAX_CUSTOM_AGENTS, parseCustomAgent, type CustomAgent } from './definition.ts'\n\n/** Where the definitions are kept (a file in the user's own ACRYL home). */\nexport interface CatalogStore {\n /** @returns the stored JSON text, or null when nothing was stored yet. */\n read(): Promise<string | null>\n write(text: string): Promise<void>\n}\n\n/** Answers whether a command names a real executable on this machine (it may wait for the login shell's search path). */\nexport type CommandExists = (command: string) => Promise<boolean>\n\nexport class AgentCatalog {\n private agents: readonly CustomAgent[] = []\n private loaded = false\n\n constructor(private readonly store: CatalogStore, private readonly commandExists: CommandExists) {}\n\n /** Read the stored definitions; a damaged file is ignored (built-in agents keep working). */\n async load(): Promise<void> {\n this.loaded = true\n try {\n const text = await this.store.read()\n const parsed: unknown = text === null ? [] : JSON.parse(text)\n if (!Array.isArray(parsed)) return\n const good: CustomAgent[] = []\n for (const item of parsed) {\n try {\n const agent = parseCustomAgent(item)\n if (!good.some(existing => existing.id === agent.id)) good.push(agent)\n } catch {\n // One bad entry does not take the others down.\n }\n }\n this.agents = good.slice(0, MAX_CUSTOM_AGENTS)\n } catch {\n this.agents = []\n }\n }\n\n list(): readonly CustomAgent[] {\n return this.agents\n }\n\n /** @returns what to launch for a custom agent id, or undefined when the id is not one. */\n resolve(id: string): AgentLaunch | undefined {\n const agent = this.agents.find(candidate => candidate.id === id)\n return agent === undefined ? undefined : { command: agent.command, args: agent.args }\n }\n\n /** @throws AgentDefinitionError for an invalid, duplicate, or unrunnable definition. */\n async add(raw: unknown): Promise<CustomAgent> {\n if (!this.loaded) await this.load()\n const agent = parseCustomAgent(raw)\n if (this.agents.some(existing => existing.id === agent.id)) throw new AgentDefinitionError(`\"${agent.id}\" already exists`)\n if (this.agents.length >= MAX_CUSTOM_AGENTS) throw new AgentDefinitionError(`at most ${String(MAX_CUSTOM_AGENTS)} custom agents`)\n if (!await this.commandExists(agent.command)) throw new AgentDefinitionError(`\"${agent.command}\" was not found on this machine`)\n const next = [...this.agents, agent]\n await this.store.write(JSON.stringify(next, null, 2))\n this.agents = next\n return agent\n }\n\n /** Idempotent. */\n async remove(id: string): Promise<void> {\n if (!this.loaded) await this.load()\n if (!this.agents.some(agent => agent.id === id)) return\n const next = this.agents.filter(agent => agent.id !== id)\n await this.store.write(JSON.stringify(next, null, 2))\n this.agents = next\n }\n}\n","/** The catalog's file in the user's ACRYL home, written atomically. */\n\nimport { randomBytes } from 'node:crypto'\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport type { CatalogStore } from './catalog.ts'\n\n/** The catalog file in the app's ACRYL home (from the `appInstance` service: this package never looks up a home itself). */\nexport function agentsFile(appHome: string): string {\n return join(appHome, 'workspace', 'agents.json')\n}\n\n/** The preferences file, next to the catalog. */\nexport function agentSettingsFile(appHome: string): string {\n return join(dirname(agentsFile(appHome)), 'agent-settings.json')\n}\n\nexport function createFileCatalogStore(path: string): CatalogStore {\n return {\n async read() {\n try {\n return await readFile(path, 'utf8')\n } catch (cause) {\n if (typeof cause === 'object' && cause !== null && 'code' in cause && cause.code === 'ENOENT') return null\n throw cause\n }\n },\n async write(text) {\n await mkdir(dirname(path), { recursive: true })\n const temp = `${path}.${randomBytes(6).toString('hex')}.tmp`\n await writeFile(temp, text, { encoding: 'utf8', mode: 0o600 })\n await rename(temp, path)\n },\n }\n}\n","/**\n * Agent settings: the preferences file plus everything a launch and Settings > Agents need from it.\n *\n * It answers three questions: what does this id run (`resolve`), what does Settings show (`view`), and what\n * changed (`apply`). The file and the \"is this program installed\" check are ports, so all of it runs in a test\n * with no disk and no process table. A custom agent is still defined only in the catalog; settings never adds one.\n */\n\nimport type { AgentCatalog, CatalogStore, CommandExists } from './catalog.ts'\nimport type { AgentSettingsEntry, AgentSettingsView } from './contract.ts'\nimport { DEFAULT_OVERRIDE, describeLaunch, planKnownLaunch, type AgentLaunch } from './launch.ts'\nimport { KNOWN_AGENTS, knownAgent } from './known-agents.ts'\nimport { applyPreferencesPatch, DEFAULT_PREFERENCES, parseStoredPreferences, type AgentPreferences, type PreferencesPatch } from './preferences.ts'\n\nexport class AgentSettings {\n private preferences: AgentPreferences = DEFAULT_PREFERENCES\n private loaded = false\n\n constructor(\n private readonly store: CatalogStore,\n private readonly catalog: Pick<AgentCatalog, 'list' | 'resolve'>,\n private readonly commandExists: CommandExists,\n ) {}\n\n /** Read the stored preferences; a damaged file gives the defaults. */\n async load(): Promise<void> {\n this.loaded = true\n try {\n const text = await this.store.read()\n this.preferences = text === null ? DEFAULT_PREFERENCES : parseStoredPreferences(JSON.parse(text))\n } catch {\n this.preferences = DEFAULT_PREFERENCES\n }\n }\n\n /** @returns what to run for an agent id (a known agent with the user's settings, or a custom agent), or undefined. */\n resolve(id: string): AgentLaunch | undefined {\n const known = knownAgent(id)\n if (known !== undefined) return planKnownLaunch(known, this.preferences.overrides[id] ?? DEFAULT_OVERRIDE, this.preferences.permissions, this.preferences.statusHooks)\n return this.catalog.resolve(id)\n }\n\n /** @throws AgentDefinitionError for an unknown agent or an invalid value. */\n async apply(patch: PreferencesPatch): Promise<AgentSettingsView> {\n if (!this.loaded) await this.load()\n const next = applyPreferencesPatch(this.preferences, patch, id => this.isAgent(id))\n await this.store.write(JSON.stringify(next, null, 2))\n this.preferences = next\n return await this.view()\n }\n\n /** The list Settings shows: known agents first, then the user's own. Detection is fresh on every call. */\n async view(): Promise<AgentSettingsView> {\n const { permissions, overrides, statusHooks } = this.preferences\n const known: AgentSettingsEntry[] = await Promise.all(KNOWN_AGENTS.map(async (agent) => {\n const override = overrides[agent.id] ?? DEFAULT_OVERRIDE\n const launch = planKnownLaunch(agent, override, permissions)\n return {\n id: agent.id,\n label: agent.label,\n kind: 'known',\n homepageUrl: agent.homepageUrl,\n defaultCommand: agent.command,\n command: launch.command,\n args: override.args,\n permissionArgs: permissions === 'yolo' ? agent.yoloArgs : [],\n permissionEnv: permissions === 'yolo' ? agent.yoloEnv ?? {} : {},\n enabled: override.enabled,\n installed: await this.commandExists(launch.command),\n preview: describeLaunch(launch),\n badge: null,\n }\n }))\n const custom: AgentSettingsEntry[] = await Promise.all(this.catalog.list().map(async agent => ({\n id: agent.id,\n label: agent.label,\n kind: 'custom',\n homepageUrl: null,\n defaultCommand: agent.command,\n command: agent.command,\n args: agent.args,\n permissionArgs: [],\n permissionEnv: {},\n enabled: (overrides[agent.id] ?? DEFAULT_OVERRIDE).enabled,\n installed: await this.commandExists(agent.command),\n preview: describeLaunch({ command: agent.command, args: agent.args }),\n badge: agent.badge,\n })))\n const agents = [...known, ...custom]\n // A default that no longer names an agent (a removed custom agent) reads as automatic.\n const stored = this.preferences.defaultAgent\n const defaultAgent = stored === 'auto' || stored === 'none' || agents.some(entry => entry.id === stored) ? stored : 'auto'\n return { permissions, defaultAgent, statusHooks, agents }\n }\n\n private isAgent(id: string): boolean {\n return knownAgent(id) !== undefined || this.catalog.list().some(agent => agent.id === id)\n }\n}\n","/**\n * What a terminal agent is doing right now, as the agent itself reports it (spec 040 T127).\n *\n * Reading this off the screen would be guessing, so the agents that support hooks tell ACRYL instead: Claude Code\n * runs a small command on \"prompt submitted\", \"tool finished\", \"needs you\" and \"turn finished\", and that command\n * posts the state here. The store keeps the latest state per terminal and only ever answers for terminals the Host\n * still has.\n */\n\n/** GET from the page: every live terminal's status. POST from an agent's hook: one report. */\nexport const WORKSPACE_AGENT_STATUS_PATH = '/api/acryl-workspace/agent-status'\n\nexport const AGENT_STATES = ['working', 'waiting', 'done'] as const\n/** `working`: busy. `waiting`: it needs you (a permission, a question). `done`: it finished its turn. */\nexport type AgentState = (typeof AGENT_STATES)[number]\n\nexport interface AgentStatus {\n readonly terminalId: string\n readonly state: AgentState\n /** Milliseconds since the epoch when it was reported. */\n readonly at: number\n}\n\nexport class AgentStatusError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'AgentStatusError'\n }\n}\n\nconst isState = (value: unknown): value is AgentState => (AGENT_STATES as readonly unknown[]).includes(value)\n\n/** @param body - untrusted JSON from a hook. @throws AgentStatusError. */\nexport function parseStatusReport(body: unknown): { readonly terminal: string; readonly state: AgentState } {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) throw new AgentStatusError('a report is an object')\n const record = body as Record<string, unknown>\n const extra = Object.keys(record).find(key => key !== 'terminal' && key !== 'state')\n if (extra !== undefined) throw new AgentStatusError(`unknown field: ${extra}`)\n const { terminal, state } = record\n if (typeof terminal !== 'string' || terminal.length === 0 || terminal.length > 80) throw new AgentStatusError('terminal must be a terminal id')\n if (!isState(state)) throw new AgentStatusError('state is working, waiting or done')\n return { terminal, state }\n}\n\nexport class AgentStatusStore {\n private readonly statuses = new Map<string, AgentStatus>()\n\n /** @param isLive - whether the Host still has a terminal with this id. @param now - the clock. */\n constructor(private readonly isLive: (terminalId: string) => boolean, private readonly now: () => number = Date.now) {}\n\n /** @returns false when no such terminal exists (a stale or forged report is ignored). */\n report(terminalId: string, state: AgentState): boolean {\n if (!this.isLive(terminalId)) return false\n this.statuses.set(terminalId, { terminalId, state, at: this.now() })\n return true\n }\n\n /** The latest status of every terminal that still exists; the others are forgotten here. */\n list(): readonly AgentStatus[] {\n for (const id of [...this.statuses.keys()]) {\n if (!this.isLive(id)) this.statuses.delete(id)\n }\n return [...this.statuses.values()]\n }\n}\n","/** The status route: agents POST what they are doing (bearer token, loopback only); the page GETs the list. */\n\nimport { Acryl } from '@acryldev/blends'\nimport { bearerAuth } from '@acryldev/blends/bearer-auth'\nimport { loopbackOnly } from '@acryldev/blends/loopback-only'\nimport { INVALID_JSON, failure, jsonBody, ownPage, readJson, type ReportError } from '../../private-route.ts'\nimport { AgentStatusError, WORKSPACE_AGENT_STATUS_PATH, parseStatusReport, type AgentStatusStore } from './agent-status.ts'\n\n/**\n * GET (from the app's own page): every live terminal's latest status.\n * POST (from an agent's hook, a program and not a page): `{ terminal, state }` with `Authorization: Bearer <token>`. The token is known only to\n * terminals ACRYL started for agents, and the request must come from this machine to the app's own loopback address.\n */\nexport function agentStatusRoutes(token: string, store: AgentStatusStore, reportError: ReportError): Acryl {\n const fromAgent = [\n loopbackOnly({ mutations: 'none', hostnames: ['127.0.0.1'] }),\n // A missing or wrong token is 401 with `WWW-Authenticate`, a malformed header 400; the hook ignores the answer either way.\n bearerAuth({\n token,\n noAuthenticationHeader: { message: failure('a bearer token is required') },\n invalidAuthenticationHeader: { message: failure('invalid authorization header') },\n invalidToken: { message: failure('wrong token') },\n }),\n ] as const\n return new Acryl()\n .get(WORKSPACE_AGENT_STATUS_PATH, ownPage, c => c.json({ statuses: store.list() }))\n .post(WORKSPACE_AGENT_STATUS_PATH, ...fromAgent, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (body === INVALID_JSON) return c.json(failure('invalid report'), 400)\n try {\n const report = parseStatusReport(body)\n // An unknown terminal is not an error for the hook: the agent may have outlived its terminal.\n return c.json({ ok: store.report(report.terminal, report.state) })\n } catch (cause) {\n if (cause instanceof AgentStatusError) return c.json(failure(cause.message), 400)\n reportError('record agent status', cause)\n return c.json(failure('the report could not be recorded'), 500)\n }\n })\n}\n","/** What the Host composition can do for the page, so the page offers only what will work. */\n\nexport const WORKSPACE_CAPABILITIES_PATH = '/api/acryl-workspace/capabilities'\n\nexport interface WorkspaceCapabilities {\n /** The DeepSeek Harness chat (its agent) is running, so \"AcrylDSH Chat\" tabs can be opened and sent from. */\n readonly chat: boolean\n /**\n * Where the Host serves this app's own page, as a path on the frame's origin (`/app` in the ACRYL frame). Present only when the Host hosts an\n * app: the frame then opens that page in a browser tile on first run, instead of an empty canvas.\n */\n readonly appPage?: string\n /** The app's folder: the worktree the frame opens on first run, so the app and its chats share one tab set. */\n readonly appRoot?: string\n /** The app's name, used as the tile's title (`my-app`), instead of the address's host. */\n readonly appName?: string\n}\n\n/** @throws when the body is not exactly the capabilities this page understands. */\nexport function parseWorkspaceCapabilities(value: unknown): WorkspaceCapabilities {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('capabilities must be an object')\n const record = value as Record<string, unknown>\n if (typeof record.chat !== 'boolean') throw new Error('capabilities.chat must be true or false')\n const appPage = record.appPage\n if (appPage !== undefined && (typeof appPage !== 'string' || !appPage.startsWith('/'))) throw new Error('capabilities.appPage must be an absolute path')\n const appRoot = record.appRoot\n if (appRoot !== undefined && (typeof appRoot !== 'string' || appRoot.length === 0)) throw new Error('capabilities.appRoot must be a non-empty path')\n const appName = record.appName\n if (appName !== undefined && (typeof appName !== 'string' || appName.length === 0)) throw new Error('capabilities.appName must be a non-empty name')\n return {\n chat: record.chat,\n ...(appPage === undefined ? {} : { appPage }),\n ...(appRoot === undefined ? {} : { appRoot }),\n ...(appName === undefined ? {} : { appName }),\n }\n}\n","/** What the running composition offers, for the app's own page only. */\n\nimport { Acryl } from '@acryldev/blends'\nimport { ownPage } from '../private-route.ts'\nimport { WORKSPACE_CAPABILITIES_PATH, type WorkspaceCapabilities } from './contract.ts'\n\n/**\n * 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\n * reported as it is now: the truth is the composition, not a flag copied from a Blueprint.\n */\nexport function capabilityRoutes(read: () => WorkspaceCapabilities): Acryl {\n return new Acryl().get(WORKSPACE_CAPABILITIES_PATH, ownPage, c => c.json(read()))\n}\n","/** Loopback routes and JSON shapes for browsing, reading and saving files inside a git worktree. */\n\nexport const WORKSPACE_FILES_TREE_PATH = '/api/acryl-workspace/files/tree'\nexport const WORKSPACE_FILES_READ_PATH = '/api/acryl-workspace/files/read'\nexport const WORKSPACE_FILES_WRITE_PATH = '/api/acryl-workspace/files/write'\nexport const WORKSPACE_FILES_ENTRY_PATH = '/api/acryl-workspace/files/entry'\n\n/** The largest file the editor opens or saves. */\nexport const MAX_EDITABLE_BYTES = 2 * 1024 * 1024\n\nexport type FileEntryKind = 'file' | 'dir'\n\nexport interface FileEntry {\n /** Base name, without any directory part. */\n readonly name: string\n readonly kind: FileEntryKind\n /** Git ignores it (build output, dependencies, local settings); the tree shows it dimmed. */\n readonly ignored?: boolean\n}\n\n/** One directory of a worktree. */\nexport interface FilesTreeView {\n /** Absolute worktree path. */\n readonly path: string\n /** Directory relative to the worktree, `''` for its root. */\n readonly dir: string\n /** Directories first, then files, each alphabetical. */\n readonly entries: readonly FileEntry[]\n /** True when the directory had more entries than the cap. */\n readonly truncated: boolean\n}\n\nexport interface FileContentView {\n readonly path: string\n readonly file: string\n /** UTF-8 text; empty when `binary`. */\n readonly content: string\n readonly binary: boolean\n readonly size: number\n /** Modification time on disk, sent back when saving to detect an outside change. */\n readonly mtimeMs: number\n}\n\nexport interface FileSavedView {\n readonly path: string\n readonly file: string\n readonly size: number\n readonly mtimeMs: number\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isEntry(value: unknown): value is FileEntry {\n return isRecord(value) && typeof value.name === 'string' && (value.kind === 'file' || value.kind === 'dir')\n && (value.ignored === undefined || typeof value.ignored === 'boolean')\n}\n\n/** @param value - unknown JSON from the tree route. */\nexport function parseFilesTreeView(value: unknown): FilesTreeView {\n if (!isRecord(value) || typeof value.path !== 'string' || typeof value.dir !== 'string'\n || typeof value.truncated !== 'boolean' || !Array.isArray(value.entries) || !value.entries.every(isEntry)) {\n throw new Error('invalid files tree response')\n }\n return { path: value.path, dir: value.dir, entries: value.entries, truncated: value.truncated }\n}\n\n/** @param value - unknown JSON from the read route. */\nexport function parseFileContentView(value: unknown): FileContentView {\n if (!isRecord(value) || typeof value.path !== 'string' || typeof value.file !== 'string'\n || typeof value.content !== 'string' || typeof value.binary !== 'boolean'\n || typeof value.size !== 'number' || typeof value.mtimeMs !== 'number') {\n throw new Error('invalid file response')\n }\n return { path: value.path, file: value.file, content: value.content, binary: value.binary, size: value.size, mtimeMs: value.mtimeMs }\n}\n\n/** @param value - unknown JSON from the write route. */\nexport function parseFileSavedView(value: unknown): FileSavedView {\n if (!isRecord(value) || typeof value.path !== 'string' || typeof value.file !== 'string'\n || typeof value.size !== 'number' || typeof value.mtimeMs !== 'number') {\n throw new Error('invalid file save response')\n }\n return { path: value.path, file: value.file, size: value.size, mtimeMs: value.mtimeMs }\n}\n\n/**\n * One structural change to a worktree's files. Deliberately small: create a file or an empty folder,\n * rename or move an entry, delete a file or an empty folder. Nothing overwrites, nothing recurses.\n */\nexport type FileEntryChange =\n | { readonly op: 'create'; readonly kind: FileEntryKind; readonly file: string }\n | { readonly op: 'rename'; readonly file: string; readonly to: string }\n | { readonly op: 'delete'; readonly file: string }\n\n/** The result of a structural change: what now exists (null after a delete). */\nexport interface FileEntryChangedView {\n readonly path: string\n readonly op: FileEntryChange['op']\n readonly file: string | null\n}\n\n/** @param value - unknown JSON from the entry route. */\nexport function parseFileEntryChangedView(value: unknown): FileEntryChangedView {\n if (!isRecord(value) || typeof value.path !== 'string'\n || (value.op !== 'create' && value.op !== 'rename' && value.op !== 'delete')\n || (value.file !== null && typeof value.file !== 'string')) {\n throw new Error('invalid file change response')\n }\n return { path: value.path, op: value.op, file: value.file }\n}\n\n/** Validate an untrusted request body into a change, or null when it is not one. */\nexport function parseFileEntryChange(value: unknown): FileEntryChange | null {\n if (!isRecord(value)) return null\n const keys = Object.keys(value).filter(key => key !== 'path').sort().join(',')\n if (value.op === 'create' && keys === 'file,kind,op' && typeof value.file === 'string' && (value.kind === 'file' || value.kind === 'dir')) {\n return { op: 'create', kind: value.kind, file: value.file }\n }\n if (value.op === 'rename' && keys === 'file,op,to' && typeof value.file === 'string' && typeof value.to === 'string') {\n return { op: 'rename', file: value.file, to: value.to }\n }\n if (value.op === 'delete' && keys === 'file,op' && typeof value.file === 'string') return { op: 'delete', file: value.file }\n return null\n}\n","/**\n * Browsing, reading and saving files inside one git worktree.\n *\n * This is the only part of the package that writes user files, so every path is confined: the worktree\n * must be the root of a git worktree (checked by the injected resolver), a file path is relative and\n * free of `..` and `.git` segments, and the real path (after symlinks) must stay inside the worktree.\n * Saves are atomic (temp file then rename) and refuse to overwrite a file that changed on disk since it\n * was read.\n */\n\nimport { randomBytes } from 'node:crypto'\nimport { chmod, lstat, mkdir, readdir, readFile, realpath, rename, rmdir, stat, unlink, writeFile } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, join, sep } from 'node:path'\nimport {\n MAX_EDITABLE_BYTES,\n type FileContentView,\n type FileEntryChange,\n type FileEntryChangedView,\n type FileEntry,\n type FileSavedView,\n type FilesTreeView,\n} from './contract.ts'\n\nexport type WorkspaceFilesErrorKind = 'invalid' | 'not-found' | 'conflict' | 'too-large' | 'failed'\n\nexport class WorkspaceFilesError extends Error {\n constructor(message: string, readonly kind: WorkspaceFilesErrorKind) {\n super(message)\n this.name = 'WorkspaceFilesError'\n }\n}\n\nconst MAX_ENTRIES = 3000\nconst BINARY_SNIFF_BYTES = 8192\n\nexport interface WorkspaceFilesOptions {\n /** Validates that a path is the root of a git worktree and returns its real path. */\n readonly resolveWorktree: (path: string) => Promise<string>\n /** Which of the given root-relative paths git ignores (a directory ends in `/`); without it nothing is marked. */\n readonly ignored?: (root: string, paths: readonly string[]) => Promise<ReadonlySet<string>>\n}\n\nexport class WorkspaceFiles {\n constructor(private readonly options: WorkspaceFilesOptions) {}\n\n async tree(worktree: string, dir: string): Promise<FilesTreeView> {\n const root = await this.options.resolveWorktree(worktree)\n const target = dir === '' ? root : await confine(root, dir)\n let dirents\n try {\n if (!(await stat(target)).isDirectory()) throw new Error('not a directory')\n dirents = await readdir(target, { withFileTypes: true })\n } catch {\n throw new WorkspaceFilesError('that directory cannot be read', 'not-found')\n }\n const entries: FileEntry[] = []\n for (const dirent of dirents) {\n if (dirent.name === '.git') continue\n if (dirent.isDirectory()) entries.push({ name: dirent.name, kind: 'dir' })\n else if (dirent.isFile()) entries.push({ name: dirent.name, kind: 'file' })\n else if (dirent.isSymbolicLink()) {\n const kind = await symlinkKind(root, join(target, dirent.name))\n if (kind !== null) entries.push({ name: dirent.name, kind })\n }\n }\n entries.sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name, 'en', { sensitivity: 'base' }) : a.kind === 'dir' ? -1 : 1))\n const shown = entries.slice(0, MAX_ENTRIES)\n const pathOf = (entry: FileEntry): string => `${dir === '' ? '' : `${dir}/`}${entry.name}${entry.kind === 'dir' ? '/' : ''}`\n const ignored = this.options.ignored === undefined ? new Set<string>() : await this.options.ignored(root, shown.map(pathOf))\n return {\n path: root,\n dir,\n entries: ignored.size === 0 ? shown : shown.map(entry => (ignored.has(pathOf(entry)) ? { ...entry, ignored: true } : entry)),\n truncated: entries.length > MAX_ENTRIES,\n }\n }\n\n async read(worktree: string, file: string): Promise<FileContentView> {\n const root = await this.options.resolveWorktree(worktree)\n const real = await confine(root, file)\n const info = await statFile(real)\n if (info.size > MAX_EDITABLE_BYTES) throw new WorkspaceFilesError('the file is too large to edit here', 'too-large')\n const buffer = await readFile(real)\n const binary = buffer.subarray(0, BINARY_SNIFF_BYTES).includes(0)\n return {\n path: root,\n file,\n content: binary ? '' : buffer.toString('utf8'),\n binary,\n size: info.size,\n mtimeMs: info.mtimeMs,\n }\n }\n\n /**\n * Replace an existing file's text.\n * @param expectedMtimeMs - the `mtimeMs` from the read this edit is based on.\n * @throws WorkspaceFilesError `conflict` when the file changed on disk since that read.\n */\n async write(worktree: string, file: string, content: string, expectedMtimeMs: number): Promise<FileSavedView> {\n const root = await this.options.resolveWorktree(worktree)\n const real = await confine(root, file)\n const info = await statFile(real)\n if (Buffer.byteLength(content, 'utf8') > MAX_EDITABLE_BYTES) throw new WorkspaceFilesError('the text is too large to save here', 'too-large')\n if (info.mtimeMs !== expectedMtimeMs) {\n throw new WorkspaceFilesError('the file changed on disk since you opened it', 'conflict')\n }\n const temp = join(dirname(real), `.${basename(real)}.acryl-${randomBytes(6).toString('hex')}.tmp`)\n try {\n await writeFile(temp, content, { encoding: 'utf8', flag: 'wx' })\n await chmod(temp, info.mode & 0o7777)\n await rename(temp, real)\n } catch {\n await unlink(temp).catch(() => {})\n throw new WorkspaceFilesError('the file could not be saved', 'failed')\n }\n const saved = await stat(real)\n return { path: root, file, size: saved.size, mtimeMs: saved.mtimeMs }\n }\n\n /**\n * Create, rename or delete one entry. Never overwrites, never recurses: a delete removes a file or an\n * empty folder only, and a create or rename refuses a name that is already taken.\n */\n async change(worktree: string, change: FileEntryChange): Promise<FileEntryChangedView> {\n const root = await this.options.resolveWorktree(worktree)\n if (change.op === 'create') {\n const target = await confineNew(root, change.file)\n try {\n if (change.kind === 'dir') await mkdir(target)\n else await writeFile(target, '', { flag: 'wx' })\n } catch {\n throw new WorkspaceFilesError('that could not be created', 'failed')\n }\n return { path: root, op: 'create', file: change.file }\n }\n if (change.op === 'rename') {\n const source = await confineEntry(root, change.file)\n const target = await confineNew(root, change.to)\n try {\n await rename(source, target)\n } catch {\n throw new WorkspaceFilesError('that could not be renamed', 'failed')\n }\n return { path: root, op: 'rename', file: change.to }\n }\n const target = await confineEntry(root, change.file)\n try {\n if ((await lstat(target)).isDirectory()) await rmdir(target)\n else await unlink(target)\n } catch (cause) {\n const code = typeof cause === 'object' && cause !== null && 'code' in cause ? cause.code : undefined\n if (code === 'ENOTEMPTY' || code === 'EEXIST') throw new WorkspaceFilesError('only an empty folder can be deleted', 'conflict')\n throw new WorkspaceFilesError('that could not be deleted', 'failed')\n }\n return { path: root, op: 'delete', file: null }\n }\n}\n\nasync function statFile(real: string): Promise<{ size: number; mtimeMs: number; mode: number }> {\n try {\n const info = await stat(real)\n if (!info.isFile()) throw new Error('not a file')\n return { size: info.size, mtimeMs: info.mtimeMs, mode: info.mode }\n } catch {\n throw new WorkspaceFilesError('that file does not exist', 'not-found')\n }\n}\n\n/** A symlink is listed only when it points at a file or directory inside the worktree. */\nasync function symlinkKind(root: string, path: string): Promise<'file' | 'dir' | null> {\n try {\n const real = await realpath(path)\n if (!isInside(root, real)) return null\n const info = await stat(real)\n return info.isDirectory() ? 'dir' : info.isFile() ? 'file' : null\n } catch {\n return null\n }\n}\n\nfunction isInside(root: string, real: string): boolean {\n return real === root || real.startsWith(root.endsWith(sep) ? root : root + sep)\n}\n\n/**\n * Turn a worktree-relative path into a real path that is guaranteed to be inside `root`.\n * Rejects absolute paths, NUL, `..` and `.git` segments, and symlinks that leave the worktree.\n */\nexport async function confine(root: string, relative: string): Promise<string> {\n if (typeof relative !== 'string' || relative.length === 0 || relative.includes('\\0') || isAbsolute(relative)) {\n throw new WorkspaceFilesError('path must be relative to the worktree', 'invalid')\n }\n const segments = relative.split(/[\\\\/]+/).filter(segment => segment.length > 0)\n if (segments.length === 0 || segments.some(segment => segment === '..' || segment.toLowerCase() === '.git')) {\n throw new WorkspaceFilesError('that path is not allowed', 'invalid')\n }\n let real: string\n try {\n real = await realpath(join(root, ...segments))\n } catch {\n throw new WorkspaceFilesError('that path does not exist', 'not-found')\n }\n if (!isInside(root, real)) throw new WorkspaceFilesError('that path leaves the worktree', 'invalid')\n return real\n}\n\nfunction segmentsOf(relative: string): string[] {\n if (typeof relative !== 'string' || relative.length === 0 || relative.includes('\\0') || isAbsolute(relative)) {\n throw new WorkspaceFilesError('path must be relative to the worktree', 'invalid')\n }\n const segments = relative.split(/[\\\\/]+/).filter(segment => segment.length > 0)\n if (segments.length === 0 || segments.some(segment => segment === '..' || segment === '.' || segment.toLowerCase() === '.git')) {\n throw new WorkspaceFilesError('that path is not allowed', 'invalid')\n }\n return segments\n}\n\n/**\n * The real path of an entry that will be created: its folder must exist inside the worktree and the name\n * must be free (a dangling symlink counts as taken).\n */\nexport async function confineNew(root: string, relative: string): Promise<string> {\n const segments = segmentsOf(relative)\n const name = segments[segments.length - 1] as string\n let parent: string\n try {\n parent = await realpath(join(root, ...segments.slice(0, -1)))\n } catch {\n throw new WorkspaceFilesError('the folder does not exist', 'not-found')\n }\n if (!isInside(root, parent)) throw new WorkspaceFilesError('that path leaves the worktree', 'invalid')\n const target = join(parent, name)\n try {\n await lstat(target)\n } catch {\n return target\n }\n throw new WorkspaceFilesError('something with that name already exists', 'conflict')\n}\n\n/** The path of an existing entry itself: a symlink is renamed or deleted as the link, never followed. */\nasync function confineEntry(root: string, relative: string): Promise<string> {\n const segments = segmentsOf(relative)\n const name = segments[segments.length - 1] as string\n let parent: string\n try {\n parent = await realpath(join(root, ...segments.slice(0, -1)))\n } catch {\n throw new WorkspaceFilesError('that path does not exist', 'not-found')\n }\n if (!isInside(root, parent)) throw new WorkspaceFilesError('that path leaves the worktree', 'invalid')\n const target = join(parent, name)\n try {\n await lstat(target)\n } catch {\n throw new WorkspaceFilesError('that path does not exist', 'not-found')\n }\n return target\n}\n","/** The worktree file routes: two reads and two changes, for the app's own page only. */\n\nimport { Acryl, type Context } from '@acryldev/blends'\nimport { INVALID_JSON, failure, isRecord, jsonBody, ownPage, readJson, type ReportError } from '../private-route.ts'\nimport {\n MAX_EDITABLE_BYTES,\n WORKSPACE_FILES_ENTRY_PATH,\n WORKSPACE_FILES_READ_PATH,\n WORKSPACE_FILES_TREE_PATH,\n WORKSPACE_FILES_WRITE_PATH,\n parseFileEntryChange,\n} from './contract.ts'\nimport { WorkspaceFilesError, type WorkspaceFiles } from './service.ts'\n\nconst STATUS = { invalid: 400, 'not-found': 404, conflict: 409, 'too-large': 413, failed: 500 } as const\n\nfunction required(c: Context, name: string): string {\n const value = c.req.query(name)\n if (value === undefined || value.length === 0) throw new WorkspaceFilesError(`missing ${name}`, 'invalid')\n return value\n}\n\n/**\n * GET `tree?path=<worktree>&dir=<relative, empty for the root>` and `read?path=&file=`; POST `write` `{ path, file, content, expectedMtimeMs }`\n * to replace an existing file's text and `entry` `{ path, op: 'create' | 'rename' | 'delete', file, kind?, to? }` for one structural change.\n */\nexport function filesRoutes(files: WorkspaceFiles, reportError: ReportError): Acryl {\n const answer = async (c: Context, operation: string, compute: () => Promise<object>): Promise<Response> => {\n try {\n return c.json(await compute())\n } catch (cause) {\n if (cause instanceof WorkspaceFilesError) return c.json(failure(cause.message), STATUS[cause.kind])\n reportError(operation, cause)\n return c.json(failure('file request failed'), 500)\n }\n }\n return new Acryl()\n .get(WORKSPACE_FILES_TREE_PATH, ownPage, c => answer(c, 'list files', () => files.tree(required(c, 'path'), c.req.query('dir') ?? '')))\n .get(WORKSPACE_FILES_READ_PATH, ownPage, c => answer(c, 'read file', () => files.read(required(c, 'path'), required(c, 'file'))))\n .post(WORKSPACE_FILES_WRITE_PATH, ownPage, jsonBody(MAX_EDITABLE_BYTES + 64 * 1024), async (c) => {\n const body = await readJson(c)\n if (body === INVALID_JSON || !isRecord(body)\n || typeof body.path !== 'string' || typeof body.file !== 'string'\n || typeof body.content !== 'string' || typeof body.expectedMtimeMs !== 'number'\n || Object.keys(body).length !== 4) {\n return c.json(failure('invalid save request'), 400)\n }\n const { path, file, content, expectedMtimeMs } = body\n return answer(c, 'save file', () => files.write(path, file, content, expectedMtimeMs))\n })\n .post(WORKSPACE_FILES_ENTRY_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n const change = body === INVALID_JSON ? null : parseFileEntryChange(body)\n if (change === null || !isRecord(body) || typeof body.path !== 'string') return c.json(failure('invalid change request'), 400)\n const { path } = body\n return answer(c, 'change file', () => files.change(path, change))\n })\n}\n","/**\n * Opens the operating system's own folder chooser and reports the folder picked. The Host serves a\n * loopback-only Web server (`@acryldev/workspace` refuses to start otherwise), so a dialog raised here is on\n * the same machine as the person using the page - the reason this is safe to offer at all, unlike a\n * chooser on a remote server nobody is sitting at.\n */\n\nimport { execFile } from 'node:child_process'\n\n/** Runs a program and resolves its stdout; rejects with `code` set to the exit code or 'ENOENT'. */\nexport type RunProgram = (file: string, args: readonly string[]) => Promise<string>\n\n/** No native chooser exists on this machine (no dialog program installed). */\nexport class FolderPickerUnavailableError extends Error {\n constructor() {\n super('no native folder chooser is available on this machine')\n this.name = 'FolderPickerUnavailableError'\n }\n}\n\nconst defaultRun: RunProgram = (file, args) => new Promise((resolve, reject) => {\n // No shell: the arguments are passed as an array, never interpolated into a command line.\n execFile(file, [...args], { maxBuffer: 1024 * 1024 }, (cause, stdout) => {\n if (cause === null) resolve(stdout)\n else reject(cause)\n })\n})\n\nfunction exitCode(cause: unknown): unknown {\n return typeof cause === 'object' && cause !== null && 'code' in cause ? (cause as { code?: unknown }).code : undefined\n}\n\n/** A trailing separator is dropped (the chooser adds one), except for a filesystem root. */\nexport function normalizePickedPath(raw: string): string | null {\n const text = raw.trim()\n if (text === '') return null\n const stripped = text.replace(/[\\\\/]+$/, '')\n return stripped === '' ? text : stripped\n}\n\nconst MAC_SCRIPT = [\n 'try',\n 'POSIX path of (choose folder with prompt \"Choose a workspace folder\")',\n 'on error number -128',\n 'return \"\"',\n 'end try',\n]\n\nconst WINDOWS_SCRIPT = [\n 'Add-Type -AssemblyName System.Windows.Forms',\n '$d = New-Object System.Windows.Forms.FolderBrowserDialog',\n '$d.Description = \"Choose a workspace folder\"',\n \"if ($d.ShowDialog() -eq 'OK') { Write-Output $d.SelectedPath }\",\n].join('; ')\n\n/**\n * @param platform - `process.platform`.\n * @param run - process runner; injected so the tests never open a dialog.\n * @returns the absolute path picked, or null when the chooser was cancelled.\n * @throws FolderPickerUnavailableError when this machine has no chooser program.\n */\nexport async function pickFolderNatively(platform: NodeJS.Platform, run: RunProgram = defaultRun): Promise<string | null> {\n if (platform === 'darwin') {\n return normalizePickedPath(await run('osascript', MAC_SCRIPT.flatMap(line => ['-e', line])))\n }\n if (platform === 'win32') {\n return normalizePickedPath(await run('powershell.exe', ['-NoProfile', '-STA', '-Command', WINDOWS_SCRIPT]))\n }\n // Linux and others: zenity, then kdialog. Cancelling either exits 1 with nothing on stdout.\n const candidates: ReadonlyArray<readonly [string, readonly string[]]> = [\n ['zenity', ['--file-selection', '--directory', '--title=Choose a workspace folder']],\n ['kdialog', ['--getexistingdirectory', '.', '--title', 'Choose a workspace folder']],\n ]\n for (const [file, args] of candidates) {\n try {\n return normalizePickedPath(await run(file, args))\n } catch (cause) {\n if (exitCode(cause) === 'ENOENT') continue\n return null // the person closed the dialog\n }\n }\n throw new FolderPickerUnavailableError()\n}\n\n/** One chooser at a time: a second request while one is open waits for that answer instead of stacking dialogs. */\nexport function singleFlight<T>(task: () => Promise<T>): () => Promise<T> {\n let inflight: Promise<T> | undefined\n return () => {\n inflight ??= task().finally(() => { inflight = undefined })\n return inflight\n }\n}\n","/** Same-origin route that opens the operating system's own folder chooser on the machine running the Host. */\nexport const WORKSPACE_PICK_FOLDER_PATH = '/api/acryl-workspace/pick-folder'\n\n/** What the chooser answered: the picked absolute path, or null when it was cancelled. */\nexport interface PickFolderView {\n readonly path: string | null\n}\n\n/** HTTP status the route uses when this machine has no native chooser (a headless Linux box, say). */\nexport const PICK_FOLDER_UNAVAILABLE_STATUS = 501\n\nexport function parsePickFolderView(value: unknown): PickFolderView {\n if (typeof value !== 'object' || value === null || !('path' in value)) throw new Error('invalid folder chooser response')\n const path = (value as { path?: unknown }).path\n if (path !== null && typeof path !== 'string') throw new Error('invalid folder chooser response')\n return { path }\n}\n","/** The native folder chooser, for the app's own page only. */\n\nimport { Acryl } from '@acryldev/blends'\nimport { failure, ownPage, type ReportError } from '../private-route.ts'\nimport { PICK_FOLDER_UNAVAILABLE_STATUS, WORKSPACE_PICK_FOLDER_PATH, type PickFolderView } from './contract.ts'\nimport { FolderPickerUnavailableError } from './picker.ts'\n\n/** POST: open the OS's chooser and answer the folder, or `null` when it was cancelled. */\nexport function pickFolderRoutes(pick: () => Promise<string | null>, reportError: ReportError): Acryl {\n return new Acryl()\n .post(WORKSPACE_PICK_FOLDER_PATH, ownPage, async (c) => {\n // It raises a window on the person's screen: a JSON request only, which a plain HTML form cannot send.\n if (c.req.header('content-type')?.split(';', 1)[0]?.trim().toLowerCase() !== 'application/json') return c.json(failure('forbidden'), 403)\n try {\n return c.json({ path: await pick() } satisfies PickFolderView)\n } catch (cause) {\n if (cause instanceof FolderPickerUnavailableError) return c.json(failure(cause.message), PICK_FOLDER_UNAVAILABLE_STATUS)\n reportError('open the folder chooser', cause)\n return c.json(failure('the folder chooser failed'), 500)\n }\n })\n}\n","/** Read-only git routes and view types shared by the ACRYL Workspace Host and Client. */\n\nexport const WORKSPACE_GIT_REPO_PATH = '/api/acryl-workspace/git/repo'\nexport const WORKSPACE_GIT_STATUS_PATH = '/api/acryl-workspace/git/status'\nexport const WORKSPACE_GIT_DIFF_PATH = '/api/acryl-workspace/git/diff'\nexport const WORKSPACE_GIT_WORKTREE_PATH = '/api/acryl-workspace/git/worktree'\nexport const WORKSPACE_GIT_CHECKS_PATH = '/api/acryl-workspace/git/checks'\nexport const WORKSPACE_GIT_SEARCH_PATH = '/api/acryl-workspace/git/search'\nexport const WORKSPACE_GIT_STAGE_PATH = '/api/acryl-workspace/git/stage'\nexport const WORKSPACE_GIT_UNSTAGE_PATH = '/api/acryl-workspace/git/unstage'\nexport const WORKSPACE_GIT_COMMIT_PATH = '/api/acryl-workspace/git/commit'\n\n/** The most hits one search returns. */\nexport const MAX_SEARCH_RESULTS = 200\n/** The longest query the search route accepts. */\nexport const MAX_SEARCH_QUERY = 200\n\n/** The most files one stage or unstage request may name. */\nexport const MAX_STAGE_FILES = 1000\n/** The longest commit message the commit route accepts. */\nexport const MAX_COMMIT_MESSAGE = 5000\n\n/** One worktree of a repository, as `git worktree list` reports it. */\nexport interface GitWorktree {\n /** Absolute path of the worktree directory. */\n readonly path: string\n /** Checked-out branch name, or null when HEAD is detached or bare. */\n readonly branch: string | null\n /** Full commit id HEAD points at. */\n readonly head: string\n /** True for the repository's main worktree (git always lists it first). */\n readonly main: boolean\n}\n\n/** A repository and every worktree attached to it. */\nexport interface GitRepoView {\n /** Display name: the main worktree's directory name. */\n readonly name: string\n /** Absolute path of the main worktree. */\n readonly root: string\n /** Path of the worktree that contains the directory the request named. */\n readonly current: string\n readonly worktrees: readonly GitWorktree[]\n}\n\n/** Status letters shown next to a changed file. `?` is untracked, `U` is unmerged. */\nexport type GitChangeCode = 'M' | 'A' | 'D' | 'R' | 'U' | '?'\n\nexport interface GitChange {\n /** Path relative to the worktree root, forward slashes. */\n readonly path: string\n readonly code: GitChangeCode\n /** True when the index already holds a change for this path. */\n readonly staged: boolean\n /** Lines added versus HEAD, or null for binary and untracked files. */\n readonly added: number | null\n /** Lines removed versus HEAD, or null for binary and untracked files. */\n readonly removed: number | null\n /** Previous path for a rename. */\n readonly oldPath?: string\n}\n\nexport interface GitStatusView {\n /** Worktree path this status describes. */\n readonly path: string\n /** Current branch, or null when detached. */\n readonly branch: string | null\n readonly changes: readonly GitChange[]\n /** True when the change list was cut at the entry cap. */\n readonly truncated: boolean\n}\n\nexport interface GitDiffView {\n readonly path: string\n readonly file: string\n /** Unified diff text against HEAD; empty for binary files. */\n readonly text: string\n readonly binary: boolean\n /** True when the diff exceeded the output cap and was cut. */\n readonly truncated: boolean\n}\n\n/** The result of creating a branch and its worktree. */\nexport interface GitWorktreeCreatedView {\n /** Absolute path of the new worktree. */\n readonly path: string\n readonly branch: string\n /** The repository after the change, so the caller does not need a second request. */\n readonly repo: GitRepoView\n}\n\nexport type CheckManager = 'pnpm' | 'npm' | 'yarn' | 'bun'\n\nexport interface CheckScript {\n /** A plain script name (letters, digits and `:_.-`), safe to type into a shell. */\n readonly name: string\n /** The script's command line, for display only. */\n readonly command: string\n /** True for check-like names (check, test, lint, typecheck, build, format, ...). */\n readonly primary: boolean\n}\n\n/** What a worktree can run: its package scripts and the package manager its lockfile names. */\nexport interface GitChecksView {\n readonly path: string\n /** The project's own manager, or null when no lockfile says (then `npm` is the neutral default). */\n readonly manager: CheckManager | null\n readonly scripts: readonly CheckScript[]\n}\n\nexport type GitSearchMode = 'name' | 'content'\n\n/** One search hit: a file, and for a content search the line and its text. */\nexport interface GitSearchHit {\n readonly file: string\n readonly line?: number\n readonly text?: string\n}\n\n/** Search results over the tracked and untracked (not ignored) files of a worktree. */\nexport interface GitSearchView {\n readonly path: string\n readonly query: string\n readonly mode: GitSearchMode\n readonly hits: readonly GitSearchHit[]\n /** True when there were more matches than the cap. */\n readonly truncated: boolean\n}\n\n/** The result of a commit: the new commit and the worktree's status afterwards. */\nexport interface GitCommitView {\n /** Abbreviated hash of the new commit. */\n readonly hash: string\n /** First line of its message. */\n readonly subject: string\n readonly status: GitStatusView\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isWorktree(value: unknown): value is GitWorktree {\n return isRecord(value)\n && typeof value.path === 'string'\n && (value.branch === null || typeof value.branch === 'string')\n && typeof value.head === 'string'\n && typeof value.main === 'boolean'\n}\n\n/** @param value - unknown JSON from the repo route. */\nexport function parseGitRepoView(value: unknown): GitRepoView {\n if (!isRecord(value) || typeof value.name !== 'string' || typeof value.root !== 'string'\n || typeof value.current !== 'string'\n || !Array.isArray(value.worktrees) || !value.worktrees.every(isWorktree)) {\n throw new Error('invalid git repo response')\n }\n return { name: value.name, root: value.root, current: value.current, worktrees: value.worktrees }\n}\n\nconst CHANGE_CODES = new Set<string>(['M', 'A', 'D', 'R', 'U', '?'])\n\nfunction isChange(value: unknown): value is GitChange {\n return isRecord(value)\n && typeof value.path === 'string'\n && typeof value.code === 'string' && CHANGE_CODES.has(value.code)\n && typeof value.staged === 'boolean'\n && (value.added === null || typeof value.added === 'number')\n && (value.removed === null || typeof value.removed === 'number')\n && (value.oldPath === undefined || typeof value.oldPath === 'string')\n}\n\n/** @param value - unknown JSON from the status route. */\nexport function parseGitStatusView(value: unknown): GitStatusView {\n if (!isRecord(value) || typeof value.path !== 'string'\n || (value.branch !== null && typeof value.branch !== 'string')\n || typeof value.truncated !== 'boolean'\n || !Array.isArray(value.changes) || !value.changes.every(isChange)) {\n throw new Error('invalid git status response')\n }\n return { path: value.path, branch: value.branch, changes: value.changes, truncated: value.truncated }\n}\n\n/** @param value - unknown JSON from the diff route. */\nexport function parseGitDiffView(value: unknown): GitDiffView {\n if (!isRecord(value) || typeof value.path !== 'string' || typeof value.file !== 'string'\n || typeof value.text !== 'string' || typeof value.binary !== 'boolean'\n || typeof value.truncated !== 'boolean') {\n throw new Error('invalid git diff response')\n }\n return { path: value.path, file: value.file, text: value.text, binary: value.binary, truncated: value.truncated }\n}\n\n/** @param value - unknown JSON from the worktree route. */\nexport function parseGitWorktreeCreatedView(value: unknown): GitWorktreeCreatedView {\n if (!isRecord(value) || typeof value.path !== 'string' || typeof value.branch !== 'string') {\n throw new Error('invalid git worktree response')\n }\n return { path: value.path, branch: value.branch, repo: parseGitRepoView(value.repo) }\n}\n\nconst MANAGERS = new Set<string>(['pnpm', 'npm', 'yarn', 'bun'])\nconst SAFE_NAME = /^[A-Za-z0-9][A-Za-z0-9:_.-]{0,63}$/\n\nfunction isCheckScript(value: unknown): value is CheckScript {\n return isRecord(value)\n && typeof value.name === 'string' && SAFE_NAME.test(value.name)\n && typeof value.command === 'string'\n && typeof value.primary === 'boolean'\n}\n\n/** @param value - unknown JSON from the checks route. */\nexport function parseGitChecksView(value: unknown): GitChecksView {\n if (!isRecord(value) || typeof value.path !== 'string'\n || (value.manager !== null && !(typeof value.manager === 'string' && MANAGERS.has(value.manager)))\n || !Array.isArray(value.scripts) || !value.scripts.every(isCheckScript)) {\n throw new Error('invalid git checks response')\n }\n return { path: value.path, manager: value.manager as CheckManager | null, scripts: value.scripts }\n}\n\n/** The command line to type for one script, using the project's own package manager. */\nexport function checkCommandLine(manager: CheckManager | null, script: string): string {\n if (!SAFE_NAME.test(script)) throw new Error('unsafe script name')\n return `${manager ?? 'npm'} run ${script}`\n}\n\n/** @param value - unknown JSON from the commit route. */\nexport function parseGitCommitView(value: unknown): GitCommitView {\n if (!isRecord(value) || typeof value.hash !== 'string' || typeof value.subject !== 'string') {\n throw new Error('invalid git commit response')\n }\n return { hash: value.hash, subject: value.subject, status: parseGitStatusView(value.status) }\n}\n\nfunction isHit(value: unknown): value is GitSearchHit {\n return isRecord(value) && typeof value.file === 'string'\n && (value.line === undefined || typeof value.line === 'number')\n && (value.text === undefined || typeof value.text === 'string')\n}\n\n/** @param value - unknown JSON from the search route. */\nexport function parseGitSearchView(value: unknown): GitSearchView {\n if (!isRecord(value) || typeof value.path !== 'string' || typeof value.query !== 'string'\n || (value.mode !== 'name' && value.mode !== 'content') || typeof value.truncated !== 'boolean'\n || !Array.isArray(value.hits) || !value.hits.every(isHit)) {\n throw new Error('invalid git search response')\n }\n return { path: value.path, query: value.query, mode: value.mode, hits: value.hits, truncated: value.truncated }\n}\n","/** Errors of the Workspace git modules. */\n\n/**\n * A request the caller got wrong (400), a directory that is not a repository (404), something that\n * already exists (409), or a git failure (500).\n */\nexport class WorkspaceGitError extends Error {\n constructor(message: string, readonly kind: 'invalid' | 'not-repo' | 'conflict' | 'failed') {\n super(message)\n this.name = 'WorkspaceGitError'\n }\n}\n","/** Checks on what a caller may hand to git, before git sees it. */\n\nimport { MAX_STAGE_FILES } from './contract.ts'\nimport { WorkspaceGitError } from './errors.ts'\n\n/**\n * A conservative first filter, before git's own check: letters, digits, `.`, `_`, `-` and `/`\n * separators, starting with a letter, digit or underscore. It keeps the branch usable as one folder\n * name and can never look like an option or a path escape.\n */\nexport function assertBranchName(branch: string): void {\n if (typeof branch !== 'string' || branch.length === 0 || branch.length > 200\n || !/^[A-Za-z0-9_][A-Za-z0-9._/-]*$/.test(branch)\n || branch.includes('..') || branch.includes('//') || branch.endsWith('/') || branch.endsWith('.') || branch.endsWith('.lock')) {\n throw new WorkspaceGitError('branch names use letters, digits, \".\", \"_\", \"-\" and \"/\", and start with a letter, digit or \"_\"', 'invalid')\n }\n}\n\nexport function assertFileList(files: readonly string[]): void {\n if (!Array.isArray(files) || files.length === 0 || files.length > MAX_STAGE_FILES) {\n throw new WorkspaceGitError(`name between 1 and ${String(MAX_STAGE_FILES)} files`, 'invalid')\n }\n for (const file of files) assertRelativeFile(file)\n}\n\nexport function assertRelativeFile(file: string): void {\n if (typeof file !== 'string' || file.length === 0 || file.length > 4096 || file.includes('\\0')\n || file.startsWith('/') || file.startsWith('-') || /(^|[\\\\/])\\.\\.([\\\\/]|$)/.test(file)) {\n throw new WorkspaceGitError('file must be a relative path inside the worktree', 'invalid')\n }\n}\n","/** Parsers for the machine-readable output of `git worktree`, `git diff --numstat` and `git status`. */\n\nimport { normalize } from 'node:path'\nimport type { GitChange, GitChangeCode, GitWorktree } from './contract.ts'\n\n/** 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`). */\nexport function parseWorktrees(text: string): GitWorktree[] {\n const worktrees: GitWorktree[] = []\n for (const block of text.split(/\\n\\n+/)) {\n let path: string | undefined\n let head = ''\n let branch: string | null = null\n for (const line of block.split('\\n')) {\n if (line.startsWith('worktree ')) path = line.slice('worktree '.length)\n else if (line.startsWith('HEAD ')) head = line.slice('HEAD '.length)\n else if (line.startsWith('branch ')) branch = line.slice('branch '.length).replace(/^refs\\/heads\\//, '')\n }\n if (path !== undefined) worktrees.push({ path: normalize(path), head, branch, main: worktrees.length === 0 })\n }\n return worktrees\n}\n\ninterface LineCount {\n readonly added: number | null\n readonly removed: number | null\n}\n\n/** Parse `git diff --numstat -z`. Binary files report `-` and map to null counts. */\nexport function parseNumstat(text: string): Map<string, LineCount> {\n const counts = new Map<string, LineCount>()\n const tokens = text.split('\\0')\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index]\n if (token === undefined || token === '') continue\n const match = /^(\\d+|-)\\t(\\d+|-)\\t([\\s\\S]*)$/.exec(token)\n if (match === null) continue\n let path = match[3] ?? ''\n // A rename carries an empty path here, then the old and new paths as the next two tokens.\n if (path === '') {\n path = tokens[index + 2] ?? ''\n index += 2\n }\n counts.set(path, {\n added: match[1] === '-' ? null : Number(match[1]),\n removed: match[2] === '-' ? null : Number(match[2]),\n })\n }\n return counts\n}\n\nfunction classify(x: string, y: string): { code: GitChangeCode; staged: boolean } {\n if (x === '?' && y === '?') return { code: '?', staged: false }\n if (x === 'U' || y === 'U' || (x === 'A' && y === 'A') || (x === 'D' && y === 'D')) {\n return { code: 'U', staged: false }\n }\n const staged = x !== ' '\n let code: string\n if (x === 'A' || x === 'C') code = 'A'\n else if (x === 'R') code = 'R'\n else code = y !== ' ' ? y : x\n if (code === 'T') code = 'M'\n return { code: (['M', 'A', 'D', 'R'].includes(code) ? code : 'M') as GitChangeCode, staged }\n}\n\n/** Parse `git status --porcelain=v1 -z`, attaching line counts where git reported them. */\nexport function parsePorcelain(text: string, counts: ReadonlyMap<string, LineCount>): GitChange[] {\n const changes: GitChange[] = []\n const tokens = text.split('\\0')\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index]\n if (token === undefined || token.length < 4) continue\n const x = token[0] ?? ' '\n const y = token[1] ?? ' '\n if (x === '!' && y === '!') continue\n const path = token.slice(3)\n let oldPath: string | undefined\n if (x === 'R' || x === 'C' || y === 'R' || y === 'C') {\n oldPath = tokens[index + 1]\n index += 1\n }\n const { code, staged } = classify(x, y)\n const count = counts.get(path)\n changes.push({\n path,\n code,\n staged,\n added: count?.added ?? null,\n removed: count?.removed ?? null,\n ...(oldPath === undefined ? {} : { oldPath }),\n })\n }\n return changes\n}\n","/**\n * The confined way to run git: an argument array (never a shell), a timeout, an output cap, and a record\n * of every in-flight process so disposal can abort and reap them. Set `GIT_OPTIONAL_LOCKS=0` so a status\n * poll never takes the index lock an agent's own `git` call may need.\n */\n\nimport { execFile } from 'node:child_process'\nimport { realpath, stat } from 'node:fs/promises'\nimport { isAbsolute } from 'node:path'\nimport { WorkspaceGitError } from './errors.ts'\n\nconst DEFAULT_MAX_OUTPUT_BYTES = 1024 * 1024\nconst DEFAULT_TIMEOUT_MS = 10_000\n\nconst GLOBAL_ARGS = ['-c', 'core.quotepath=false', '-c', 'color.ui=false', '-c', 'core.fsmonitor=false'] as const\n\nexport interface GitRunnerOptions {\n /** Executable to run. Defaults to `git`. */\n readonly gitPath?: string\n /** Output cap per command; longer output is cut and flagged. */\n readonly maxOutputBytes?: number\n readonly timeoutMs?: number\n}\n\nexport interface RunResult {\n readonly stdout: string\n readonly truncated: boolean\n}\n\ninterface Inflight {\n readonly abort: () => void\n readonly done: Promise<void>\n}\n\n\nexport function emptyResult(): RunResult {\n return { stdout: '', truncated: false }\n}\n\nexport class GitRunner {\n private readonly gitPath: string\n private readonly maxOutputBytes: number\n private readonly timeoutMs: number\n private readonly inflight = new Set<Inflight>()\n private disposed = false\n\n constructor(options: GitRunnerOptions = {}) {\n this.gitPath = options.gitPath ?? 'git'\n this.maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n }\n\n /** Abort every in-flight `git` process and wait for each to exit. Later calls reject. */\n async dispose(): Promise<void> {\n this.disposed = true\n const pending = [...this.inflight]\n for (const entry of pending) entry.abort()\n await Promise.all(pending.map(entry => entry.done))\n }\n\n async resolveDirectory(path: string): Promise<string> {\n if (typeof path !== 'string' || path.length === 0 || path.includes('\\0') || !isAbsolute(path)) {\n throw new WorkspaceGitError('path must be an absolute directory', 'invalid')\n }\n let real: string\n try {\n real = await realpath(path)\n if (!(await stat(real)).isDirectory()) throw new Error('not a directory')\n } catch {\n throw new WorkspaceGitError('path is not an existing directory', 'invalid')\n }\n return real\n }\n\n run(args: readonly string[], cwd: string, acceptExit?: number, timeoutMs?: number): Promise<RunResult> {\n if (this.disposed) return Promise.reject(new WorkspaceGitError('git service is disposed', 'failed'))\n const controller = new AbortController()\n let settle!: () => void\n const done = new Promise<void>((resolve) => { settle = resolve })\n const entry: Inflight = { abort: () => { controller.abort() }, done }\n this.inflight.add(entry)\n const env: NodeJS.ProcessEnv = {\n ...process.env,\n GIT_OPTIONAL_LOCKS: '0',\n GIT_TERMINAL_PROMPT: '0',\n GIT_PAGER: 'cat',\n LC_ALL: 'C',\n }\n delete env.GIT_DIR\n delete env.GIT_WORK_TREE\n delete env.GIT_INDEX_FILE\n return new Promise<RunResult>((resolve, reject) => {\n const child = execFile(\n this.gitPath,\n [...GLOBAL_ARGS, ...args],\n {\n cwd,\n env,\n encoding: 'utf8',\n maxBuffer: this.maxOutputBytes,\n timeout: timeoutMs ?? this.timeoutMs,\n signal: controller.signal,\n },\n (failure, stdout, stderr) => {\n if (failure === null) {\n resolve({ stdout, truncated: false })\n return\n }\n const info = failure as NodeJS.ErrnoException & { stdout?: string }\n if (info.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {\n resolve({ stdout: info.stdout ?? stdout, truncated: true })\n return\n }\n if (typeof info.code === 'number' && info.code === acceptExit) {\n resolve({ stdout, truncated: false })\n return\n }\n if (/not a git repository/i.test(stderr)) {\n reject(new WorkspaceGitError('not a git repository', 'not-repo'))\n return\n }\n reject(new WorkspaceGitError(`git ${args[0] ?? ''} failed`, 'failed'))\n },\n )\n // execFile's callback fires as soon as an abort is requested, before the process has exited.\n // Only the child's `close` (or a spawn `error`) proves it is gone, so that is what disposal awaits.\n const finished = (): void => {\n this.inflight.delete(entry)\n settle()\n }\n child.once('close', finished)\n child.once('error', finished)\n })\n }\n}\n","/** What changed in a worktree: the status list, one file's diff, and staging. Nothing here commits. */\n\nimport type { GitDiffView, GitStatusView } from './contract.ts'\nimport { WorkspaceGitError } from './errors.ts'\nimport { assertFileList, assertRelativeFile } from './guards.ts'\nimport { parseNumstat, parsePorcelain } from './parsing.ts'\nimport { emptyResult, type GitRunner, type RunResult } from './runner.ts'\n\nexport class WorkspaceChanges {\n constructor(private readonly git: GitRunner, private readonly maxChanges: number) {}\n\n /**\n * Changed files in one worktree, versus HEAD.\n * @param path - absolute worktree directory.\n */\n async status(path: string): Promise<GitStatusView> {\n const dir = await this.git.resolveDirectory(path)\n const [porcelain, numstat, branch] = await Promise.all([\n this.git.run(['status', '--porcelain=v1', '-z', '--untracked-files=all'], dir),\n this.git.run(['diff', '--numstat', '-z', 'HEAD', '--'], dir).catch(emptyResult),\n this.git.run(['branch', '--show-current'], dir).catch(emptyResult),\n ])\n const counts = parseNumstat(numstat.stdout)\n const all = parsePorcelain(porcelain.stdout, counts)\n const truncated = porcelain.truncated || all.length > this.maxChanges\n const name = branch.stdout.trim()\n return {\n path: dir,\n branch: name === '' ? null : name,\n changes: all.slice(0, this.maxChanges),\n truncated,\n }\n }\n\n /**\n * Unified diff of one file against HEAD (untracked files diff against nothing).\n * @param path - absolute worktree directory.\n * @param file - path relative to that worktree.\n */\n async diff(path: string, file: string): Promise<GitDiffView> {\n const dir = await this.git.resolveDirectory(path)\n assertRelativeFile(file)\n const untracked = (await this.git.run(['ls-files', '--others', '--exclude-standard', '-z', '--', file], dir)).stdout.length > 0\n const flags = ['--no-color', '--no-ext-diff', '--no-textconv'] as const\n let result: RunResult\n if (untracked) {\n // `git diff --no-index` exits 1 when the files differ, which is the normal case here.\n result = await this.git.run(['diff', '--no-index', ...flags, '--', '/dev/null', file], dir, 1)\n } else {\n try {\n result = await this.git.run(['diff', ...flags, 'HEAD', '--', file], dir)\n } catch (cause) {\n // A repository with no commits has no HEAD; fall back to the index against the empty tree.\n if (!(cause instanceof WorkspaceGitError) || cause.kind !== 'failed') throw cause\n result = await this.git.run(['diff', '--cached', ...flags, '--', file], dir)\n }\n }\n const binary = /^Binary files .* differ$/m.test(result.stdout) || result.stdout.includes('GIT binary patch')\n return { path: dir, file, text: binary ? '' : result.stdout, binary, truncated: result.truncated }\n }\n\n /**\n * Stage files (`git add`), then report the worktree's status.\n * @param path - absolute worktree directory.\n * @param files - paths relative to that worktree.\n */\n async stage(path: string, files: readonly string[]): Promise<GitStatusView> {\n const dir = await this.git.resolveDirectory(path)\n assertFileList(files)\n await this.git.run(['add', '--', ...files], dir)\n return this.status(dir)\n }\n\n /**\n * Unstage files, keeping their working-tree changes, then report the status. Works before the first commit too.\n */\n async unstage(path: string, files: readonly string[]): Promise<GitStatusView> {\n const dir = await this.git.resolveDirectory(path)\n assertFileList(files)\n try {\n await this.git.run(['reset', '-q', 'HEAD', '--', ...files], dir)\n } catch {\n // No HEAD yet (an empty repository): dropping the paths from the index is the same thing.\n await this.git.run(['rm', '--cached', '-r', '-q', '--', ...files], dir)\n }\n return this.status(dir)\n }\n}\n","/** Read-only discovery of the checks a worktree can run: its package.json scripts and package manager. */\n\nimport { readFile, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { CheckManager, CheckScript, GitChecksView } from './contract.ts'\n\nconst MAX_PACKAGE_JSON_BYTES = 256 * 1024\nconst MAX_SCRIPTS = 60\n/** A script name is typed into a shell on the user's behalf, so only plain names are ever offered. */\nconst SAFE_SCRIPT_NAME = /^[A-Za-z0-9][A-Za-z0-9:_.-]{0,63}$/\nconst PRIMARY = /^(check|verify|ci|test|tests|lint|typecheck|type-check|build|format)([:._-].*)?$/i\n\nconst LOCKFILES: readonly (readonly [string, CheckManager])[] = [\n ['pnpm-lock.yaml', 'pnpm'],\n ['yarn.lock', 'yarn'],\n ['bun.lock', 'bun'],\n ['bun.lockb', 'bun'],\n ['package-lock.json', 'npm'],\n]\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path)\n return true\n } catch {\n return false\n }\n}\n\n/** The manager the project itself uses: its lockfile, else null (the caller then runs plain `npm`). */\nexport async function detectManager(dir: string): Promise<CheckManager | null> {\n for (const [file, manager] of LOCKFILES) {\n if (await exists(join(dir, file))) return manager\n }\n return null\n}\n\n/** Parse `package.json` scripts; a missing, oversized or malformed file simply means \"no scripts\". */\nexport function parseScripts(text: string): CheckScript[] {\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return []\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return []\n const scripts = (parsed as { scripts?: unknown }).scripts\n if (typeof scripts !== 'object' || scripts === null || Array.isArray(scripts)) return []\n const out: CheckScript[] = []\n for (const [name, command] of Object.entries(scripts)) {\n if (typeof command !== 'string' || !SAFE_SCRIPT_NAME.test(name)) continue\n out.push({ name, command: command.slice(0, 300), primary: PRIMARY.test(name) })\n }\n // Check-like scripts first, otherwise keep the file's order.\n out.sort((a, b) => Number(b.primary) - Number(a.primary))\n return out.slice(0, MAX_SCRIPTS)\n}\n\n/** @param dir - an already validated absolute worktree directory. */\nexport async function readWorktreeChecks(dir: string): Promise<GitChecksView> {\n let scripts: CheckScript[] = []\n try {\n const file = join(dir, 'package.json')\n if ((await stat(file)).size <= MAX_PACKAGE_JSON_BYTES) scripts = parseScripts(await readFile(file, 'utf8'))\n } catch {\n scripts = []\n }\n return { path: dir, manager: await detectManager(dir), scripts }\n}\n","/** Committing what is staged. It never pushes and never bypasses hooks. */\n\nimport type { GitCommitView } from './contract.ts'\nimport { MAX_COMMIT_MESSAGE } from './contract.ts'\nimport type { WorkspaceChanges } from './changes.ts'\nimport { WorkspaceGitError } from './errors.ts'\nimport type { GitRunner } from './runner.ts'\n\nconst COMMIT_TIMEOUT_MS = 120_000\n\nexport class WorkspaceCommits {\n constructor(private readonly git: GitRunner, private readonly changes: WorkspaceChanges) {}\n\n /**\n * Commit what is staged. Refuses an empty message, nothing staged, or a missing git identity with a reason the\n * user can act on; never pushes, and never bypasses hooks.\n */\n async commit(path: string, message: string): Promise<GitCommitView> {\n const dir = await this.git.resolveDirectory(path)\n const text = typeof message === 'string' ? message.trim() : ''\n if (text === '' || text.length > MAX_COMMIT_MESSAGE || text.includes('\\0')) {\n throw new WorkspaceGitError('write a commit message (up to 5000 characters)', 'invalid')\n }\n if ((await this.git.run(['diff', '--cached', '--name-only', '-z'], dir)).stdout === '') {\n throw new WorkspaceGitError('nothing is staged to commit', 'conflict')\n }\n try {\n await this.git.run(['var', 'GIT_AUTHOR_IDENT'], dir)\n } catch {\n throw new WorkspaceGitError('git does not know who you are: set user.name and user.email first', 'conflict')\n }\n try {\n await this.git.run(['commit', '-q', '-m', text], dir, undefined, COMMIT_TIMEOUT_MS)\n } catch {\n throw new WorkspaceGitError('git could not commit (a commit hook may have refused it)', 'conflict')\n }\n const [hash, subject] = await Promise.all([\n this.git.run(['rev-parse', '--short', 'HEAD'], dir),\n this.git.run(['log', '-1', '--format=%s'], dir),\n ])\n return { hash: hash.stdout.trim(), subject: subject.stdout.trim(), status: await this.changes.status(dir) }\n }\n}\n","/** Which entries of one directory git ignores, for the file tree to show them dimmed. */\n\nimport type { GitRunner } from './runner.ts'\n\n/**\n * @param git - the runner.\n * @param root - absolute worktree root (its real path).\n * @param paths - entries relative to the root, `/`-separated; a directory ends in `/`, so directory-only patterns (`build/`) apply.\n * @returns the given paths git ignores; none when git cannot answer (the tree then shows everything undimmed).\n */\nexport async function ignoredPaths(git: GitRunner, root: string, paths: readonly string[]): Promise<ReadonlySet<string>> {\n if (paths.length === 0) return new Set()\n try {\n // Exit 1 means none of them is ignored. One path per line (`-z` needs `--stdin`, which the runner has no input for); a name git still\n // quotes (a newline or a quote in it) does not match and is shown undimmed.\n const result = await git.run(['-c', 'core.quotePath=false', 'check-ignore', '--', ...paths], root, 1)\n return new Set(result.stdout.split('\\n').filter(path => path !== ''))\n } catch {\n return new Set()\n }\n}\n","/** Repo-wide search over the files git tracks or would track: by name or by content. */\n\nimport type { GitSearchMode, GitSearchView } from './contract.ts'\nimport { MAX_SEARCH_QUERY, MAX_SEARCH_RESULTS } from './contract.ts'\nimport { WorkspaceGitError } from './errors.ts'\nimport type { GitRunner } from './runner.ts'\n\nexport class WorkspaceSearch {\n constructor(private readonly git: GitRunner) {}\n\n /**\n * Find files by name, or lines by content, among the tracked and untracked files git does not ignore.\n * Case-insensitive and literal (the query is never a pattern), so it cannot be a regular-expression trap.\n * @param path - absolute worktree directory.\n * @param query - what to look for.\n */\n async search(path: string, query: string, mode: GitSearchMode): Promise<GitSearchView> {\n const dir = await this.git.resolveDirectory(path)\n const text = typeof query === 'string' ? query.trim() : ''\n if (text === '' || text.length > MAX_SEARCH_QUERY || text.includes('\\0') || (mode !== 'name' && mode !== 'content')) {\n throw new WorkspaceGitError('type something to search for (up to 200 characters)', 'invalid')\n }\n if (mode === 'name') {\n const listed = await this.git.run(['ls-files', '-z', '--cached', '--others', '--exclude-standard'], dir)\n const needle = text.toLowerCase()\n const matches = listed.stdout.split('\\0').filter(file => file !== '' && file.toLowerCase().includes(needle))\n // A match in the file's own name outranks one in a folder name; then shorter and alphabetical.\n const inName = (file: string): boolean => (file.split('/').pop() ?? file).toLowerCase().includes(needle)\n matches.sort((a, b) => Number(inName(b)) - Number(inName(a)) || a.length - b.length || a.localeCompare(b))\n return {\n path: dir, query: text, mode,\n hits: matches.slice(0, MAX_SEARCH_RESULTS).map(file => ({ file })),\n truncated: matches.length > MAX_SEARCH_RESULTS || listed.truncated,\n }\n }\n const found = await this.git.run(['grep', '-n', '-I', '-i', '-F', '-z', '--untracked', '-e', text, '--'], dir, 1)\n const hits: { file: string; line: number; text: string }[] = []\n let truncated = found.truncated\n // With -z each hit is `file NUL line NUL text` and hits are separated by a newline.\n for (const record of found.stdout.split('\\n')) {\n if (record === '') continue\n const [file, line, ...rest] = record.split('\\0')\n if (file === undefined || line === undefined || !/^\\d+$/.test(line)) continue\n if (hits.length >= MAX_SEARCH_RESULTS) { truncated = true; break }\n hits.push({ file, line: Number(line), text: rest.join('\\0').slice(0, 300) })\n }\n return { path: dir, query: text, mode, hits, truncated }\n }\n}\n","/** Repositories and their worktrees: listing them, confirming a path is one, and creating one. */\n\nimport { mkdir, realpath, stat } from 'node:fs/promises'\nimport { basename, dirname, join, normalize } from 'node:path'\nimport type { GitRepoView, GitWorktreeCreatedView } from './contract.ts'\nimport { WorkspaceGitError } from './errors.ts'\nimport { assertBranchName } from './guards.ts'\nimport { parseWorktrees } from './parsing.ts'\nimport type { GitRunner } from './runner.ts'\n\n/** Checking out a large repository can take far longer than a status call. */\nconst WORKTREE_ADD_TIMEOUT_MS = 120_000\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path)\n return true\n } catch {\n return false\n }\n}\n\nexport class WorkspaceWorktrees {\n constructor(private readonly git: GitRunner) {}\n\n /**\n * List the repository's worktrees.\n * @param cwd - any directory inside the repository.\n * @returns the repository view, or null when `cwd` is not inside a git repository.\n */\n async repo(cwd: string): Promise<GitRepoView | null> {\n const dir = await this.git.resolveDirectory(cwd)\n let current: string\n try {\n // Git reports `C:/repo` on Windows; the rest of the app speaks `C:\\repo`.\n current = normalize((await this.git.run(['rev-parse', '--show-toplevel'], dir)).stdout.trim())\n } catch (cause) {\n if (cause instanceof WorkspaceGitError && cause.kind === 'not-repo') return null\n throw cause\n }\n const listed = await this.git.run(['worktree', 'list', '--porcelain'], dir)\n const worktrees = parseWorktrees(listed.stdout)\n const main = worktrees[0]\n if (main === undefined) throw new WorkspaceGitError('git listed no worktrees', 'failed')\n return { name: basename(main.path), root: main.path, current, worktrees }\n }\n\n /**\n * Confirm `path` is the root of a git worktree and return its real path. The file routes use this so\n * they only ever touch a checkout, never an arbitrary directory.\n * @throws WorkspaceGitError `invalid` when the path is not a worktree root.\n */\n async worktreeRoot(path: string): Promise<string> {\n const dir = await this.git.resolveDirectory(path)\n const top = (await this.git.run(['rev-parse', '--show-toplevel'], dir)).stdout.trim()\n let real: string\n try {\n real = await realpath(top)\n } catch {\n throw new WorkspaceGitError('path is not a git worktree', 'invalid')\n }\n if (real !== dir) throw new WorkspaceGitError('path is not the root of a git worktree', 'invalid')\n return dir\n }\n\n /**\n * Create a branch and a worktree for it in the repository's sibling `<repo>.worktrees/` folder,\n * which never dirties the repository. The branch starts at the main worktree's current commit.\n * @param cwd - any directory inside the repository.\n * @param branch - the new branch name.\n */\n async createWorktree(cwd: string, branch: string): Promise<GitWorktreeCreatedView> {\n assertBranchName(branch)\n const view = await this.repo(cwd)\n if (view === null) throw new WorkspaceGitError('not a git repository', 'not-repo')\n // Git has the last word on what a valid branch name is.\n try {\n await this.git.run(['check-ref-format', '--branch', branch], view.root)\n } catch {\n throw new WorkspaceGitError('that is not a valid branch name', 'invalid')\n }\n if ((await this.git.run(['branch', '--list', branch], view.root)).stdout.trim() !== '') {\n throw new WorkspaceGitError(`the branch ${branch} already exists`, 'conflict')\n }\n const parent = join(dirname(view.root), `${basename(view.root)}.worktrees`)\n const target = join(parent, branch.replace(/\\//g, '-'))\n if (await pathExists(target)) throw new WorkspaceGitError('that worktree folder already exists', 'conflict')\n await mkdir(parent, { recursive: true })\n await this.git.run(['worktree', 'add', '-b', branch, target], view.root, undefined, WORKTREE_ADD_TIMEOUT_MS)\n const path = await realpath(target)\n const after = await this.repo(path)\n if (after === null) throw new WorkspaceGitError('the new worktree is not readable', 'failed')\n return { path, branch, repo: after }\n }\n}\n","/**\n * The Workspace's git access, as one facade over focused modules.\n *\n * Each use case lives in its own module and reaches git only through the confined {@link GitRunner}\n * (argument arrays, timeouts, output caps, no shell):\n * - `worktrees.ts` repositories and worktrees\n * - `changes.ts` status, diff, stage, unstage\n * - `commits.ts` commit (never pushes)\n * - `search.ts` repo-wide search\n * - `checks.ts` package scripts a worktree can run\n * The facade exists so the routes and the file routes keep one collaborator to depend on.\n */\n\nimport type {\n GitChecksView,\n GitCommitView,\n GitDiffView,\n GitRepoView,\n GitSearchMode,\n GitSearchView,\n GitStatusView,\n GitWorktreeCreatedView,\n} from './contract.ts'\nimport { WorkspaceChanges } from './changes.ts'\nimport { readWorktreeChecks } from './checks.ts'\nimport { WorkspaceCommits } from './commits.ts'\nimport { ignoredPaths } from './ignored.ts'\nimport { GitRunner, type GitRunnerOptions } from './runner.ts'\nimport { WorkspaceSearch } from './search.ts'\nimport { WorkspaceWorktrees } from './worktrees.ts'\n\nexport { WorkspaceGitError } from './errors.ts'\nexport { parseNumstat, parsePorcelain, parseWorktrees } from './parsing.ts'\n\nconst DEFAULT_MAX_CHANGES = 1000\n\nexport interface WorkspaceGitOptions extends GitRunnerOptions {\n /** Cap on entries returned by `status`. */\n readonly maxChanges?: number\n}\n\nexport class WorkspaceGit {\n private readonly runner: GitRunner\n private readonly worktrees: WorkspaceWorktrees\n private readonly changes: WorkspaceChanges\n private readonly commits: WorkspaceCommits\n private readonly searcher: WorkspaceSearch\n\n constructor(options: WorkspaceGitOptions = {}) {\n this.runner = new GitRunner(options)\n this.worktrees = new WorkspaceWorktrees(this.runner)\n this.changes = new WorkspaceChanges(this.runner, options.maxChanges ?? DEFAULT_MAX_CHANGES)\n this.commits = new WorkspaceCommits(this.runner, this.changes)\n this.searcher = new WorkspaceSearch(this.runner)\n }\n\n /** The repository containing `cwd`, or null when it is not inside a git repository. */\n repo(cwd: string): Promise<GitRepoView | null> { return this.worktrees.repo(cwd) }\n\n /** Confirm `path` is the root of a git worktree and return its real path. */\n worktreeRoot(path: string): Promise<string> { return this.worktrees.worktreeRoot(path) }\n\n /** Create a branch and a worktree for it in the repository's sibling `<repo>.worktrees/` folder. */\n createWorktree(cwd: string, branch: string): Promise<GitWorktreeCreatedView> { return this.worktrees.createWorktree(cwd, branch) }\n\n /** Changed files in one worktree, versus HEAD. */\n status(path: string): Promise<GitStatusView> { return this.changes.status(path) }\n\n /** Unified diff of one file against HEAD (untracked files diff against nothing). */\n diff(path: string, file: string): Promise<GitDiffView> { return this.changes.diff(path, file) }\n\n /** Stage files, then report the worktree's status. */\n stage(path: string, files: readonly string[]): Promise<GitStatusView> { return this.changes.stage(path, files) }\n\n /** Unstage files, keeping their working-tree changes, then report the status. */\n unstage(path: string, files: readonly string[]): Promise<GitStatusView> { return this.changes.unstage(path, files) }\n\n /** Commit what is staged; never pushes. */\n commit(path: string, message: string): Promise<GitCommitView> { return this.commits.commit(path, message) }\n\n /** Find files by name, or lines by content, literally and case-insensitively. */\n search(path: string, query: string, mode: GitSearchMode): Promise<GitSearchView> { return this.searcher.search(path, query, mode) }\n\n /** Which of the given worktree-relative paths git ignores (a directory ends in `/`); none when git cannot say. */\n ignored(root: string, paths: readonly string[]): Promise<ReadonlySet<string>> { return ignoredPaths(this.runner, root, paths) }\n\n /** The scripts a worktree can run as checks, and its package manager. */\n async checks(path: string): Promise<GitChecksView> {\n return readWorktreeChecks(await this.runner.resolveDirectory(path))\n }\n\n /** Abort every in-flight `git` process and wait for each to exit. Later calls reject. */\n dispose(): Promise<void> { return this.runner.dispose() }\n}\n","/** The workspace git routes: five reads, and the writes the Changes panel makes (worktree, stage, unstage, commit), for the app's own page only. */\n\nimport { Acryl, type Context } from '@acryldev/blends'\nimport { INVALID_JSON, failure, isRecord, jsonBody, ownPage, readJson, type ReportError } from '../private-route.ts'\nimport {\n WORKSPACE_GIT_CHECKS_PATH,\n WORKSPACE_GIT_COMMIT_PATH,\n WORKSPACE_GIT_DIFF_PATH,\n WORKSPACE_GIT_REPO_PATH,\n WORKSPACE_GIT_SEARCH_PATH,\n WORKSPACE_GIT_STAGE_PATH,\n WORKSPACE_GIT_STATUS_PATH,\n WORKSPACE_GIT_UNSTAGE_PATH,\n WORKSPACE_GIT_WORKTREE_PATH,\n} from './contract.ts'\nimport { WorkspaceGitError, type WorkspaceGit } from './service.ts'\n\nfunction required(c: Context, name: string): string {\n const value = c.req.query(name)\n if (value === undefined || value.length === 0) throw new WorkspaceGitError(`missing ${name}`, 'invalid')\n return value\n}\n\ntype Parse<T> = (body: Record<string, unknown>) => T | undefined\n\nfunction parseFiles(body: Record<string, unknown>): { path: string, files: string[] } | undefined {\n if (Object.keys(body).length !== 2 || typeof body.path !== 'string' || !Array.isArray(body.files)) return undefined\n if (!body.files.every((file): file is string => typeof file === 'string')) return undefined\n return { path: body.path, files: body.files }\n}\n\nfunction parseWorktree(body: Record<string, unknown>): { cwd: string, branch: string } | undefined {\n if (Object.keys(body).length !== 2 || typeof body.cwd !== 'string' || typeof body.branch !== 'string') return undefined\n return { cwd: body.cwd, branch: body.branch }\n}\n\nfunction parseCommit(body: Record<string, unknown>): { path: string, message: string } | undefined {\n if (Object.keys(body).length !== 2 || typeof body.path !== 'string' || typeof body.message !== 'string') return undefined\n return { path: body.path, message: body.message }\n}\n\n/**\n * GET `repo?cwd=`, `status?path=`, `checks?path=`, `search?path=&q=&mode=name|content` and `diff?path=&file=`; POST `worktree` `{ cwd, branch }`\n * (create a branch and its worktree), `stage` and `unstage` `{ path, files }`, and `commit` `{ path, message }` (never pushes).\n */\nexport function gitRoutes(git: WorkspaceGit, reportError: ReportError): Acryl {\n const answer = async (c: Context, operation: string, compute: () => Promise<object | null>): Promise<Response> => {\n try {\n const view = await compute()\n if (view === null) return c.json(failure('not a git repository'), 404)\n return c.json(view)\n } catch (cause) {\n if (cause instanceof WorkspaceGitError) {\n if (cause.kind === 'invalid') return c.json(failure(cause.message), 400)\n if (cause.kind === 'conflict') return c.json(failure(cause.message), 409)\n if (cause.kind === 'not-repo') return c.json(failure('not a git repository'), 404)\n }\n reportError(operation, cause)\n return c.json(failure('git request failed'), 500)\n }\n }\n /** A small JSON body, parsed strictly, then one git write answered with its result. */\n const write = <T>(operation: string, invalid: string, parse: Parse<T>, compute: (input: T) => Promise<object>) => async (c: Context): Promise<Response> => {\n const body = await readJson(c)\n const input = body === INVALID_JSON || !isRecord(body) ? undefined : parse(body)\n if (input === undefined) return c.json(failure(invalid), 400)\n return answer(c, operation, () => compute(input))\n }\n return new Acryl()\n // 200 with `{ repo: null }` for a directory that is not a repository: that is an ordinary answer, and a 404 would print a console error for\n // every temporary folder a chat session uses.\n .get(WORKSPACE_GIT_REPO_PATH, ownPage, c => answer(c, 'read git repo', async () => ({ repo: await git.repo(required(c, 'cwd')) })))\n .get(WORKSPACE_GIT_STATUS_PATH, ownPage, c => answer(c, 'read git status', () => git.status(required(c, 'path'))))\n .get(WORKSPACE_GIT_CHECKS_PATH, ownPage, c => answer(c, 'read checks', () => git.checks(required(c, 'path'))))\n .get(WORKSPACE_GIT_SEARCH_PATH, ownPage, c => answer(c, 'search', () =>\n git.search(required(c, 'path'), required(c, 'q'), c.req.query('mode') === 'content' ? 'content' : 'name')))\n .get(WORKSPACE_GIT_DIFF_PATH, ownPage, c => answer(c, 'read git diff', () => git.diff(required(c, 'path'), required(c, 'file'))))\n .post(WORKSPACE_GIT_WORKTREE_PATH, ownPage, jsonBody(), write('create git worktree', 'invalid worktree request', parseWorktree,\n input => git.createWorktree(input.cwd, input.branch)))\n .post(WORKSPACE_GIT_STAGE_PATH, ownPage, jsonBody(), write('stage', 'invalid stage request', parseFiles, input => git.stage(input.path, input.files)))\n .post(WORKSPACE_GIT_UNSTAGE_PATH, ownPage, jsonBody(), write('unstage', 'invalid unstage request', parseFiles,\n input => git.unstage(input.path, input.files)))\n .post(WORKSPACE_GIT_COMMIT_PATH, ownPage, jsonBody(), write('commit', 'invalid commit request', parseCommit, input => git.commit(input.path, input.message)))\n}\n","/**\n * 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\n * `@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\n * way round.\n */\n\nexport const WORKSPACE_PROJECTS_PATH = '/api/acryl-workspace/projects'\n/** A server-sent event stream of the registry's view: one message now, then one per change (an agent's tool call, another window). */\nexport const WORKSPACE_PROJECTS_EVENTS_PATH = '/api/acryl-workspace/projects/events'\n\n/** How a workspace is organized (spec 043): separate projects, projects that share context with every agent, or a remote machine. */\nexport type WorkspaceKind = 'individual' | 'shared' | 'remote'\n\nexport const WORKSPACE_KINDS: readonly WorkspaceKind[] = ['individual', 'shared', 'remote']\n\n/** The workspace every app has: it cannot be deleted, and the folders added before workspaces existed are its projects. */\nexport const DEFAULT_WORKSPACE_ID = 'default'\n\n/** One workspace as the page sees it. */\nexport interface WorkspaceSummary {\n readonly id: string\n readonly name: string\n readonly kind: WorkspaceKind\n /** Absolute folder paths, in the order they were added. */\n readonly projects: readonly string[]\n /** For a remote workspace: the SSH target saved for the connection that comes later. */\n readonly remote?: { readonly host: string, readonly user?: string, readonly path?: string }\n}\n\nexport interface ProjectRegistryView {\n /** The shown workspace's folders, in the order the user added them. */\n readonly paths: readonly string[]\n /** The projects that already existed as DSH workspaces were taken over once (see `adopt`). */\n readonly adopted: boolean\n /** Every workspace, Default first. */\n readonly workspaces: readonly WorkspaceSummary[]\n /** The id of the workspace the sidebar shows. */\n readonly current: string\n}\n\nexport type ProjectRequest =\n | { readonly op: 'add'; readonly path: string }\n | { readonly op: 'remove'; readonly path: string }\n /** Take over folders that were registered before ACRYL owned the list. Applied once; later calls change nothing. */\n | { readonly op: 'adopt'; readonly paths: readonly string[] }\n | { readonly op: 'create-workspace'; readonly name: string; readonly kind: WorkspaceKind; readonly remote?: { readonly host: string, readonly user?: string, readonly path?: string } }\n | { readonly op: 'switch-workspace'; readonly id: string }\n | { readonly op: 'rename-workspace'; readonly id: string; readonly name: string }\n | { readonly op: 'delete-workspace'; readonly id: string }\n\nexport type ProjectResponse =\n | { readonly ok: true; readonly view: ProjectRegistryView }\n | { readonly ok: false; readonly code: 'invalid' | 'not-a-folder' | 'workspace'; readonly message: string }\n\nexport class ProjectRequestError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ProjectRequestError'\n }\n}\n\nconst MAX_ADOPTED = 500\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction only(record: Record<string, unknown>, allowed: readonly string[]): void {\n const extra = Object.keys(record).find(key => key !== 'op' && !allowed.includes(key))\n if (extra !== undefined) throw new ProjectRequestError(`unknown field \"${extra}\"`)\n}\n\nfunction pathOf(value: unknown): string {\n if (typeof value !== 'string' || value.trim() === '' || value.length > 4096) throw new ProjectRequestError('path must be the absolute path of a folder')\n return value\n}\n\n/** @throws ProjectRequestError naming what is wrong; nothing is coerced. */\nexport function parseProjectRequest(value: unknown): ProjectRequest {\n if (!isRecord(value) || typeof value.op !== 'string') throw new ProjectRequestError('the request must be an object with an op')\n switch (value.op) {\n case 'add':\n case 'remove':\n only(value, ['path'])\n return { op: value.op, path: pathOf(value.path) }\n case 'adopt': {\n only(value, ['paths'])\n 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`)\n return { op: 'adopt', paths: value.paths.map(pathOf) }\n }\n case 'create-workspace': {\n only(value, ['name', 'kind', 'remote'])\n if (typeof value.kind !== 'string' || !(WORKSPACE_KINDS as readonly string[]).includes(value.kind)) throw new ProjectRequestError(`kind must be one of ${WORKSPACE_KINDS.join(', ')}`)\n const remote = value.remote === undefined ? undefined : remoteOf(value.remote)\n return { op: 'create-workspace', name: textOf(value.name, 'name'), kind: value.kind as WorkspaceKind, ...(remote === undefined ? {} : { remote }) }\n }\n case 'switch-workspace':\n case 'delete-workspace':\n only(value, ['id'])\n return { op: value.op, id: textOf(value.id, 'id') }\n case 'rename-workspace':\n only(value, ['id', 'name'])\n return { op: 'rename-workspace', id: textOf(value.id, 'id'), name: textOf(value.name, 'name') }\n default:\n throw new ProjectRequestError(`unknown op \"${value.op}\"`)\n }\n}\n\nfunction textOf(value: unknown, field: string): string {\n if (typeof value !== 'string' || value.length > 200) throw new ProjectRequestError(`${field} must be a short text`)\n return value\n}\n\nfunction remoteOf(value: unknown): { host: string, user?: string, path?: string } {\n if (!isRecord(value)) throw new ProjectRequestError('remote must be an object with a host')\n const extra = Object.keys(value).find(key => !['host', 'user', 'path'].includes(key))\n if (extra !== undefined) throw new ProjectRequestError(`unknown remote field \"${extra}\"`)\n return {\n host: textOf(value.host, 'remote.host'),\n ...(value.user === undefined ? {} : { user: textOf(value.user, 'remote.user') }),\n ...(value.path === undefined ? {} : { path: textOf(value.path, 'remote.path') }),\n }\n}\n\nfunction isStringList(value: unknown): value is string[] {\n return Array.isArray(value) && value.every(item => typeof item === 'string')\n}\n\nfunction workspaceOf(value: unknown): WorkspaceSummary {\n if (!isRecord(value) || typeof value.id !== 'string' || typeof value.name !== 'string' || !(WORKSPACE_KINDS as readonly unknown[]).includes(value.kind) || !isStringList(value.projects)) {\n throw new ProjectRequestError('the registry view is malformed')\n }\n const remote = value.remote === undefined ? undefined : remoteOf(value.remote)\n return { id: value.id, name: value.name, kind: value.kind as WorkspaceKind, projects: value.projects, ...(remote === undefined ? {} : { remote }) }\n}\n\nexport function parseProjectRegistryView(value: unknown): ProjectRegistryView {\n if (!isRecord(value) || !isStringList(value.paths) || typeof value.adopted !== 'boolean' || !Array.isArray(value.workspaces) || typeof value.current !== 'string') {\n throw new ProjectRequestError('the registry view is malformed')\n }\n return { paths: value.paths, adopted: value.adopted, workspaces: value.workspaces.map(workspaceOf), current: value.current }\n}\n","/**\n * The project registry: the folders the user added, grouped into workspaces (spec 043), in one `@acryldev/settings` section, changed one write at a time.\n * 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\n * existed. A project can be in several workspaces; removing it from one never touches the others or the disk.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { statSync } from 'node:fs'\nimport { isAbsolute, resolve } from 'node:path'\nimport type { SettingsScope } from '@acryldev/settings'\nimport z from '@deepseek-ai/schemastery'\nimport { DEFAULT_WORKSPACE_ID, type ProjectRegistryView, type WorkspaceKind, type WorkspaceSummary } from './contract.ts'\n\nexport const PROJECTS_NAMESPACE = 'workspace'\n\nexport { DEFAULT_WORKSPACE_ID }\n\nexport interface RemoteTarget {\n host: string\n user?: string\n path?: string\n}\n\nexport interface WorkspaceRecord {\n id: string\n name: string\n kind: WorkspaceKind\n projects: string[]\n remote?: RemoteTarget\n}\n\nexport interface ProjectsSection {\n /** The folders added before workspaces existed: read once to build Default, then left empty. */\n projects: string[]\n adopted: boolean\n workspaces: WorkspaceRecord[]\n current: string\n}\n\nconst WorkspaceSchema: z<WorkspaceRecord> = z.object({\n id: z.string().required(),\n name: z.string().required(),\n kind: z.union(['individual', 'shared', 'remote']).default('individual'),\n projects: z.array(z.string()).default([]),\n // Validated in code (validRemote) where it applies: a schema-required host would also be demanded of workspaces that have no remote.\n remote: z.object({ host: z.string(), user: z.string(), path: z.string() }),\n})\n\n/** The section's schema: the workspaces with their folders, the one shown, and whether the pre-existing folders were taken over. */\nexport const ProjectsSchema: z<ProjectsSection> = z.object({\n projects: z.array(z.string()).default([]).description('Folders added before workspaces existed; moved into the Default workspace.'),\n adopted: z.boolean().default(false).description('Projects registered before ACRYL owned the list were taken over once.'),\n workspaces: z.array(WorkspaceSchema).default([]).description('Workspaces: named sets of projects, Default first.'),\n current: z.string().default(DEFAULT_WORKSPACE_ID).description('The workspace the sidebar shows.'),\n})\n\n/** A request the registry refuses (an unknown workspace, a duplicate name, deleting Default). */\nexport class WorkspaceError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'WorkspaceError'\n }\n}\n\nconst MAX_NAME_LENGTH = 60\n\nexport class ProjectFolderError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ProjectFolderError'\n }\n}\n\n/** The canonical form of a project folder: absolute, no trailing separator. @throws ProjectFolderError for anything that is not an existing folder. */\nexport function normalizeProjectFolder(path: string): string {\n if (!isAbsolute(path)) throw new ProjectFolderError(`${path} is not an absolute path`)\n const folder = resolve(path)\n let stat\n try {\n stat = statSync(folder)\n } catch {\n throw new ProjectFolderError(`${folder} does not exist`)\n }\n if (!stat.isDirectory()) throw new ProjectFolderError(`${folder} is not a folder`)\n return folder\n}\n\nexport class ProjectRegistry {\n private readonly listeners = new Set<(view: ProjectRegistryView) => void>()\n\n constructor(private readonly scope: SettingsScope<ProjectsSection>) {}\n\n /** Observe every saved change, whoever made it (a page, an agent's tool). @returns disposer. */\n onChange(listener: (view: ProjectRegistryView) => void): () => void {\n this.listeners.add(listener)\n return () => { this.listeners.delete(listener) }\n }\n\n view(): ProjectRegistryView {\n const section = this.scope.get()\n const workspaces = this.workspaces()\n const current = this.current(workspaces)\n return {\n paths: [...current.projects],\n adopted: section.adopted,\n workspaces: workspaces.map(summary),\n current: current.id,\n }\n }\n\n /** Add a folder to the workspace shown. */\n async add(path: string): Promise<ProjectRegistryView> {\n const folder = normalizeProjectFolder(path)\n const workspaces = this.workspaces()\n const current = this.current(workspaces)\n if (current.projects.includes(folder)) return this.view()\n return this.save(workspaces.map(workspace => (workspace.id === current.id ? { ...workspace, projects: [...workspace.projects, folder] } : workspace)), current.id)\n }\n\n /** 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. */\n async remove(path: string): Promise<ProjectRegistryView> {\n const folder = resolve(path)\n const workspaces = this.workspaces()\n const current = this.current(workspaces)\n if (!current.projects.includes(folder)) return this.view()\n return this.save(workspaces.map(workspace => (workspace.id === current.id ? { ...workspace, projects: workspace.projects.filter(candidate => candidate !== folder) } : workspace)), current.id)\n }\n\n /** Take over folders registered elsewhere, once, into Default. Folders that no longer exist are skipped, not fatal. */\n async adopt(paths: readonly string[]): Promise<ProjectRegistryView> {\n if (this.scope.get().adopted) return this.view()\n const workspaces = this.workspaces()\n const merged = [...this.defaultOf(workspaces).projects]\n for (const path of paths) {\n try {\n const folder = normalizeProjectFolder(path)\n if (!merged.includes(folder)) merged.push(folder)\n } catch {\n // A project that has since been deleted is not carried over.\n }\n }\n return this.save(workspaces.map(workspace => (workspace.id === DEFAULT_WORKSPACE_ID ? { ...workspace, projects: merged } : workspace)), this.current(workspaces).id, true)\n }\n\n /** Create a workspace and show it. @throws WorkspaceError for an empty or taken name, or a remote one without a host. */\n async createWorkspace(input: { readonly name: string, readonly kind: WorkspaceKind, readonly remote?: RemoteTarget }): Promise<ProjectRegistryView> {\n const workspaces = this.workspaces()\n const name = this.validName(input.name, workspaces)\n const remote = input.kind === 'remote' ? validRemote(input.remote) : undefined\n const record: WorkspaceRecord = { id: `ws-${randomUUID().slice(0, 8)}`, name, kind: input.kind, projects: [], ...(remote === undefined ? {} : { remote }) }\n return this.save([...workspaces, record], record.id)\n }\n\n /** Show another workspace. */\n async switchWorkspace(id: string): Promise<ProjectRegistryView> {\n const workspaces = this.workspaces()\n this.find(workspaces, id)\n return this.save(workspaces, id)\n }\n\n async renameWorkspace(id: string, name: string): Promise<ProjectRegistryView> {\n const workspaces = this.workspaces()\n this.find(workspaces, id)\n const valid = this.validName(name, workspaces.filter(workspace => workspace.id !== id))\n return this.save(workspaces.map(workspace => (workspace.id === id ? { ...workspace, name: valid } : workspace)), this.current(workspaces).id)\n }\n\n /** Delete a workspace (never Default). Its projects stay in other workspaces and on disk; the sidebar shows Default if it was shown. */\n async deleteWorkspace(id: string): Promise<ProjectRegistryView> {\n if (id === DEFAULT_WORKSPACE_ID) throw new WorkspaceError('The Default workspace cannot be deleted.')\n const workspaces = this.workspaces()\n this.find(workspaces, id)\n const current = this.current(workspaces).id\n return this.save(workspaces.filter(workspace => workspace.id !== id), current === id ? DEFAULT_WORKSPACE_ID : current)\n }\n\n /** The workspaces, Default first; before the first workspace write, Default is built from the pre-workspace folder list. */\n private workspaces(): WorkspaceRecord[] {\n const section = this.scope.get()\n const stored = section.workspaces.map(({ remote, ...workspace }): WorkspaceRecord => ({\n ...workspace,\n projects: [...workspace.projects],\n ...(workspace.kind === 'remote' && remote !== undefined && typeof remote.host === 'string' && remote.host !== '' ? { remote } : {}),\n }))\n if (stored.some(workspace => workspace.id === DEFAULT_WORKSPACE_ID)) return stored\n return [{ id: DEFAULT_WORKSPACE_ID, name: 'Default', kind: 'individual', projects: [...section.projects] }, ...stored]\n }\n\n private current(workspaces: readonly WorkspaceRecord[]): WorkspaceRecord {\n const id = this.scope.get().current\n return workspaces.find(workspace => workspace.id === id) ?? this.defaultOf(workspaces)\n }\n\n private defaultOf(workspaces: readonly WorkspaceRecord[]): WorkspaceRecord {\n const found = workspaces.find(workspace => workspace.id === DEFAULT_WORKSPACE_ID)\n if (found === undefined) throw new WorkspaceError('The Default workspace is missing.')\n return found\n }\n\n private find(workspaces: readonly WorkspaceRecord[], id: string): WorkspaceRecord {\n const found = workspaces.find(workspace => workspace.id === id)\n if (found === undefined) throw new WorkspaceError(`There is no workspace \"${id}\".`)\n return found\n }\n\n private validName(raw: string, others: readonly WorkspaceRecord[]): string {\n const name = raw.trim()\n if (name === '') throw new WorkspaceError('A workspace needs a name.')\n if (name.length > MAX_NAME_LENGTH) throw new WorkspaceError(`A workspace name has at most ${String(MAX_NAME_LENGTH)} characters.`)\n if (others.some(workspace => workspace.name.toLowerCase() === name.toLowerCase())) throw new WorkspaceError(`There is already a workspace called \"${name}\".`)\n return name\n }\n\n /** One write: the workspaces become the only list (the pre-workspace one is emptied, its folders now in Default). */\n private async save(workspaces: readonly WorkspaceRecord[], current: string, adopted?: boolean): Promise<ProjectRegistryView> {\n await this.scope.update({ workspaces: [...workspaces], current, projects: [], ...(adopted === undefined ? {} : { adopted }) })\n const view = this.view()\n for (const listener of [...this.listeners]) listener(view)\n return view\n }\n}\n\nfunction summary(workspace: WorkspaceRecord): WorkspaceSummary {\n return {\n id: workspace.id,\n name: workspace.name,\n kind: workspace.kind,\n projects: [...workspace.projects],\n ...(workspace.remote === undefined ? {} : { remote: { ...workspace.remote } }),\n }\n}\n\nfunction validRemote(remote: RemoteTarget | undefined): RemoteTarget {\n const host = remote?.host.trim() ?? ''\n if (host === '') throw new WorkspaceError('A remote workspace needs the SSH host.')\n const user = remote?.user?.trim()\n const path = remote?.path?.trim()\n return { host, ...(user === undefined || user === '' ? {} : { user }), ...(path === undefined || path === '' ? {} : { path }) }\n}\n","/** The project registry, for the app's own page only: the list, its changes, and a stream of the list as it changes. */\n\nimport { Acryl } from '@acryldev/blends'\nimport { streamSSE } from '@acryldev/blends/streaming'\nimport { INVALID_JSON, failure, jsonBody, ownPage, readJson, type ReportError } from '../private-route.ts'\nimport {\n ProjectRequestError,\n WORKSPACE_PROJECTS_EVENTS_PATH,\n WORKSPACE_PROJECTS_PATH,\n parseProjectRequest,\n type ProjectRegistryView,\n type ProjectRequest,\n type ProjectResponse,\n} from './contract.ts'\nimport { ProjectFolderError, WorkspaceError, type ProjectRegistry } from './registry.ts'\n\n/** A comment line this often keeps an idle event stream open through proxies and the browser's own timeout. */\nconst KEEP_ALIVE_MS = 25_000\n\n/** One timer for every open stream, owned by the plugin's effect rather than by a request: `stop()` is its disposer. */\nexport interface KeepAlive {\n onBeat(listener: () => void): () => void\n stop(): void\n}\n\nexport function createKeepAlive(intervalMs: number = KEEP_ALIVE_MS): KeepAlive {\n const listeners = new Set<() => void>()\n const timer = setInterval(() => { for (const listener of listeners) listener() }, intervalMs)\n timer.unref()\n return {\n onBeat(listener) {\n listeners.add(listener)\n return () => { listeners.delete(listener) }\n },\n stop() {\n clearInterval(timer)\n listeners.clear()\n },\n }\n}\n\nfunction change(registry: ProjectRegistry, request: ProjectRequest): Promise<ProjectRegistryView> {\n switch (request.op) {\n case 'add': return registry.add(request.path)\n case 'remove': return registry.remove(request.path)\n case 'adopt': return registry.adopt(request.paths)\n case 'create-workspace': return registry.createWorkspace(request)\n case 'switch-workspace': return registry.switchWorkspace(request.id)\n case 'rename-workspace': return registry.renameWorkspace(request.id, request.name)\n case 'delete-workspace': return registry.deleteWorkspace(request.id)\n }\n}\n\n/**\n * GET `projects` (the list) and POST `{ op, ... }` to add, remove or adopt, a refusal being a 400 whose message says what to fix. GET\n * `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):\n * 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.\n */\nexport function projectRoutes(registry: ProjectRegistry, keepAlive: KeepAlive, reportError: ReportError): Acryl {\n return new Acryl()\n .get(WORKSPACE_PROJECTS_PATH, ownPage, c => c.json({ ok: true, view: registry.view() } satisfies ProjectResponse))\n .post(WORKSPACE_PROJECTS_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (body === INVALID_JSON) return c.json({ ok: false, code: 'invalid', message: 'invalid request body' } satisfies ProjectResponse, 400)\n try {\n const view = await change(registry, parseProjectRequest(body))\n return c.json({ ok: true, view } satisfies ProjectResponse)\n } catch (cause) {\n if (cause instanceof ProjectRequestError) return c.json({ ok: false, code: 'invalid', message: cause.message } satisfies ProjectResponse, 400)\n if (cause instanceof ProjectFolderError) return c.json({ ok: false, code: 'not-a-folder', message: cause.message } satisfies ProjectResponse, 400)\n if (cause instanceof WorkspaceError) return c.json({ ok: false, code: 'workspace', message: cause.message } satisfies ProjectResponse, 400)\n reportError('change the project list', cause)\n return c.json(failure('the project list could not be saved'), 500)\n }\n })\n .get(WORKSPACE_PROJECTS_EVENTS_PATH, ownPage, c => streamSSE(c, async (stream) => {\n const ended = new Promise<void>(resolve => { stream.onAbort(resolve) })\n // Writes are asynchronous; chaining them keeps messages in the order the list changed.\n let queue: Promise<unknown> = Promise.resolve()\n const enqueue = (write: () => Promise<unknown>): void => { queue = queue.then(write).catch(() => {}) }\n const send = (view: ProjectRegistryView): void => { enqueue(() => stream.writeSSE({ data: JSON.stringify(view) })) }\n send(registry.view())\n const stopFollowing = registry.onChange(send)\n const stopBeating = keepAlive.onBeat(() => { enqueue(() => stream.write(': keep-alive\\n\\n')) })\n try {\n await ended\n } finally {\n stopBeating()\n stopFollowing()\n }\n }))\n}\n","/**\n * Agent Control's workspace tools (spec 043 T007, spec 041's `workspace.*` vocabulary): typed tools provided by the package that owns the\n * project registry, so an agent lists, switches and creates workspaces and adds projects through the same registry the sidebar uses, with\n * its rules and refusals. Every open page follows the change through the registry's event stream. Creating a workspace and adding a\n * project are asked about every time; listing and switching are not (switching only changes what the sidebar shows, and is undone the same way).\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport { defineAcrylTool, type AcrylToolCall, type AcrylToolDecision } from '@acryldev/control'\nimport { WORKSPACE_KINDS, type ProjectRegistryView, type WorkspaceKind, type WorkspaceSummary } from './contract.ts'\nimport type { ProjectRegistry } from './registry.ts'\n\nexport const WORKSPACE_LIST_TOOL = 'acryl_workspace_list'\nexport const WORKSPACE_SWITCH_TOOL = 'acryl_workspace_switch'\nexport const WORKSPACE_CREATE_TOOL = 'acryl_workspace_create'\nexport const WORKSPACE_ADD_PROJECT_TOOL = 'acryl_workspace_add_project'\n\n/** The registry's view as the tools return it: every workspace, and which one is shown. */\nexport interface WorkspacesValue {\n readonly current: string\n readonly workspaces: readonly WorkspaceSummary[]\n}\n\nconst WORKSPACES_SCHEMA = {\n type: 'object', additionalProperties: false,\n properties: {\n current: { type: 'string', required: true },\n workspaces: {\n type: 'array', required: true,\n items: {\n type: 'object', additionalProperties: false,\n properties: {\n id: { type: 'string', required: true }, name: { type: 'string', required: true }, kind: { type: 'string', required: true },\n projects: { type: 'array', required: true, items: { type: 'string' } },\n remote: { type: 'object', additionalProperties: false, properties: { host: { type: 'string', required: true }, user: { type: 'string' }, path: { type: 'string' } } },\n },\n },\n },\n },\n} as const\n\nconst value = (view: ProjectRegistryView): WorkspacesValue => ({ current: view.current, workspaces: view.workspaces })\n\n/** What the model reads: one line per workspace, the shown one marked. */\nexport function renderWorkspaces(view: WorkspacesValue): string {\n return view.workspaces.map((workspace) => {\n const projects = workspace.projects.length === 0 ? 'no projects' : workspace.projects.join(', ')\n const remote = workspace.remote === undefined ? '' : ` (SSH ${workspace.remote.user === undefined ? '' : `${workspace.remote.user}@`}${workspace.remote.host})`\n return `${workspace.id === view.current ? '* ' : ' '}${workspace.name} [${workspace.id}, ${workspace.kind}]${remote}: ${projects}`\n }).join('\\n')\n}\n\nfunction isKind(candidate: string): candidate is WorkspaceKind {\n return (WORKSPACE_KINDS as readonly string[]).includes(candidate)\n}\n\n/** Words for the approval prompt. */\nexport function describeWorkspaceChange(name: string, args: unknown, view: ProjectRegistryView): string {\n const a = (typeof args === 'object' && args !== null ? args : {}) as Record<string, unknown>\n if (name === WORKSPACE_CREATE_TOOL) return `Create the workspace \"${String(a.name)}\" (${String(a.kind ?? 'individual')}) and show it`\n const shown = view.workspaces.find(workspace => workspace.id === view.current)?.name ?? view.current\n return `Add the folder ${String(a.path)} to the workspace \"${shown}\"`\n}\n\n/** Register the four tools and the approval for the two that add something. @returns disposer. */\nexport function registerWorkspaceTools(ctx: Context, registry: ProjectRegistry): () => void {\n const output = { schema: WORKSPACES_SCHEMA, render: (_args: unknown, view: WorkspacesValue) => [{ type: 'text' as const, text: renderWorkspaces(view) }] }\n\n const list = defineAcrylTool({\n name: WORKSPACE_LIST_TOOL,\n description: 'List the workspaces (sets of project folders in the sidebar), their projects, and the shown one (*).',\n parameters: {},\n output,\n execute: () => value(registry.view()),\n })\n\n const switchTo = defineAcrylTool({\n name: WORKSPACE_SWITCH_TOOL,\n description: 'Show another workspace by id (from acryl_workspace_list).',\n parameters: { id: { type: 'string', required: true } },\n output,\n execute: async args => value(await registry.switchWorkspace(args.id)),\n })\n\n const create = defineAcrylTool({\n name: WORKSPACE_CREATE_TOOL,\n description: 'Create a workspace and show it. kind: individual (default), shared (projects share context) or remote (SSH: host, optional user and path).',\n parameters: {\n name: { type: 'string', required: true },\n kind: { type: 'string' },\n host: { type: 'string' },\n user: { type: 'string' },\n path: { type: 'string' },\n },\n output,\n execute: async (args) => {\n const kind = args.kind ?? 'individual'\n if (!isKind(kind)) throw new Error(`unknown workspace kind \"${kind}\"; use individual, shared or remote`)\n const remote = kind === 'remote'\n ? { host: args.host ?? '', ...(args.user === undefined ? {} : { user: args.user }), ...(args.path === undefined ? {} : { path: args.path }) }\n : undefined\n return value(await registry.createWorkspace({ name: args.name, kind, ...(remote === undefined ? {} : { remote }) }))\n },\n })\n\n const addProject = defineAcrylTool({\n name: WORKSPACE_ADD_PROJECT_TOOL,\n description: 'Add a folder (absolute path) as a project of the shown workspace.',\n parameters: { path: { type: 'string', required: true } },\n output,\n execute: async args => value(await registry.add(args.path)),\n })\n\n const disposers = [list, switchTo, create, addProject].map(tool => ctx.acrylTools.register(tool))\n const removePolicy = ctx.acrylTools.policy(async (exec: AcrylToolCall, next: () => Promise<AcrylToolDecision>): Promise<AcrylToolDecision> => {\n const decision = await next()\n if ((exec.name !== WORKSPACE_CREATE_TOOL && exec.name !== WORKSPACE_ADD_PROJECT_TOOL) || decision.kind === 'deny') return decision\n return { kind: 'ask', reason: describeWorkspaceChange(exec.name, exec.arguments, registry.view()) }\n })\n return () => { removePolicy(); for (const dispose of disposers.reverse()) dispose() }\n}\n","/** The adapter that starts a real process behind a terminal with node-pty (a native module). */\n\nimport { spawn as spawnPty } from 'node-pty'\nimport type { WorkspacePtyProcess, WorkspacePtySpawn } from './service.ts'\n\nexport const spawnNodePty: WorkspacePtySpawn = (command, args, options): WorkspacePtyProcess =>\n spawnPty(command, [...args], {\n cwd: options.cwd,\n env: options.env as Record<string, string>,\n name: options.name,\n cols: options.cols,\n rows: options.rows,\n })\n","/** The workspace terminal routes: start, snapshot, input, resize and close, for the app's own page only. The output streams over the PTY WebSocket. */\n\nimport { Acryl } from '@acryldev/blends'\nimport { INVALID_JSON, failure, isRecord, jsonBody, ownPage, readJson, type ReportError } from '../private-route.ts'\nimport type { WorkspacePtyRegistry } from './service.ts'\nimport {\n WORKSPACE_PTY_CLOSE_PATH,\n WORKSPACE_PTY_INPUT_PATH,\n WORKSPACE_PTY_PATH,\n WORKSPACE_PTY_RESIZE_PATH,\n} from './contract.ts'\n\nconst START_KEYS = new Set(['commandId', 'cwd', 'cols', 'rows'])\n\n/**\n * GET `pty?id=` (the session's snapshot) and POST `pty` `{ commandId, cwd?, cols?, rows? }` (start one); POST `input` `{ id, data }`, `resize`\n * `{ id, cols, rows }` and `close` `{ id }` (idempotent) for a live session.\n */\nexport function ptyRoutes(registry: WorkspacePtyRegistry, reportError: ReportError): Acryl {\n return new Acryl()\n .get(WORKSPACE_PTY_PATH, ownPage, (c) => {\n const id = c.req.query('id')\n if (id === undefined || id.length === 0) return c.json(failure('invalid workspace PTY request'), 400)\n try {\n return c.json(registry.read(id))\n } catch (cause) {\n reportError('read workspace PTY', cause)\n return c.json(failure('unknown workspace PTY session'), 404)\n }\n })\n .post(WORKSPACE_PTY_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (body === INVALID_JSON || !isRecord(body) || Object.keys(body).some(key => !START_KEYS.has(key))\n || typeof body.commandId !== 'string' || body.commandId.length === 0 || body.commandId.length > 32\n || (body.cwd !== undefined && (typeof body.cwd !== 'string' || body.cwd.length === 0))) {\n return c.json(failure('invalid workspace PTY request'), 400)\n }\n const size = typeof body.cols === 'number' && typeof body.rows === 'number' ? { cols: body.cols, rows: body.rows } : undefined\n if ((body.cols !== undefined || body.rows !== undefined) && size === undefined) return c.json(failure('invalid workspace PTY request'), 400)\n try {\n return c.json(await registry.start(body.commandId, body.cwd as string | undefined, size))\n } catch (cause) {\n reportError('start workspace PTY', cause)\n return c.json(failure(cause instanceof Error ? cause.message : 'workspace PTY spawn failed'), 500)\n }\n })\n .post(WORKSPACE_PTY_INPUT_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (!isRecord(body) || typeof body.id !== 'string' || typeof body.data !== 'string' || Object.keys(body).length !== 2) {\n return c.json(failure('invalid workspace PTY input'), 400)\n }\n try {\n registry.write(body.id, body.data)\n return c.json({ accepted: true })\n } catch (cause) {\n reportError('write workspace PTY', cause)\n return c.json(failure('unknown workspace PTY session'), 404)\n }\n })\n .post(WORKSPACE_PTY_RESIZE_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (!isRecord(body) || typeof body.id !== 'string'\n || typeof body.cols !== 'number' || typeof body.rows !== 'number'\n || !Number.isInteger(body.cols) || !Number.isInteger(body.rows)\n || body.cols < 2 || body.cols > 500 || body.rows < 1 || body.rows > 200\n || Object.keys(body).length !== 3) {\n return c.json(failure('invalid workspace PTY resize'), 400)\n }\n try {\n registry.resize(body.id, body.cols, body.rows)\n return c.json({ accepted: true })\n } catch (cause) {\n reportError('resize workspace PTY', cause)\n return c.json(failure('unknown workspace PTY session'), 404)\n }\n })\n .post(WORKSPACE_PTY_CLOSE_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (!isRecord(body) || typeof body.id !== 'string' || Object.keys(body).length !== 1) return c.json(failure('invalid workspace PTY close'), 400)\n try {\n await registry.close(body.id)\n return c.json({ accepted: true })\n } catch (cause) {\n reportError('close workspace PTY', cause)\n return c.json(failure('workspace PTY could not be closed'), 500)\n }\n })\n}\n","/**\n * The hook settings ACRYL adds to a Claude Code launch so Claude reports what it is doing.\n *\n * They travel as `--settings <json>`, which Claude merges with the user's own settings; nothing is written to the\n * user's files. Each hook runs one `curl` to ACRYL's loopback status route. The secret and the terminal id are read\n * from the environment ACRYL gives that terminal, never written into the JSON. A failing or slow hook is silent\n * and can never block Claude (`-m 2`, `|| true`).\n */\n\nimport type { AgentState } from './agent-status.ts'\n\n/** The environment a status-reporting terminal is started with. */\nexport const STATUS_ENV = {\n terminal: 'ACRYL_TERMINAL_ID',\n url: 'ACRYL_STATUS_URL',\n token: 'ACRYL_STATUS_TOKEN',\n} as const\n\nconst report = (state: AgentState): string =>\n `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`\n\nconst hook = (state: AgentState, matcher?: string) => [{ ...(matcher === undefined ? {} : { matcher }), hooks: [{ type: 'command', command: report(state) }] }]\n\n/** @returns the JSON text for `claude --settings`. */\nexport function claudeStatusSettings(): string {\n return JSON.stringify({\n hooks: {\n UserPromptSubmit: hook('working'),\n // After an approved tool runs Claude is working again, though no prompt was submitted.\n PostToolUse: hook('working', '*'),\n Notification: hook('waiting'),\n Stop: hook('done'),\n },\n })\n}\n\n/** The extra launch arguments for an agent that reports through hooks. */\nexport function statusHookArgs(kind: 'claude'): readonly string[] {\n return kind === 'claude' ? ['--settings', claudeStatusSettings()] : []\n}\n","/**\n * The retained tail of one terminal's output, addressed by an ever-growing cursor.\n *\n * The cursor is the total number of characters the process has written, so a client that remembers the\n * cursor it reached can ask for exactly what it missed, with no gap and no repeat. Only the tail is kept;\n * a client that fell behind the kept part is told to start over from the tail instead.\n */\n\nexport interface Replay {\n /** Output from the requested cursor (or from the start of the kept tail when `replace`). */\n readonly data: string\n /** The cursor after `data`. */\n readonly cursor: number\n /** True when the client must clear its terminal first: what it missed is no longer kept. */\n readonly replace: boolean\n}\n\nconst DEFAULT_LIMIT = 1024 * 1024\n/** After a cut, look this far for a line break so the tail does not start in the middle of a line. */\nconst LINE_SEARCH = 4096\n\nexport class Scrollback {\n private tail = ''\n private start = 0\n\n constructor(private readonly limit: number = DEFAULT_LIMIT) {}\n\n /** Total characters ever appended. */\n get cursor(): number {\n return this.start + this.tail.length\n }\n\n append(chunk: string): void {\n if (chunk.length === 0) return\n this.tail += chunk\n if (this.tail.length <= this.limit) return\n let cut = this.tail.length - this.limit\n const lineBreak = this.tail.indexOf('\\n', cut)\n if (lineBreak !== -1 && lineBreak - cut < LINE_SEARCH) cut = lineBreak + 1\n this.tail = this.tail.slice(cut)\n this.start += cut\n }\n\n /** @param since - the cursor the client reached, or 0 for a fresh attach. */\n replay(since: number): Replay {\n if (since >= this.start && since <= this.cursor) {\n return { data: this.tail.slice(since - this.start), cursor: this.cursor, replace: false }\n }\n return { data: this.tail, cursor: this.cursor, replace: true }\n }\n}\n","/**\n * The Host's own picture of one terminal's screen.\n *\n * It is fed the same bytes the process writes, so at any moment it can say exactly what is on screen\n * (including a full-screen program's alternate screen, colours, and cursor position). A view that attaches\n * late, reconnects after a long gap, or reloads is given that picture instead of a replay of raw history,\n * which cannot reproduce a screen that was drawn by cursor movement.\n */\n\nimport serializeModule from '@xterm/addon-serialize'\nimport type { SerializeAddon as SerializeAddonType } from '@xterm/addon-serialize'\nimport headlessModule from '@xterm/headless'\nimport type { Terminal as HeadlessTerminal } from '@xterm/headless'\n\n// Both packages are CommonJS, whose named exports Node's ESM loader cannot see; take them from the default.\nconst { Terminal } = headlessModule\nconst { SerializeAddon } = serializeModule\n\nconst SCROLLBACK_LINES = 5000\n\nexport interface ScreenSnapshot {\n /** Escape sequences that redraw the screen and scrollback from empty. */\n readonly screen: string\n /** The cursor of the output this snapshot already includes. Anything after it is still to be sent. */\n readonly cursor: number\n}\n\nexport class ScreenModel {\n private readonly terminal: HeadlessTerminal\n private readonly serializer: SerializeAddonType = new SerializeAddon()\n private applied = 0\n\n constructor(cols: number, rows: number) {\n this.terminal = new Terminal({ cols, rows, scrollback: SCROLLBACK_LINES, allowProposedApi: true })\n this.terminal.loadAddon(this.serializer)\n }\n\n /** @param endCursor - the output cursor after this chunk, so a snapshot can say how far it reaches. */\n write(chunk: string, endCursor: number): void {\n // The terminal parses asynchronously; the snapshot only claims what the parser has really reached.\n this.terminal.write(chunk, () => { this.applied = endCursor })\n }\n\n resize(cols: number, rows: number): void {\n this.terminal.resize(cols, rows)\n }\n\n snapshot(): ScreenSnapshot {\n return { screen: this.serializer.serialize(), cursor: this.applied }\n }\n\n dispose(): void {\n this.terminal.dispose()\n }\n}\n","/** Host-owned ACRYL Workspace PTY sessions. UI observes; this module owns lifetime. */\n\nimport { spawn } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport { statSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { isAbsolute, join } from 'node:path'\nimport type { AgentId, WorkspacePtyCommandId, WorkspacePtyStatus, WorkspacePtyView } from './contract.ts'\nimport { knownAgent } from '../agents/known-agents.ts'\nimport { STATUS_ENV, statusHookArgs } from '../agents/status/claude-hooks.ts'\nimport { MAX_PTY_COLS, MAX_PTY_ROWS, isWorkspacePtyCommandId } from './contract.ts'\nimport { Scrollback, type Replay } from './scrollback.ts'\nimport { ScreenModel } from './screen-model.ts'\n\nconst KILL_GRACE_MS = 1_000\nconst DEFAULT_COLS = 120\nconst DEFAULT_ROWS = 40\n\nconst PROBE_TIMEOUT_MS = 3_000\n\n/** What `shell args` printed on stdout, or `undefined` when it failed, timed out or could not start. Never blocks the event loop. */\nfunction probe(shell: string, args: readonly string[], env: NodeJS.ProcessEnv): Promise<string | undefined> {\n return new Promise((resolve) => {\n let out = ''\n let child: ReturnType<typeof spawn>\n try {\n child = spawn(shell, args, { env, stdio: ['ignore', 'pipe', 'ignore'], timeout: PROBE_TIMEOUT_MS, windowsHide: true })\n } catch {\n resolve(undefined)\n return\n }\n child.stdout?.setEncoding('utf8')\n child.stdout?.on('data', (chunk: string) => { out += chunk })\n child.on('error', () => { resolve(undefined) })\n child.on('close', (code) => { resolve(code === 0 ? out : undefined) })\n })\n}\n\nasync function lookUpSpawnDirs(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): Promise<readonly string[]> {\n const dirs: string[] = []\n const add = (raw: string | undefined): void => {\n if (raw === undefined) return\n for (const dir of raw.split(platform === 'win32' ? ';' : ':')) {\n if (dir.length > 0 && !dirs.includes(dir)) dirs.push(dir)\n }\n }\n add(env.PATH)\n const shell = env.SHELL ?? (platform === 'win32' ? env.ComSpec ?? 'cmd.exe' : '/bin/sh')\n const probes = platform === 'win32'\n ? [['/d', '/s', '/c', 'echo %PATH%']]\n : [['-lic', 'echo $PATH'], ['-lc', 'echo $PATH']]\n for (const args of probes) {\n const out = await probe(shell, args, env)\n // Log-in shell not available: keep the env PATH we already have.\n if (out === undefined) continue\n add(out.trimEnd())\n if (dirs.length > 0) break\n }\n return Object.freeze(dirs)\n}\n\n/** 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. */\nconst spawnDirsCache = new Map<string, Promise<readonly string[]>>()\n\n/**\n * A Finder-launched macOS app gets a minimal PATH (`/usr/bin:/bin:…`), so a\n * bare agent name such as `claude` fails to spawn even when it is installed.\n * Resolve bare commands to an absolute executable by merging `env.PATH` with\n * the user's login-shell PATH. The login shell is asked asynchronously (an\n * interactive zsh takes about a second, which must not stall the Host), once\n * per shell, home and PATH; callers wait for the answer.\n */\nexport function workspacePtySpawnDirs(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): Promise<readonly string[]> {\n const key = [platform, env.SHELL ?? env.ComSpec ?? '', env.HOME ?? env.USERPROFILE ?? '', env.PATH ?? ''].join('\\0')\n let dirs = spawnDirsCache.get(key)\n if (dirs === undefined) {\n dirs = lookUpSpawnDirs(env, platform)\n spawnDirsCache.set(key, dirs)\n }\n return dirs\n}\n\n/**\n * Return an absolute executable path for `command`, or `undefined` when none of\n * `dirs` contains an executable `command`. Absolute/relative paths pass through.\n */\nexport function resolveWorkspacePtyCommand(\n command: string,\n dirs: readonly string[],\n platform: NodeJS.Platform,\n): string | undefined {\n if (isAbsolute(command) || command.includes('/') || command.includes('\\\\')) return command\n const names = platform === 'win32'\n ? [command, `${command}.exe`, `${command}.cmd`, `${command}.bat`]\n : [command]\n for (const dir of dirs) {\n for (const name of names) {\n try {\n const candidate = join(dir, name)\n const stat = statSync(candidate)\n if (stat.isFile() && (platform === 'win32' || (stat.mode & 0o111) !== 0)) return candidate\n } catch {\n // Not present here; keep searching.\n }\n }\n }\n return undefined\n}\n\n/** The spawn cwd: process.cwd() when it exists, else the user's home directory. */\nfunction defaultSpawnCwd(): string {\n try {\n if (statSync(process.cwd()).isDirectory()) return process.cwd()\n } catch {\n // Fall through to the home directory.\n }\n return homedir()\n}\n\nexport interface WorkspacePtyProcess {\n onData(listener: (data: string) => void): { dispose(): void }\n onExit(listener: (event: { exitCode: number; signal?: number }) => void): { dispose(): void }\n write(data: string): void\n resize(cols: number, rows: number): void\n kill(signal?: string): void\n}\n\n/** PTY spawn injected so unit tests never launch a real process. */\nexport type WorkspacePtySpawn = (\n command: string,\n args: readonly string[],\n options: {\n readonly cwd: string\n readonly env: NodeJS.ProcessEnv\n readonly name: string\n readonly cols: number\n readonly rows: number\n },\n) => WorkspacePtyProcess\n\nexport interface WorkspacePtySpawnPlan {\n readonly command: string\n readonly args: readonly string[]\n /** Added to the terminal's environment for this launch. */\n readonly env?: Readonly<Record<string, string>>\n /** The agent reports its state through hooks of this kind; the registry adds the reporting when it can. */\n readonly statusHooks?: 'claude'\n}\n\n/** Says what an agent id runs: the user's settings for a known agent, or a custom agent's definition. */\nexport interface AgentResolver {\n resolve(id: string): WorkspacePtySpawnPlan | undefined\n}\n\n/** What an agent started in a folder is given beyond its own launch: the shared workspace context (spec 043), or nothing. */\nexport interface LaunchContextProvider {\n launchFor(agentId: string, cwd: string): { readonly args: readonly string[], readonly env: Readonly<Record<string, string>> } | undefined\n}\n\nexport interface WorkspacePtyRegistryOptions {\n readonly agents?: AgentResolver\n /** Looked up at each agent start, so the context is the workspace's as it is then. */\n readonly launchContext?: LaunchContextProvider\n /** Where agents report their state, and the secret they present. Without it no reporting is added. */\n readonly agentStatus?: { readonly url: string; readonly token: string }\n /** Starts a real process behind a terminal. Injected: the policy here never loads a native module. */\n readonly spawn: WorkspacePtySpawn\n readonly env?: NodeJS.ProcessEnv\n readonly cwd?: string\n readonly platform?: NodeJS.Platform\n readonly createId?: () => string\n}\n\ninterface LiveSession {\n readonly id: string\n readonly process: WorkspacePtyProcess\n readonly subscriptions: readonly { dispose(): void }[]\n status: WorkspacePtyStatus\n readonly scrollback: Scrollback\n readonly screen: ScreenModel\n readonly listeners: Set<(event: WorkspacePtyEvent) => void>\n exitCode: number | null\n error: string | null\n}\n\n/** What a live subscriber to one session is told. */\nexport type WorkspacePtyEvent =\n | { readonly kind: 'data'; readonly data: string; readonly cursor: number }\n | { readonly kind: 'exit'; readonly exitCode: number | null; readonly error: string | null }\n\n/**\n * Resolve argv for one allowlisted workspace command.\n * @param commandId - catalog id from the tab.\n * @param platform - Host process.platform.\n * @param env - environment used to pick SHELL / ComSpec.\n */\nexport function planWorkspacePtyCommand(\n commandId: WorkspacePtyCommandId,\n platform: NodeJS.Platform,\n env: NodeJS.ProcessEnv,\n): WorkspacePtySpawnPlan {\n if (commandId === 'shell') {\n if (platform === 'win32') {\n return { command: env.ComSpec ?? 'cmd.exe', args: [] }\n }\n return { command: env.SHELL ?? '/bin/sh', args: [] }\n }\n return { command: commandId, args: [] }\n}\n\n/**\n * The environment a terminal process starts with: a real terminal type, true color, and a UTF-8 locale\n * (an app launched from Finder has none, which makes shells and TUIs draw wrong glyphs).\n */\nexport function terminalEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const locale = env.LC_ALL ?? env.LC_CTYPE ?? env.LANG\n return {\n ...env,\n TERM: env.TERM ?? 'xterm-256color',\n COLORTERM: env.COLORTERM ?? 'truecolor',\n TERM_PROGRAM: 'ACRYL',\n ...(locale === undefined || !/utf-?8/i.test(locale) ? { LANG: 'en_US.UTF-8' } : {}),\n }\n}\n\nfunction isExistingAbsoluteDirectory(path: string): boolean {\n if (path.length === 0 || path.includes('\\0') || !isAbsolute(path)) return false\n try {\n return statSync(path).isDirectory()\n } catch {\n return false\n }\n}\n\n/** Table of live native PTY sessions for one ACRYL Workspace Host fiber. */\nexport class WorkspacePtyRegistry {\n private readonly sessions = new Map<string, LiveSession>()\n private readonly spawnImpl: WorkspacePtySpawn\n private readonly env: NodeJS.ProcessEnv\n private readonly cwd: string\n private readonly platform: NodeJS.Platform\n private readonly createId: () => string\n /** The search path for bare commands; the login shell's answer arrives after the registry is built (see {@link workspacePtySpawnDirs}). */\n private readonly spawnDirs: Promise<readonly string[]>\n private readonly agents: AgentResolver | undefined\n private readonly agentStatus: { readonly url: string; readonly token: string } | undefined\n private readonly launchContext: LaunchContextProvider | undefined\n /** Set by {@link disposeAll}: a start still waiting for the search path then spawns nothing. */\n private disposed = false\n\n constructor(options: WorkspacePtyRegistryOptions) {\n this.spawnImpl = options.spawn\n this.env = options.env ?? process.env\n this.cwd = options.cwd ?? defaultSpawnCwd()\n this.platform = options.platform ?? process.platform\n this.createId = options.createId ?? (() => `pty_${randomUUID()}`)\n this.spawnDirs = workspacePtySpawnDirs(this.env, this.platform)\n this.agents = options.agents\n this.agentStatus = options.agentStatus\n this.launchContext = options.launchContext\n }\n\n /**\n * Start one allowlisted command inside a real terminal.\n * @param commandId - catalog id from the Terminal/agent tab.\n * @param cwd - optional working directory (a worktree); must be an existing absolute directory.\n */\n async start(commandId: AgentId, cwd?: string, size?: { readonly cols: number; readonly rows: number }): Promise<WorkspacePtyView> {\n // The terminal is planned here; any other id is an agent, and the resolver (when there is one) knows the user's settings.\n const known = isWorkspacePtyCommandId(commandId) ? knownAgent(commandId) : undefined\n const agentPlan: WorkspacePtySpawnPlan | undefined = commandId === 'shell'\n ? undefined\n : this.agents?.resolve(commandId) ?? (known === undefined ? undefined : { command: known.command, args: [] })\n if (commandId !== 'shell' && agentPlan === undefined) {\n throw new Error('@acryldev/workspace: unknown workspace PTY command')\n }\n if (cwd !== undefined && !isExistingAbsoluteDirectory(cwd)) {\n throw new Error('@acryldev/workspace: workspace PTY cwd must be an existing absolute directory')\n }\n const cols = size?.cols ?? DEFAULT_COLS\n const rows = size?.rows ?? DEFAULT_ROWS\n if (!Number.isInteger(cols) || !Number.isInteger(rows) || cols < 2 || cols > MAX_PTY_COLS || rows < 1 || rows > MAX_PTY_ROWS) {\n throw new Error('@acryldev/workspace: workspace PTY size is out of range')\n }\n const plan: WorkspacePtySpawnPlan = agentPlan ?? planWorkspacePtyCommand('shell', this.platform, this.env)\n const dirs = await this.spawnDirs\n if (this.disposed) throw new Error('@acryldev/workspace: workspace PTY registry is disposed')\n const id = this.createId()\n let process: WorkspacePtyProcess\n try {\n const resolved = resolveWorkspacePtyCommand(plan.command, dirs, this.platform)\n if (resolved === undefined && !plan.command.includes('/') && !plan.command.includes('\\\\')) {\n throw new Error(`workspace PTY command not found in PATH: ${plan.command}`)\n }\n // An agent that reports through hooks gets the reporting launch settings and the terminal's own credentials.\n const reporting = plan.statusHooks !== undefined && this.agentStatus !== undefined\n // In a Shared Context workspace an agent also gets the workspace's context, in its own way; the shell gets nothing.\n const shared = commandId === 'shell' ? undefined : this.launchContext?.launchFor(commandId, cwd ?? this.cwd)\n const args = [...(reporting && plan.statusHooks !== undefined ? statusHookArgs(plan.statusHooks) : []), ...(shared?.args ?? []), ...plan.args]\n const reportingEnv = reporting && this.agentStatus !== undefined\n ? { [STATUS_ENV.terminal]: id, [STATUS_ENV.url]: this.agentStatus.url, [STATUS_ENV.token]: this.agentStatus.token }\n : {}\n process = this.spawnImpl(resolved ?? plan.command, args, {\n cwd: cwd ?? this.cwd,\n env: { ...terminalEnvironment(this.env), ...plan.env, ...shared?.env, ...reportingEnv },\n name: 'xterm-256color',\n cols,\n rows,\n })\n } catch (cause) {\n throw new Error(\n `@acryldev/workspace: workspace PTY spawn failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n )\n }\n const subscriptions: { dispose(): void }[] = []\n const session: LiveSession = {\n id,\n process,\n subscriptions,\n status: 'running',\n scrollback: new Scrollback(),\n screen: new ScreenModel(cols, rows),\n listeners: new Set(),\n exitCode: null,\n error: null,\n }\n subscriptions.push(process.onData((chunk) => {\n session.scrollback.append(chunk)\n session.screen.write(chunk, session.scrollback.cursor)\n const event: WorkspacePtyEvent = { kind: 'data', data: chunk, cursor: session.scrollback.cursor }\n for (const listener of [...session.listeners]) listener(event)\n }))\n subscriptions.push(process.onExit(({ exitCode, signal }) => {\n session.status = 'exited'\n session.exitCode = exitCode\n if (session.error === null && signal !== undefined && signal !== 0) {\n session.error = `signal ${String(signal)}`\n }\n const event: WorkspacePtyEvent = { kind: 'exit', exitCode: session.exitCode, error: session.error }\n for (const listener of [...session.listeners]) listener(event)\n }))\n this.sessions.set(id, session)\n return this.view(session)\n }\n\n /** True when a live terminal has this id. */\n has(id: string): boolean {\n return this.sessions.has(id)\n }\n\n /** True when `command` is an absolute executable file or a program on the search path. */\n async canRun(command: string): Promise<boolean> {\n if (isAbsolute(command)) {\n try {\n const info = statSync(command)\n return info.isFile() && (this.platform === 'win32' || (info.mode & 0o111) !== 0)\n } catch {\n return false\n }\n }\n return resolveWorkspacePtyCommand(command, await this.spawnDirs, this.platform) !== undefined\n }\n\n /** Write exact terminal input bytes. */\n write(id: string, data: string): void {\n const session = this.require(id)\n if (session.status !== 'running') {\n throw new Error('@acryldev/workspace: workspace PTY is not running')\n }\n session.process.write(data)\n }\n\n /** Resize one live terminal. */\n resize(id: string, cols: number, rows: number): void {\n const session = this.require(id)\n if (session.status !== 'running') return\n session.process.resize(cols, rows)\n session.screen.resize(cols, rows)\n }\n\n /**\n * Follow one session live. `replay` is what the subscriber has not seen yet (from `since`, or the kept\n * tail when it missed more than is kept); everything after it arrives through `listener`, in order,\n * with nothing lost or repeated in between.\n * @param since - the cursor the subscriber already reached, 0 for a first attach.\n */\n subscribe(id: string, since: number, listener: (event: WorkspacePtyEvent) => void): {\n readonly replay: Replay\n readonly status: WorkspacePtyStatus\n readonly exitCode: number | null\n readonly error: string | null\n dispose(): void\n } {\n const session = this.require(id)\n session.listeners.add(listener)\n return {\n replay: this.replayFor(session, since),\n status: session.status,\n exitCode: session.exitCode,\n error: session.error,\n dispose: () => { session.listeners.delete(listener) },\n }\n }\n\n /**\n * A subscriber that can resume from its cursor gets just what it missed. Any other (first attach,\n * reload, a gap larger than the kept tail) gets the screen as it is now, then what was written since.\n */\n private replayFor(session: LiveSession, since: number): Replay {\n if (since > 0) {\n const direct = session.scrollback.replay(since)\n if (!direct.replace) return direct\n }\n const { screen, cursor } = session.screen.snapshot()\n const tail = session.scrollback.replay(cursor)\n return tail.replace\n ? tail\n : { data: screen + tail.data, cursor: tail.cursor, replace: true }\n }\n\n /** Snapshot one session for the renderer. */\n read(id: string): WorkspacePtyView {\n return this.view(this.require(id))\n }\n\n /** Stop one session. Idempotent. */\n async close(id: string): Promise<void> {\n const session = this.sessions.get(id)\n if (session === undefined) return\n await stopPty(session)\n for (const subscription of session.subscriptions) subscription.dispose()\n session.screen.dispose()\n this.sessions.delete(id)\n }\n\n /** Stop every session owned by this fiber. */\n async disposeAll(): Promise<void> {\n this.disposed = true\n const ids = [...this.sessions.keys()]\n await Promise.all(ids.map(async id => this.close(id)))\n }\n\n private require(id: string): LiveSession {\n const session = this.sessions.get(id)\n if (session === undefined) {\n throw new Error('@acryldev/workspace: unknown workspace PTY session')\n }\n return session\n }\n\n private view(session: LiveSession): WorkspacePtyView {\n return {\n id: session.id,\n status: session.status,\n output: session.scrollback.replay(0).data,\n exitCode: session.exitCode,\n error: session.error,\n }\n }\n}\n\nasync function stopPty(session: LiveSession): Promise<void> {\n if (session.status !== 'running') return\n await new Promise<void>((resolve) => {\n let done = false\n const finish = (): void => {\n if (done) return\n done = true\n clearTimeout(timer)\n exitSubscription.dispose()\n resolve()\n }\n const exitSubscription = session.process.onExit(finish)\n const timer = setTimeout(() => {\n try {\n session.process.kill('SIGKILL')\n } catch {\n // The PTY may have exited between the status check and timeout.\n }\n finish()\n }, KILL_GRACE_MS)\n timer.unref?.()\n try {\n session.process.kill()\n } catch {\n finish()\n }\n })\n}\n","/**\n * The live terminal stream: one WebSocket per open terminal view, on the framework's router.\n *\n * Output goes down and keystrokes and size changes go up over one ordered connection, so nothing is\n * polled, nothing is re-sent, and two keystrokes can never arrive swapped. The route is an ordinary router\n * route: the own-page rule that guards the HTTP routes runs before the upgrade, with the exact `Origin` a\n * socket must show (a WebSocket is not covered by the same-origin policy on its own), and a refusal is a\n * plain status before any handshake. The framework's hub owns the sockets: it pings them, ends dead peers,\n * and closes them with 1001 when the plugin unloads.\n */\n\nimport { Acryl, type MiddlewareHandler } from '@acryldev/blends'\nimport type { UpgradeWebSocket, WSContext, WSEvents } from '@acryldev/blends/ws'\nimport { failure, ownPageSocket, type ReportError } from '../private-route.ts'\nimport { WORKSPACE_PTY_STREAM_PATH, parsePtyClientMessage, type PtyServerMessage } from './contract.ts'\nimport type { WorkspacePtyRegistry } from './service.ts'\n\n/** Output is sent in batches this far apart, so a burst of small writes becomes one frame. */\nconst BATCH_MS = 4\n/** When the socket already holds this much unsent data, wait instead of piling on. */\nconst BACKPRESSURE_BYTES = 1024 * 1024\n/** A client this far behind is dropped; it reconnects and resumes from its cursor. */\nconst MAX_PENDING_CHARS = 8 * 1024 * 1024\n\n/** A well-formed attach request: the session and the cursor its view already shows. */\nconst validAttach: MiddlewareHandler = async (c, next) => {\n const id = c.req.query('id')\n const since = c.req.query('since') ?? '0'\n if (id === undefined || id.length === 0 || !/^\\d{1,15}$/.test(since)) return c.json(failure('invalid terminal stream request'), 400)\n await next()\n}\n\n/** One open view of session `id`, from cursor `since`: the replay, then live output; its input is written to the session. */\nfunction attach(registry: WorkspacePtyRegistry, id: string, since: number): WSEvents {\n let subscription: ReturnType<WorkspacePtyRegistry['subscribe']> | undefined\n let pending = ''\n let pendingCursor = 0\n let timer: NodeJS.Timeout | undefined\n return {\n onOpen(_event, ws) {\n const send = (message: PtyServerMessage): void => {\n if (ws.readyState === 1) ws.send(JSON.stringify(message))\n }\n const flush = (): void => {\n timer = undefined\n if (pending === '') return\n if (ws.bufferedAmount > BACKPRESSURE_BYTES) {\n timer = setTimeout(flush, BATCH_MS * 2)\n return\n }\n send({ t: 'out', data: pending, cursor: pendingCursor, replace: false })\n pending = ''\n }\n try {\n subscription = registry.subscribe(id, since, (event) => {\n if (event.kind === 'data') {\n pending += event.data\n pendingCursor = event.cursor\n if (pending.length > MAX_PENDING_CHARS) { ws.close(1013, 'too slow'); return }\n timer ??= setTimeout(flush, BATCH_MS)\n return\n }\n if (timer !== undefined) clearTimeout(timer)\n flush()\n send({ t: 'exit', exitCode: event.exitCode, error: event.error })\n })\n } catch {\n ws.close(4404, 'unknown session')\n return\n }\n const { replay } = subscription\n if (replay.replace || replay.data.length > 0) send({ t: 'out', data: replay.data, cursor: replay.cursor, replace: replay.replace })\n if (subscription.status !== 'running') send({ t: 'exit', exitCode: subscription.exitCode, error: subscription.error })\n },\n onMessage(event, ws: WSContext) {\n if (subscription === undefined) return\n const message = typeof event.data === 'string' ? parsePtyClientMessage(event.data) : null\n if (message === null) { ws.close(1008, 'invalid message'); return }\n try {\n if (message.t === 'in') registry.write(id, message.data)\n else registry.resize(id, message.cols, message.rows)\n } catch {\n // The process already exited; the exit message has been or will be sent.\n }\n },\n onClose() {\n if (timer !== undefined) clearTimeout(timer)\n subscription?.dispose()\n },\n }\n}\n\n/**\n * GET {@link WORKSPACE_PTY_STREAM_PATH}`?id=&since=` upgraded to the session's stream. `upgrade` is the mounting plugin's\n * `ctx.routerHttp.upgrades()`, so the sockets belong to it; the path must be one the plugin mounted with `upgrade: [path]`.\n */\nexport function ptyStreamRoutes(registry: WorkspacePtyRegistry, upgrade: UpgradeWebSocket, reportError: ReportError): Acryl {\n return new Acryl().get(\n WORKSPACE_PTY_STREAM_PATH,\n ownPageSocket,\n validAttach,\n upgrade((c) => {\n const events = attach(registry, c.req.query('id') ?? '', Number(c.req.query('since') ?? '0'))\n return { ...events, onError: (event) => { reportError('terminal stream', event instanceof ErrorEvent ? event.error : event) } }\n }, { textOnly: true, onError: (cause: unknown) => { reportError('terminal stream', cause) } }),\n )\n}\n","/**\n * The DSH chat's share of the workspace context (spec 043 T010): a `systemPrompt.context` contribution, the harness's dynamic context that is\n * recorded as a durable user-role snapshot per assembly (so a change does not invalidate the cached system prompt). It is keyed by the\n * session's own folder, so a chat in a Shared Context workspace is told about its projects and any other chat gets nothing.\n */\n\n/** The share of DSH's `systemPrompt` service used here (the harness types are not a dependency of this package). */\nexport interface SystemPromptContextPort {\n context(context: { readonly name: string, readonly order: number, readonly text: (assembly: AssemblyLike) => string }): () => void\n}\n\n/** The share of an assembly read here: the session whose prompt is being assembled. */\nexport interface AssemblyLike {\n readonly agent?: { readonly session?: { readonly header?: { readonly cwd?: unknown } } }\n}\n\nexport const WORKSPACE_CONTEXT_NAME = 'acryl:workspace'\n/** After the harness's own runtime contexts (sandbox 110, approval 115, subagents 120). */\nexport const WORKSPACE_CONTEXT_ORDER = 130\n\n/** @returns the prompt block for the session's folder, or '' (no contribution) outside a Shared Context workspace. */\nexport function chatContextText(contextFor: (folder: string) => { readonly prompt: string } | undefined, assembly: AssemblyLike): string {\n const cwd = assembly.agent?.session?.header?.cwd\n return typeof cwd === 'string' && cwd !== '' ? contextFor(cwd)?.prompt ?? '' : ''\n}\n\n/** Register the contribution. @returns disposer. */\nexport function registerChatContext(systemPrompt: SystemPromptContextPort, contextFor: (folder: string) => { readonly prompt: string } | undefined): () => void {\n return systemPrompt.context({ name: WORKSPACE_CONTEXT_NAME, order: WORKSPACE_CONTEXT_ORDER, text: assembly => chatContextText(contextFor, assembly) })\n}\n","/**\n * How a terminal agent started in a Shared Context workspace gets the context, in its own way (spec 043 T010). Only flags each agent\n * documents and its installed `--help` lists: Claude Code gets the other projects and the workspace folder (`--add-dir`) and the context\n * (`--append-system-prompt`); Pi gets the context; Codex gets the same folders (`--add-dir`) and the context as developer instructions\n * (`-c developer_instructions=...`, Codex 0.162). Every agent gets `ACRYL_WORKSPACE_CONTEXT`, the generated document's path.\n *\n * 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\n * kind, is started with. That is how a session moves between agents without adapting one agent to another.\n */\n\n/** The environment variable naming the workspace's generated context document. */\nexport const WORKSPACE_CONTEXT_ENV = 'ACRYL_WORKSPACE_CONTEXT'\n\nexport interface ContextLaunch {\n readonly args: readonly string[]\n readonly env: Readonly<Record<string, string>>\n}\n\nexport interface LaunchContext {\n readonly prompt: string\n readonly documentPath: string\n readonly otherProjects: readonly string[]\n /** `<home>/workspaces/<id>/`: the brief and the generated document. */\n readonly workspaceFolder: string\n}\n\n/** @returns the arguments and environment a known agent is started with in a shared workspace. */\nexport function contextLaunch(agentId: string, context: LaunchContext): ContextLaunch {\n const env = { [WORKSPACE_CONTEXT_ENV]: context.documentPath }\n const folders = [...context.otherProjects, context.workspaceFolder]\n switch (agentId) {\n case 'claude':\n // `--add-dir` takes every folder up to the next flag.\n return { args: ['--add-dir', ...folders, '--append-system-prompt', context.prompt], env }\n case 'pi':\n return { args: ['--append-system-prompt', context.prompt], env }\n case 'codex':\n // The value is parsed as TOML; a JSON string literal is a valid TOML basic string.\n return { args: [...folders.flatMap(folder => ['--add-dir', folder]), '-c', `developer_instructions=${JSON.stringify(context.prompt)}`], env }\n default:\n return { args: [], env }\n }\n}\n","/**\n * The shared context of a Shared Context workspace (spec 043), as text: what an agent is told about the workspace it works in. Pure: the\n * caller reads the files. Two shapes: the prompt block (inside a size budget, so it never floods a model's context) and the full document\n * written to `WORKSPACE.md`.\n */\n\nexport interface ContextProject {\n readonly name: string\n readonly path: string\n /** The project's own agent instructions present at its root (`CLAUDE.md`, `AGENTS.md`, `README.md`), referenced, never copied. */\n readonly instructions: readonly string[]\n}\n\nexport interface ContextInput {\n readonly name: string\n readonly projects: readonly ContextProject[]\n /** The workspace brief, as the user wrote it; empty when there is none. */\n readonly brief: string\n /** Where the full document is, for the agent to read. */\n readonly documentPath: string\n /** Where the brief is, for the agent to know what it may edit. */\n readonly briefPath: string\n}\n\n/** The prompt block's size, in characters (about 900 tokens). */\nexport const CONTEXT_PROMPT_BUDGET = 3200\n/** The XML-style tag of the prompt block, in the style of the other ACRYL sections. */\nexport const CONTEXT_TAG = 'acryl_workspace'\n\nfunction projectLines(projects: readonly ContextProject[]): string[] {\n if (projects.length === 0) return ['- (no projects yet)']\n return projects.map(project => `- ${project.name}: ${project.path}${project.instructions.length === 0 ? '' : ` (instructions: ${project.instructions.join(', ')})`}`)\n}\n\n/** The block the DSH chat and terminal agents get. The brief is cut to fit the budget, and says so. */\nexport function renderContextPrompt(input: ContextInput, budget = CONTEXT_PROMPT_BUDGET): string {\n const head = [\n `<${CONTEXT_TAG}>`,\n `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.`,\n 'Projects:',\n ...projectLines(input.projects),\n ]\n const tail = [`Full context: ${input.documentPath}. The brief is ${input.briefPath} (the user's; edit it only when asked).`, `</${CONTEXT_TAG}>`]\n const brief = input.brief.trim()\n if (brief === '') return [...head, ...tail].join('\\n')\n // What is left for the brief: the block without it, plus the one line break that joins the brief in.\n const room = budget - [...head, 'Brief:', ...tail].join('\\n').length - 1\n const note = '\\n(brief cut here; the rest is in the file)'\n if (room <= note.length + 40) return [...head, ...tail].join('\\n')\n const cut = brief.length <= room ? brief : `${brief.slice(0, room - note.length).trimEnd()}${note}`\n return [...head, 'Brief:', cut, ...tail].join('\\n')\n}\n\n/** The whole document written to `WORKSPACE.md`: the brief in full. */\nexport function renderContextDocument(input: ContextInput): string {\n const brief = input.brief.trim()\n return [\n `# Workspace: ${input.name}`,\n '',\n 'Generated by ACRYL for every agent working in this shared-context workspace. Do not edit: it is rewritten when the workspace changes.',\n `The brief is ${input.briefPath}.`,\n '',\n '## Projects',\n '',\n ...projectLines(input.projects),\n '',\n '## Brief',\n '',\n brief === '' ? '(none yet)' : brief,\n '',\n ].join('\\n')\n}\n","/**\n * `SharedContext`: which Shared Context workspace a folder works in, and what an agent there is told (spec 043 T009). It keeps\n * `<home>/workspaces/<id>/WORKSPACE.md` current for every shared workspace and holds each workspace's brief (`BRIEF.md`, the user's).\n * Provided as the `acrylSharedContext` service, so another mechanism can replace it (FR-005).\n */\n\nimport { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport type { ProjectRegistryView, WorkspaceSummary } from '../projects/contract.ts'\nimport { contextLaunch, type ContextLaunch } from './launch.ts'\nimport { renderContextDocument, renderContextPrompt, type ContextInput } from './render.ts'\n\n/** The service name other plugins read. */\nexport const SHARED_CONTEXT_SERVICE = 'acrylSharedContext'\n\n/** A brief longer than this is refused: it is a page of notes, not a store. */\nexport const MAX_BRIEF_CHARS = 100_000\n\nconst INSTRUCTION_FILES = ['CLAUDE.md', 'AGENTS.md', 'README.md'] as const\n\nexport interface SharedContextRegistry {\n view(): ProjectRegistryView\n onChange(listener: (view: ProjectRegistryView) => void): () => void\n}\n\n/** What a terminal agent or the chat gets for one workspace. */\nexport interface WorkspaceContext {\n readonly workspace: WorkspaceSummary\n /** The prompt block (within the budget). */\n readonly prompt: string\n /** The generated document's path. */\n readonly documentPath: string\n /** The workspace's projects other than the one the agent starts in. */\n readonly otherProjects: (folder: string) => readonly string[]\n}\n\n/** `path` is `folder` or below it, with either separator. */\nexport function isInside(path: string, folder: string): boolean {\n if (path === folder) return true\n const base = folder.replace(/[\\\\/]+$/u, '')\n return path.startsWith(`${base}/`) || path.startsWith(`${base}\\\\`)\n}\n\n/**\n * The checkout a folder belongs to: the nearest folder above it with `.git`; for a linked worktree (`.git` is a file pointing into\n * `<main>/.git/worktrees/<name>`), the main checkout. Synchronous and git-free, so a prompt provider can call it. The main checkout is spelled\n * the way git wrote it (on Windows long names and `/`, turned into native separators here), so compare it with `samePlaceOrInside`, not as text.\n */\nexport function checkoutOf(folder: string): string | undefined {\n for (let current = resolve(folder); ; current = dirname(current)) {\n const marker = join(current, '.git')\n if (existsSync(marker)) {\n try {\n if (statSync(marker).isFile()) {\n const pointer = /^gitdir:\\s*(.+)$/mu.exec(readFileSync(marker, 'utf8'))?.[1]?.trim()\n const at = pointer?.search(/[\\\\/]\\.git[\\\\/]worktrees[\\\\/]/u) ?? -1\n if (pointer !== undefined && at > 0) return resolve(pointer.slice(0, at))\n }\n } catch {\n // An unreadable marker: the folder itself is the checkout.\n }\n return current\n }\n if (dirname(current) === current) return undefined\n }\n}\n\n/** A path as the file system names it (Windows 8.3 short names, letter case and symlinks resolved); a missing path only resolved. */\nfunction canonical(path: string): string {\n try {\n return realpathSync.native(path)\n } catch {\n return resolve(path)\n }\n}\n\n/** `path` is `folder` or below it, however each is spelled (see `canonical`). */\nexport function samePlaceOrInside(path: string, folder: string): boolean {\n return isInside(path, folder) || isInside(canonical(path), canonical(folder))\n}\n\nexport class SharedContext {\n constructor(private readonly deps: { readonly registry: SharedContextRegistry, readonly home: string }) {}\n\n /** `<home>/workspaces/<id>/`. */\n folder(id: string): string {\n return join(this.deps.home, 'workspaces', id)\n }\n\n briefPath(id: string): string {\n return join(this.folder(id), 'BRIEF.md')\n }\n\n documentPath(id: string): string {\n return join(this.folder(id), 'WORKSPACE.md')\n }\n\n /**\n * The Shared Context workspace an agent working in `folder` belongs to: the shown workspace when it is shared and holds the folder, else\n * the first shared one that does; `undefined` in an Individual Projects workspace (nothing crosses projects there).\n */\n forFolder(folder: string): WorkspaceSummary | undefined {\n const view = this.deps.registry.view()\n const checkout = checkoutOf(folder)\n const places = checkout === undefined ? [folder] : [folder, checkout]\n const holds = (workspace: WorkspaceSummary): boolean => workspace.kind === 'shared' && workspace.projects.some(project => places.some(place => samePlaceOrInside(place, project)))\n const shown = view.workspaces.find(workspace => workspace.id === view.current)\n if (shown !== undefined && holds(shown)) return shown\n return view.workspaces.find(holds)\n }\n\n /** What an agent working in `folder` is told, or `undefined` outside a Shared Context workspace. */\n contextFor(folder: string): WorkspaceContext | undefined {\n const workspace = this.forFolder(folder)\n if (workspace === undefined) return undefined\n return {\n workspace,\n prompt: renderContextPrompt(this.input(workspace)),\n documentPath: this.documentPath(workspace.id),\n otherProjects: (start: string) => {\n const checkout = checkoutOf(start) ?? start\n return workspace.projects.filter(project => !samePlaceOrInside(start, project) && !samePlaceOrInside(checkout, project))\n },\n }\n }\n\n /** What a terminal agent started in `cwd` is given (`WorkspacePtyRegistry`'s launch context): nothing outside a shared workspace. */\n launchFor(agentId: string, cwd: string): ContextLaunch | undefined {\n const context = this.contextFor(cwd)\n if (context === undefined) return undefined\n return contextLaunch(agentId, { prompt: context.prompt, documentPath: context.documentPath, otherProjects: context.otherProjects(cwd), workspaceFolder: this.folder(context.workspace.id) })\n }\n\n /** The prompt block for a workspace by id (the tool's answer), or `undefined` when it is not a shared workspace. */\n promptFor(id: string): string | undefined {\n const workspace = this.deps.registry.view().workspaces.find(candidate => candidate.id === id)\n return workspace?.kind === 'shared' ? renderContextPrompt(this.input(workspace)) : undefined\n }\n\n brief(id: string): string {\n try {\n return readFileSync(this.briefPath(id), 'utf8')\n } catch {\n return ''\n }\n }\n\n /** Save a workspace's brief and rewrite its document. @throws when the workspace does not exist or the brief is too long. */\n setBrief(id: string, text: string): void {\n const workspace = this.deps.registry.view().workspaces.find(candidate => candidate.id === id)\n if (workspace === undefined) throw new Error(`there is no workspace ${id}`)\n if (text.length > MAX_BRIEF_CHARS) throw new Error(`the brief is longer than ${String(MAX_BRIEF_CHARS)} characters`)\n writeAtomically(this.briefPath(id), text)\n if (workspace.kind === 'shared') writeAtomically(this.documentPath(id), renderContextDocument(this.input(workspace)))\n }\n\n /** Rewrite `WORKSPACE.md` for every shared workspace. */\n writeDocuments(view: ProjectRegistryView = this.deps.registry.view()): void {\n for (const workspace of view.workspaces) {\n if (workspace.kind === 'shared') writeAtomically(this.documentPath(workspace.id), renderContextDocument(this.input(workspace)))\n }\n }\n\n /** Keep the documents current as the registry changes. @returns disposer, for one owning effect. */\n start(report: (cause: unknown) => void): () => void {\n const write = (view?: ProjectRegistryView): void => {\n try { this.writeDocuments(view) } catch (cause) { report(cause) }\n }\n write()\n return this.deps.registry.onChange(write)\n }\n\n private input(workspace: WorkspaceSummary): ContextInput {\n return {\n name: workspace.name,\n projects: workspace.projects.map(path => ({\n name: basename(path),\n path,\n instructions: INSTRUCTION_FILES.filter(file => existsSync(join(path, file))),\n })),\n brief: this.brief(workspace.id),\n documentPath: this.documentPath(workspace.id),\n briefPath: this.briefPath(workspace.id),\n }\n }\n}\n\nfunction writeAtomically(path: string, text: string): void {\n mkdirSync(dirname(path), { recursive: true })\n const temporary = `${path}.${String(process.pid)}.tmp`\n writeFileSync(temporary, text)\n renameSync(temporary, path)\n}\n","/** 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. */\n\nimport { Acryl } from '@acryldev/blends'\nimport { bodyLimit } from '@acryldev/blends/body-limit'\nimport { INVALID_JSON, ownPage, readJson, WORKSPACE_API_PREFIX } from '../private-route.ts'\nimport { MAX_BRIEF_CHARS, type SharedContext } from './service.ts'\n\nexport const WORKSPACE_BRIEF_PATH = `${WORKSPACE_API_PREFIX}/brief`\n\nexport type BriefResponse =\n | { readonly ok: true, readonly id: string, readonly text: string }\n | { readonly ok: false, readonly message: string }\n\nconst ID = /^[A-Za-z0-9_-]{1,64}$/u\n\nexport function briefRoutes(shared: SharedContext): Acryl {\n return new Acryl()\n .get(WORKSPACE_BRIEF_PATH, ownPage, (c) => {\n const id = c.req.query('id') ?? ''\n if (!ID.test(id)) return c.json({ ok: false, message: 'a workspace id is required' } satisfies BriefResponse, 400)\n return c.json({ ok: true, id, text: shared.brief(id) } satisfies BriefResponse)\n })\n .post(\n WORKSPACE_BRIEF_PATH,\n ownPage,\n bodyLimit({ maxSize: MAX_BRIEF_CHARS * 4 + 1024, onError: c => c.json({ ok: false, message: 'the brief is too long' } satisfies BriefResponse, 413) }),\n async (c) => {\n const body = await readJson(c)\n if (body === INVALID_JSON) return c.json({ ok: false, message: 'invalid request body' } satisfies BriefResponse, 400)\n const { id, text } = (typeof body === 'object' && body !== null ? body : {}) as { id?: unknown, text?: unknown }\n if (typeof id !== 'string' || !ID.test(id) || typeof text !== 'string') return c.json({ ok: false, message: 'send { id, text }' } satisfies BriefResponse, 400)\n try {\n shared.setBrief(id, text)\n return c.json({ ok: true, id, text } satisfies BriefResponse)\n } catch (cause) {\n return c.json({ ok: false, message: cause instanceof Error ? cause.message : String(cause) } satisfies BriefResponse, 400)\n }\n },\n )\n}\n","/**\n * `acryl_workspace_context` (spec 043 T011): any agent reads a Shared Context workspace's context, through the tool registry the DSH chat\n * uses and, for agents ACRYL does not run, the loopback tool gateway (it is on the gateway's default allowlist). Reading only.\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport { defineAcrylTool } from '@acryldev/control'\nimport type { ProjectRegistryView } from '../projects/contract.ts'\n\nexport const WORKSPACE_CONTEXT_TOOL = 'acryl_workspace_context'\n\nexport interface ContextToolValue {\n readonly workspace: string\n readonly shared: boolean\n readonly text: string\n}\n\nexport interface ContextToolDeps {\n view(): ProjectRegistryView\n promptFor(id: string): string | undefined\n}\n\n/** @returns the value for a workspace id, the shown one by default. */\nexport function readWorkspaceContext(deps: ContextToolDeps, id?: string): ContextToolValue {\n const view = deps.view()\n const workspace = id ?? view.current\n if (!view.workspaces.some(candidate => candidate.id === workspace)) throw new Error(`there is no workspace ${workspace}; call acryl_workspace_list`)\n const text = deps.promptFor(workspace)\n return text === undefined\n ? { workspace, shared: false, text: 'This workspace does not share context: its projects are separate.' }\n : { workspace, shared: true, text }\n}\n\n/** @returns disposer. */\nexport function registerContextTool(ctx: Context, deps: ContextToolDeps): () => void {\n return ctx.acrylTools.register(defineAcrylTool({\n name: WORKSPACE_CONTEXT_TOOL,\n description: 'Read a shared-context workspace\\'s projects and brief (default: the shown workspace).',\n parameters: { workspace: { type: 'string' } },\n output: {\n schema: {\n type: 'object', additionalProperties: false,\n properties: { workspace: { type: 'string', required: true }, shared: { type: 'boolean', required: true }, text: { type: 'string', required: true } },\n },\n render: (_args, value: ContextToolValue) => [{ type: 'text', text: value.text }],\n },\n execute: args => readWorkspaceContext(deps, args.workspace),\n }))\n}\n","/** Cordis Host plugin: ACRYL Workspace PTY table and loopback routes. */\n\nimport { randomBytes } from 'node:crypto'\nimport { basename } from 'node:path'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type {} from '@acryldev/control'\nimport type { Acryl } from '@acryldev/blends'\nimport type {} from '@acryldev/blends/cordis/router'\nimport type {} from '@acryldev/blends/cordis/router-http'\nimport { agentRoutes } from './agents/route.ts'\nimport { AgentCatalog } from './agents/catalog.ts'\nimport { agentSettingsFile, agentsFile, createFileCatalogStore } from './agents/file-store.ts'\nimport { AgentSettings } from './agents/settings.ts'\nimport { AgentStatusStore, WORKSPACE_AGENT_STATUS_PATH } from './agents/status/agent-status.ts'\nimport { agentStatusRoutes } from './agents/status/route.ts'\nimport { capabilityRoutes } from './capabilities/route.ts'\nimport { filesRoutes } from './files/route.ts'\nimport { WorkspaceFiles, WorkspaceFilesError } from './files/service.ts'\nimport { pickFolderNatively, singleFlight } from './folder-picker/picker.ts'\nimport { pickFolderRoutes } from './folder-picker/route.ts'\nimport { gitRoutes } from './git/route.ts'\nimport { WorkspaceGit, WorkspaceGitError } from './git/service.ts'\nimport { WORKSPACE_API_PREFIX, privateApi } from './private-route.ts'\nimport { PROJECTS_NAMESPACE, ProjectRegistry, ProjectsSchema } from './projects/registry.ts'\nimport { createKeepAlive, projectRoutes } from './projects/route.ts'\nimport { registerWorkspaceTools } from './projects/tools.ts'\nimport { WORKSPACE_PTY_STREAM_PATH } from './pty/contract.ts'\nimport { spawnNodePty } from './pty/node-pty-spawn.ts'\nimport { ptyRoutes } from './pty/route.ts'\nimport { WorkspacePtyRegistry } from './pty/service.ts'\nimport { ptyStreamRoutes } from './pty/stream.ts'\nimport { registerChatContext, type SystemPromptContextPort } from './shared-context/chat.ts'\nimport { briefRoutes } from './shared-context/route.ts'\nimport { SHARED_CONTEXT_SERVICE, SharedContext } from './shared-context/service.ts'\nimport { registerContextTool } from './shared-context/tool.ts'\n\n/** Stable Cordis plugin name. */\nexport const name = 'acryl-workspace'\n\n/**\n * The part of the runtime's `appInstance` service ACRYL plugins read (a separated interface: plugins do not import the runtime). Every plugin declares\n * exactly this shape, so the Context augmentations agree in any program that loads several of them.\n */\ninterface AppInstanceService {\n readonly home: string\n readonly dshHome: string\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n appInstance: AppInstanceService\n }\n}\n\n/**\n * The row's config, written by the generated overlay when the frame hosts an app: where the app's own page is served (`/app`). The page opens it in a\n * browser tile on first run, so the person starts at the app they are building rather than an empty canvas.\n */\nexport interface WorkspaceConfig {\n readonly appPage?: string\n /** A folder to open on: added to the projects shown at start (`acryl ade` passes the folder it was started in). Not a folder: ignored. */\n readonly openFolder?: string\n}\n\n/**\n * The routes, the terminal's WebSocket among them, are served by the router (`router`, `routerHttp`) under {@link WORKSPACE_API_PREFIX}. The\n * loopback Web server is still needed for its address (agent hooks report to it). The app instance says where this app keeps its data.\n */\nexport const inject = ['acrylWeb', 'appInstance', 'acrylSettings', 'router', 'routerHttp']\n\n/**\n * Activate the workspace's Host half: its services and their routes. Disabling the Loader row unmounts the routes and kills leftover PTY sessions.\n * @param ctx - Host context for this generation.\n */\nexport function apply(ctx: Context, config: WorkspaceConfig = {}): void {\n if (ctx.acrylWeb.host !== '127.0.0.1') {\n throw new Error('@acryldev/workspace: requires a loopback Web server')\n }\n const appPage = typeof config.appPage === 'string' && config.appPage.startsWith('/') ? config.appPage : undefined\n const rendererOrigin = `http://127.0.0.1:${String(ctx.acrylWeb.port)}`\n const reportHostError = (operation: string, cause: unknown): void => {\n ctx.logger.error(\n `@acryldev/workspace: failed to ${operation}: ${cause instanceof Error ? cause.message : String(cause)}`,\n )\n }\n // The services and their routes are built in the effect; the terminal's sockets are taken and the app mounted after it, so on unload the\n // mount goes first (its requests end and are waited for), then the terminal sockets close with 1001, then the PTYs, git and the rest go.\n const built: { routes?: readonly Acryl[]; pty?: WorkspacePtyRegistry } = {}\n ctx.effect(() => {\n // The user's custom agents live in their ACRYL home; the registry asks the catalog what an id means.\n // The registry asks the settings what an id runs; the settings ask the catalog and the registry's own PATH search.\n let settings: AgentSettings | undefined\n // Agents that support hooks report working, waiting and done here; the secret is known only to their terminals.\n const statusToken = randomBytes(24).toString('hex')\n // An agent started in a Shared Context workspace gets its context; the service is set further down, once the registry exists.\n let sharedContext: SharedContext | undefined\n const workspacePty = new WorkspacePtyRegistry({\n spawn: spawnNodePty,\n agents: { resolve: id => settings?.resolve(id) },\n launchContext: { launchFor: (id, cwd) => sharedContext?.launchFor(id, cwd) },\n agentStatus: { url: `${rendererOrigin}${WORKSPACE_AGENT_STATUS_PATH}`, token: statusToken },\n })\n const agentStatus = new AgentStatusStore(id => workspacePty.has(id))\n const catalog = new AgentCatalog(createFileCatalogStore(agentsFile(ctx.appInstance.home)), command => workspacePty.canRun(command))\n const agentSettings = new AgentSettings(createFileCatalogStore(agentSettingsFile(ctx.appInstance.home)), catalog, command => workspacePty.canRun(command))\n settings = agentSettings\n void catalog.load().catch(reportHostError.bind(undefined, 'load custom agents'))\n void agentSettings.load().catch(reportHostError.bind(undefined, 'load agent settings'))\n const workspaceGit = new WorkspaceGit()\n const workspaceFiles = new WorkspaceFiles({\n // Only a git worktree root is a place the editor may touch; a failed check surfaces as a bad path.\n resolveWorktree: async (path) => {\n try {\n return await workspaceGit.worktreeRoot(path)\n } catch (cause) {\n if (cause instanceof WorkspaceGitError && cause.kind === 'invalid') throw new WorkspaceFilesError(cause.message, 'invalid')\n throw cause\n }\n },\n ignored: (root, paths) => workspaceGit.ignored(root, paths),\n })\n const releases: Array<() => void> = []\n try {\n // The project list is ACRYL's own: one section of the ACRYL home's settings, released with this plugin so a reloaded plugin registers it again.\n const projects = new ProjectRegistry(ctx.acrylSettings.register(PROJECTS_NAMESPACE, ProjectsSchema))\n // The app itself is the first project: its own folder, so the left pane has a place for the first chats and the agent works where\n // the app lives. Added once, only while the list is empty; removing it later stays the person's choice and is not undone here.\n const appRoot = (ctx.appInstance as { readonly root?: unknown }).root\n // The folder the app was started on (`acryl ade` in a project) is the one asked for: it is added, and on a first start instead of the app's own.\n const openFolder = typeof config.openFolder === 'string' && config.openFolder !== '' ? config.openFolder : undefined\n const first = openFolder ?? (typeof appRoot === 'string' && projects.view().paths.length === 0 ? appRoot : undefined)\n if (first !== undefined)\n void projects.add(first).catch(cause => { reportHostError(`add ${first} as a project`, cause) })\n // Shared context (spec 043 T009): the generated WORKSPACE.md of every Shared Context workspace stays current, and other plugins can read it.\n const shared = new SharedContext({ registry: projects, home: ctx.appInstance.home })\n sharedContext = shared\n releases.push(shared.start(cause => { reportHostError('write the shared workspace context', cause) }))\n const withdrawSharedContext = ctx.reflect.provide(SHARED_CONTEXT_SERVICE, shared)\n releases.push(() => { void withdrawSharedContext() })\n // The DSH chat in a Shared Context workspace is told about it (T010); present while the harness's system prompt service is.\n const contextFor = (folder: string): { readonly prompt: string } | undefined => sharedContext?.contextFor(folder)\n const chatContextFiber = ctx.inject(['systemPrompt'], (child) => {\n const systemPrompt = (child as unknown as { readonly systemPrompt: SystemPromptContextPort }).systemPrompt\n child.effect(() => registerChatContext(systemPrompt, contextFor), '@acryldev/workspace: shared workspace context for the chat')\n })\n releases.push(() => { void chatContextFiber.dispose() })\n // The context for any agent through the tool registry and the gateway, and the agent's workspace tools (spec 043 T007); present while\n // ACRYL's tool port is.\n const contextToolFiber = ctx.inject(['acrylTools'], (child) => {\n child.effect(() => registerContextTool(child, { view: () => projects.view(), promptFor: id => sharedContext?.promptFor(id) }), '@acryldev/workspace: workspace context tool')\n })\n releases.push(() => { void contextToolFiber.dispose() })\n const toolsFiber = ctx.inject(['acrylTools'], (child) => {\n child.effect(() => registerWorkspaceTools(child, projects), '@acryldev/workspace: workspace agent tools')\n })\n releases.push(() => { void toolsFiber.dispose() })\n const keepAlive = createKeepAlive()\n releases.push(() => { keepAlive.stop() })\n // The chat is the DSH `agents` service; reading it per request, not injecting it, is what lets this plugin stay up when the chat is off.\n const services: { get(name: string): unknown } = ctx\n // The OS's own folder chooser, for the \"+\" on Web (a browser page cannot open one that yields a path).\n const pickFolder = singleFlight(() => pickFolderNatively(process.platform))\n built.pty = workspacePty\n built.routes = [\n ptyRoutes(workspacePty, reportHostError),\n agentRoutes(catalog, agentSettings, reportHostError),\n agentStatusRoutes(statusToken, agentStatus, reportHostError),\n capabilityRoutes(() => ({\n chat: services.get('agents') !== undefined,\n ...(appPage === undefined ? {} : { appPage }),\n ...(typeof appRoot === 'string' ? { appRoot, appName: basename(appRoot) } : {}),\n })),\n projectRoutes(projects, keepAlive, reportHostError),\n briefRoutes(shared),\n filesRoutes(workspaceFiles, reportHostError),\n gitRoutes(workspaceGit, reportHostError),\n pickFolderRoutes(pickFolder, reportHostError),\n ]\n } catch (cause) {\n for (const release of releases.reverse()) release()\n void workspaceGit.dispose()\n throw cause\n }\n return async () => {\n for (const release of releases.reverse()) release()\n await Promise.all([workspacePty.disposeAll(), workspaceGit.dispose()])\n }\n }, '@acryldev/workspace: PTY table, git, files, projects and agents')\n if (built.routes === undefined || built.pty === undefined) throw new Error('@acryldev/workspace: the routes were not built')\n const upgrade = ctx.routerHttp.upgrades()\n // Removing the mount ends the requests still in flight, the project event streams among them.\n ctx.router.route('/', privateApi(...built.routes, ptyStreamRoutes(built.pty, upgrade, reportHostError)))\n ctx.routerHttp.mount(WORKSPACE_API_PREFIX, { upgrade: [WORKSPACE_PTY_STREAM_PATH] })\n}\n\n/** The agent's workspace tools, exported so the runtime can check their schemas against DSH's own compiler. */\nexport { registerWorkspaceTools } from './projects/tools.ts'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AAC,IAAI,EAAE,QAAQ;KAC3C,GAAI,OAAO,YAAY,WAAW;MAAE;MAAS,SAAS,SAAS,OAAO;KAAE,IAAI,CAAC;IAC/E,EAAE;IACF,cAAc,UAAU,WAAW,eAAe;IAClD,YAAY,MAAM;IAClB,YAAY,gBAAgB,eAAe;IAC3C,UAAU,cAAc,eAAe;IACvC,iBAAiB,YAAY,eAAe;GAC9C;EACF,SAAS,OAAO;GACd,KAAK,MAAM,WAAW,SAAS,QAAQ,GAAG,QAAQ;GAClD,aAAkB,QAAQ;GAC1B,MAAM;EACR;EACA,OAAO,YAAY;GACjB,KAAK,MAAM,WAAW,SAAS,QAAQ,GAAG,QAAQ;GAClD,MAAM,QAAQ,IAAI,CAAC,aAAa,WAAW,GAAG,aAAa,QAAQ,CAAC,CAAC;EACvE;CACF,GAAG,iEAAiE;CACpE,IAAI,MAAM,WAAW,KAAA,KAAa,MAAM,QAAQ,KAAA,GAAW,MAAM,IAAI,MAAM,gDAAgD;CAC3H,MAAM,UAAU,IAAI,WAAW,SAAS;CAExC,IAAI,OAAO,MAAM,KAAKC,aAAW,GAAG,MAAM,QAAQ,gBAAgB,MAAM,KAAK,SAAS,eAAe,CAAC,CAAC;CACvG,IAAI,WAAW,MAAM,sBAAsB,EAAE,SAAS,CAAC,yBAAyB,EAAE,CAAC;AACrF"}
1
+ {"version":3,"file":"index.js","names":["privateApi","privateRoutes","isRecord","isRecord","isRecord","isRecord","isRecord","isRecord","isInside","required","isRecord","isRecord","spawnPty","isRecord","privateApi"],"sources":["../src/private-route.ts","../src/agents/known-agents.ts","../src/pty/contract.ts","../src/agents/definition.ts","../src/agents/contract.ts","../src/agents/launch.ts","../src/agents/preferences.ts","../src/agents/route.ts","../src/agents/catalog.ts","../src/agents/file-store.ts","../src/agents/settings.ts","../src/agents/status/agent-status.ts","../src/agents/status/route.ts","../src/capabilities/contract.ts","../src/capabilities/route.ts","../src/files/contract.ts","../src/files/service.ts","../src/files/route.ts","../src/folder-picker/picker.ts","../src/folder-picker/contract.ts","../src/folder-picker/route.ts","../src/git/contract.ts","../src/git/errors.ts","../src/git/guards.ts","../src/git/parsing.ts","../src/git/runner.ts","../src/git/changes.ts","../src/git/checks.ts","../src/git/commits.ts","../src/git/ignored.ts","../src/git/search.ts","../src/git/worktrees.ts","../src/git/service.ts","../src/git/route.ts","../src/projects/contract.ts","../src/projects/registry.ts","../src/projects/route.ts","../src/projects/tools.ts","../src/pty/node-pty-spawn.ts","../src/pty/route.ts","../src/agents/status/claude-hooks.ts","../src/pty/scrollback.ts","../src/pty/screen-model.ts","../src/pty/service.ts","../src/pty/stream.ts","../src/shared-context/chat.ts","../src/shared-context/launch.ts","../src/shared-context/render.ts","../src/shared-context/service.ts","../src/shared-context/route.ts","../src/shared-context/tool.ts","../src/index.ts"],"sourcesContent":["/**\n * What every workspace route shares, on the router: the private-route rules of `@acryldev/loopback-http/router` (only the app's own page\n * may call it, answers are never cached or sniffed, a JSON body is small) under the workspace's one prefix. Each domain folder builds its\n * routes with these and `index.ts` mounts them under {@link WORKSPACE_API_PREFIX}.\n */\n\nimport type { Acryl } from '@acryldev/blends'\nimport { privateApi as privateRoutes } from '@acryldev/loopback-http/router'\n\nexport { INVALID_JSON, jsonBody, ownPage, ownPageSocket, readJson, type ReportError } from '@acryldev/loopback-http/router'\n\n/** Every workspace route lives below this path; it is the one prefix the plugin mounts on the Web server. */\nexport const WORKSPACE_API_PREFIX = '/api/acryl-workspace'\n\n/** The workspace's routes as one app, the shared rules scoped to {@link WORKSPACE_API_PREFIX}. */\nexport function privateApi(...routes: readonly Acryl[]): Acryl {\n return privateRoutes(WORKSPACE_API_PREFIX, ...routes)\n}\n\nexport function failure(message: string): { readonly error: string } {\n return { error: message }\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n","/**\n * The coding agents ACRYL knows by name: what to run, which flags mean \"do not ask me\", and where to install\n * them. This is the single source for the \"+\" menu, the launcher and Settings > Agents; the closed list of\n * ids is also the Host's allowlist of what a terminal tab may start.\n *\n * The launch commands, permission flags and install pages follow the public documentation of each agent\n * (the shape of the list is inspired by Orca's agent catalog, MIT licensed).\n */\n\n/** The permission mode a launch uses. `yolo` adds the agent's own \"skip approvals\" flags; `manual` adds none. */\nexport type PermissionMode = 'yolo' | 'manual'\n\nexport interface KnownAgent {\n readonly id: string\n readonly label: string\n /** The executable looked up on PATH. */\n readonly command: string\n /** Added to a launch in `yolo` mode, one argument per entry. */\n readonly yoloArgs: readonly string[]\n /** Environment added to a launch in `yolo` mode. */\n readonly yoloEnv?: Readonly<Record<string, string>>\n /** Where the agent's install instructions live. */\n readonly homepageUrl: string\n /** How this agent reports what it is doing, when it can (hooks): its own launch settings carry the reporting. */\n readonly statusHooks?: 'claude'\n /** The letter and colour of its tab icon when no drawn mark exists. */\n readonly badge: { readonly letter: string; readonly color: string }\n}\n\nconst agent = (\n id: string, label: string, command: string, homepageUrl: string, color: string,\n yoloArgs: readonly string[] = [], yoloEnv?: Readonly<Record<string, string>>,\n): KnownAgent => ({\n id, label, command, homepageUrl, yoloArgs, ...(yoloEnv === undefined ? {} : { yoloEnv }),\n badge: { letter: [...label][0]?.toUpperCase() ?? '?', color },\n})\n\n/** In the order the lists show them. Ids of agents that shipped earlier keep their spelling. */\nexport const KNOWN_AGENTS = [\n { ...agent('claude', 'Claude', 'claude', 'https://code.claude.com/docs', '#d97757', ['--dangerously-skip-permissions']), statusHooks: 'claude' as const },\n agent('codex', 'Codex', 'codex', 'https://github.com/openai/codex', '#10a37f', ['--dangerously-bypass-approvals-and-sandbox']),\n agent('grok', 'Grok', 'grok', 'https://x.ai/cli', '#94a3b8', ['--permission-mode', 'bypassPermissions']),\n agent('copilot', 'GitHub Copilot', 'copilot', 'https://docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli', '#a78bfa', ['--yolo']),\n agent('opencode', 'OpenCode', 'opencode', 'https://opencode.ai/docs/cli/', '#94a3b8'),\n agent('ante', 'Ante', 'ante', 'https://github.com/AntigmaLabs/ante-preview', '#fb923c', ['--yolo']),\n agent('pi', 'Pi', 'pi', 'https://pi.dev', '#a78bfa'),\n agent('omp', 'OMP', 'omp', 'https://omp.sh', '#a78bfa'),\n agent('gemini', 'Gemini', 'gemini', 'https://github.com/google-gemini/gemini-cli', '#4285f4', ['--yolo']),\n agent('antigravity', 'Antigravity', 'agy', 'https://antigravity.google/docs/cli-overview', '#4285f4', ['--dangerously-skip-permissions']),\n agent('aider', 'Aider', 'aider', 'https://aider.chat/docs/', '#34d399', ['--yes-always']),\n agent('goose', 'Goose', 'goose', 'https://block.github.io/goose/docs/quickstart/', '#f59e0b', [], { GOOSE_MODE: 'auto' }),\n agent('amp', 'Amp', 'amp', 'https://ampcode.com/manual#install', '#ef4444', ['--dangerously-allow-all']),\n agent('kilo', 'Kilocode', 'kilo', 'https://kilo.ai/docs/cli', '#f59e0b'),\n agent('crush', 'Charm', 'crush', 'https://github.com/charmbracelet/crush', '#a78bfa', ['--yolo']),\n agent('command-code', 'Command Code', 'command-code', 'https://commandcode.ai/docs/quickstart', '#94a3b8', ['--yolo']),\n agent('cursor', 'Cursor', 'cursor-agent', 'https://cursor.com/cli', '#94a3b8', ['--yolo']),\n agent('droid', 'Droid', 'droid', 'https://docs.factory.ai/cli/getting-started/quickstart', '#94a3b8', ['--auto', 'high']),\n agent('kimi', 'Kimi', 'kimi', 'https://www.kimi.com/code/docs/en/kimi-code-cli/getting-started.html', '#38bdf8', ['--yolo']),\n agent('mistral-vibe', 'Mistral Vibe', 'vibe', 'https://github.com/mistralai/mistral-vibe', '#fb923c', ['--agent', 'auto-approve']),\n agent('qwen', 'Qwen Code', 'qwen', 'https://github.com/QwenLM/qwen-code', '#a78bfa', ['--approval-mode', 'yolo']),\n agent('hermes', 'Hermes', 'hermes', 'https://hermes-agent.nousresearch.com/docs/', '#94a3b8', ['--yolo']),\n agent('mimo-code', 'MiMo Code', 'mimo', 'https://mimo.xiaomi.com/coder', '#94a3b8'),\n agent('trae', 'Trae', 'traecli', 'https://docs.trae.cn/cli_get-started-with-trae-cli', '#34d399', ['--yolo']),\n agent('kiro', 'Kiro', 'kiro-cli', 'https://kiro.dev/docs/cli/', '#a78bfa', ['--trust-all-tools']),\n agent('aug', 'Auggie', 'auggie', 'https://docs.augmentcode.com/cli/overview', '#94a3b8'),\n agent('autohand', 'Autohand Code', 'autohand', 'https://github.com/autohandai/code-cli', '#94a3b8', ['--unrestricted']),\n agent('cline', 'Cline', 'cline', 'https://docs.cline.bot/cline-cli/overview', '#94a3b8', ['--auto-approve', 'true']),\n agent('codebuff', 'Codebuff', 'codebuff', 'https://www.codebuff.com/docs/help/quick-start', '#94a3b8'),\n agent('continue', 'Continue', 'cn', 'https://docs.continue.dev/guides/cli', '#94a3b8', ['--allow', '*']),\n agent('rovo', 'Rovo Dev', 'rovo', 'https://support.atlassian.com/rovo/docs/install-and-run-rovo-dev-cli-on-your-device/', '#4285f4', ['--yolo']),\n agent('devin', 'Devin', 'devin', 'https://devin.ai/cli', '#34d399', ['--permission-mode', 'bypass', '--respect-workspace-trust', 'false']),\n agent('openclaw', 'OpenClaw', 'openclaw', 'https://github.com/openclaw/openclaw', '#ef4444'),\n] as const satisfies readonly KnownAgent[]\n\nexport type KnownAgentId = (typeof KNOWN_AGENTS)[number]['id']\n\nexport const KNOWN_AGENT_IDS: readonly KnownAgentId[] = KNOWN_AGENTS.map(entry => entry.id)\n\nconst BY_ID = new Map<string, KnownAgent>(KNOWN_AGENTS.map(entry => [entry.id, entry]))\n\n/** @returns the known agent with this id, or undefined (a custom agent, the terminal, or nothing). */\nexport function knownAgent(id: string): KnownAgent | undefined {\n return BY_ID.get(id)\n}\n","/** Allowlisted ACRYL Workspace PTY commands and loopback routes. */\n\nimport { KNOWN_AGENT_IDS, type KnownAgentId } from '../agents/known-agents.ts'\n\n/** The terminal, then every agent ACRYL knows by name (`agents/known-agents.ts` owns that list). */\nexport const WORKSPACE_PTY_COMMAND_IDS = ['shell', ...KNOWN_AGENT_IDS] as const\n\nexport type WorkspacePtyCommandId = 'shell' | KnownAgentId\n\nexport const WORKSPACE_PTY_PATH = '/api/acryl-workspace/pty'\nexport const WORKSPACE_PTY_INPUT_PATH = '/api/acryl-workspace/pty/input'\nexport const WORKSPACE_PTY_RESIZE_PATH = '/api/acryl-workspace/pty/resize'\nexport const WORKSPACE_PTY_CLOSE_PATH = '/api/acryl-workspace/pty/close'\n/** WebSocket: live output down, keystrokes and size up, in order. Query: `id`, `since` (cursor already shown). */\nexport const WORKSPACE_PTY_STREAM_PATH = '/api/acryl-workspace/pty/stream'\n\nconst COMMAND_IDS = new Set<string>(WORKSPACE_PTY_COMMAND_IDS)\n\n/** @param value - unknown command id from JSON. */\nexport function isWorkspacePtyCommandId(value: unknown): value is WorkspacePtyCommandId {\n return typeof value === 'string' && COMMAND_IDS.has(value)\n}\n\nexport type WorkspacePtyStatus = 'starting' | 'running' | 'exited' | 'error'\n\nexport interface WorkspacePtyView {\n readonly id: string\n readonly status: WorkspacePtyStatus\n readonly output: string\n readonly exitCode: number | null\n readonly error: string | null\n}\n\n/** What the Host sends over the stream. */\nexport type PtyServerMessage =\n /** Output. `replace` clears the client's terminal first (it missed more than the Host kept). */\n | { readonly t: 'out'; readonly data: string; readonly cursor: number; readonly replace: boolean }\n | { readonly t: 'exit'; readonly exitCode: number | null; readonly error: string | null }\n\n/** What the client sends over the stream. */\nexport type PtyClientMessage =\n | { readonly t: 'in'; readonly data: string }\n | { readonly t: 'resize'; readonly cols: number; readonly rows: number }\n\nexport const MAX_PTY_INPUT_CHARS = 256 * 1024\nexport const MAX_PTY_COLS = 500\nexport const MAX_PTY_ROWS = 200\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** @param text - one text frame from the client; null when it is not a well-formed message. */\nexport function parsePtyClientMessage(text: string): PtyClientMessage | null {\n let value: unknown\n try {\n value = JSON.parse(text)\n } catch {\n return null\n }\n if (!isRecord(value)) return null\n if (value.t === 'in' && typeof value.data === 'string' && value.data.length <= MAX_PTY_INPUT_CHARS && Object.keys(value).length === 2) {\n return { t: 'in', data: value.data }\n }\n if (value.t === 'resize' && Object.keys(value).length === 3\n && typeof value.cols === 'number' && typeof value.rows === 'number'\n && Number.isInteger(value.cols) && Number.isInteger(value.rows)\n && value.cols >= 2 && value.cols <= MAX_PTY_COLS && value.rows >= 1 && value.rows <= MAX_PTY_ROWS) {\n return { t: 'resize', cols: value.cols, rows: value.rows }\n }\n return null\n}\n\n/** @param text - one text frame from the Host; throws on anything unexpected. */\nexport function parsePtyServerMessage(text: string): PtyServerMessage {\n const value: unknown = JSON.parse(text)\n if (isRecord(value)) {\n if (value.t === 'out' && typeof value.data === 'string' && typeof value.cursor === 'number' && typeof value.replace === 'boolean') {\n return { t: 'out', data: value.data, cursor: value.cursor, replace: value.replace }\n }\n if (value.t === 'exit' && (value.exitCode === null || typeof value.exitCode === 'number') && (value.error === null || typeof value.error === 'string')) {\n return { t: 'exit', exitCode: value.exitCode, error: value.error }\n }\n }\n throw new Error('@acryldev/workspace: invalid terminal stream message')\n}\n\n/** Any agent id the Host may be asked to start: a built-in one or one from the user's catalog. */\nexport type AgentId = string\n","/**\n * A custom coding agent: something the user added to the \"+\" menu. Pure rules, shared by the Host (which\n * enforces them) and the page (which uses the same rules to explain a refusal before asking).\n *\n * The Host starts an agent only by its id from the catalog, so what a definition may contain is the whole\n * safety story: a bare executable name or absolute path, an argument list that never goes through a shell,\n * and nothing else. See `specs/040-agentic-multiplexer-ade/design-phase-9.md`.\n */\n\nimport { WORKSPACE_PTY_COMMAND_IDS } from '../pty/contract.ts'\n\nexport const MAX_CUSTOM_AGENTS = 32\nexport const MAX_AGENT_ARGS = 16\nexport const MAX_AGENT_ARG_LENGTH = 200\nexport const MAX_AGENT_LABEL = 40\n\n/** The colours a badge may use, so a definition can never carry arbitrary CSS. */\nexport const BADGE_COLORS = ['#94a3b8', '#d97757', '#10a37f', '#4285f4', '#a78bfa', '#34d399', '#f59e0b', '#ef4444', '#38bdf8', '#fb923c'] as const\n\nexport interface AgentBadge {\n readonly letter: string\n readonly color: (typeof BADGE_COLORS)[number]\n}\n\nexport interface CustomAgent {\n readonly id: string\n readonly label: string\n /** An absolute path, or a bare executable name found on the Host's PATH. */\n readonly command: string\n /** Passed as an argument array to the process; never interpreted by a shell. */\n readonly args: readonly string[]\n readonly badge: AgentBadge\n}\n\n/** Thrown for a definition that breaks a rule; the message is fit to show the user. */\nexport class AgentDefinitionError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'AgentDefinitionError'\n }\n}\n\nconst ID_PATTERN = /^[a-z][a-z0-9-]{1,31}$/\n/** A bare name or an absolute path; no whitespace, quotes, or shell metacharacters. */\nconst COMMAND_PATTERN = /^(?:\\/[A-Za-z0-9._@+:%~\\-/]+|[A-Za-z0-9._@+-]+)$/\nconst BUILTIN = new Set<string>(WORKSPACE_PTY_COMMAND_IDS)\n\nexport function isBuiltinAgentId(id: string): boolean {\n return BUILTIN.has(id)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** @param value - untrusted JSON. @returns a command that is an absolute path or a bare program name. @throws AgentDefinitionError. */\nexport function parseAgentCommand(value: unknown): string {\n if (typeof value !== 'string' || !COMMAND_PATTERN.test(value) || value.includes('..')) {\n 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)')\n }\n return value\n}\n\n/** @param value - untrusted JSON; absent means no arguments. @throws AgentDefinitionError. */\nexport function parseAgentArgs(value: unknown): readonly string[] {\n const list = value === undefined ? [] : value\n if (!Array.isArray(list) || list.length > MAX_AGENT_ARGS\n || !list.every((arg): arg is string => typeof arg === 'string' && arg.length <= MAX_AGENT_ARG_LENGTH && !arg.includes('\\0'))) {\n throw new AgentDefinitionError(`up to ${String(MAX_AGENT_ARGS)} arguments of up to ${String(MAX_AGENT_ARG_LENGTH)} characters each`)\n }\n return list\n}\n\n/** @param value - untrusted JSON. @throws AgentDefinitionError with a user-facing message. */\nexport function parseCustomAgent(value: unknown): CustomAgent {\n if (!isRecord(value)) throw new AgentDefinitionError('an agent needs an id, a name, a command and a badge')\n const extra = Object.keys(value).filter(key => !['id', 'label', 'command', 'args', 'badge'].includes(key))\n if (extra.length > 0) throw new AgentDefinitionError(`unknown field: ${extra[0] ?? ''}`)\n const { id, label, command, args, badge } = value\n 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')\n if (isBuiltinAgentId(id)) throw new AgentDefinitionError(`\"${id}\" is a built-in agent`)\n if (typeof label !== 'string' || label.trim() === '' || [...label.trim()].length > MAX_AGENT_LABEL) throw new AgentDefinitionError(`the name must be 1 to ${String(MAX_AGENT_LABEL)} characters`)\n const commandText = parseAgentCommand(command)\n const argList = parseAgentArgs(args)\n if (!isRecord(badge) || typeof badge.letter !== 'string' || [...badge.letter].length !== 1\n || !(BADGE_COLORS as readonly unknown[]).includes(badge.color)) {\n throw new AgentDefinitionError('the badge needs one character and one of the offered colours')\n }\n return { id, label: label.trim(), command: commandText, args: argList, badge: { letter: badge.letter, color: badge.color as AgentBadge['color'] } }\n}\n","/** Loopback routes and JSON shapes for the custom agent catalog. */\n\nimport { parseCustomAgent, type CustomAgent } from './definition.ts'\n\n/** GET the catalog; POST `{ agent }` to add one. */\nexport const WORKSPACE_AGENTS_PATH = '/api/acryl-workspace/agents'\n/** POST `{ id }` to remove one. */\nexport const WORKSPACE_AGENTS_REMOVE_PATH = '/api/acryl-workspace/agents/remove'\n\nexport interface AgentsView {\n readonly agents: readonly CustomAgent[]\n}\n\n/** @param value - unknown JSON from the agents routes. */\nexport function parseAgentsView(value: unknown): AgentsView {\n if (typeof value !== 'object' || value === null || !('agents' in value) || !Array.isArray(value.agents)) {\n throw new Error('invalid agents response')\n }\n return { agents: value.agents.map(item => parseCustomAgent(item)) }\n}\n\n/** GET the settings view; POST a {@link PreferencesPatch} to change one thing. Both answer with the whole view. */\nexport const WORKSPACE_AGENT_SETTINGS_PATH = '/api/acryl-workspace/agents/settings'\n\n/** One row of Settings > Agents. */\nexport interface AgentSettingsEntry {\n readonly id: string\n readonly label: string\n readonly kind: 'known' | 'custom'\n /** The agent's install page (known agents only). */\n readonly homepageUrl: string | null\n /** The executable the agent ships with. */\n readonly defaultCommand: string\n /** What runs: the user's replacement when set, otherwise {@link defaultCommand}. */\n readonly command: string\n /** The user's extra arguments (known agents), or the definition's own arguments (custom agents). */\n readonly args: readonly string[]\n /** What the permission mode adds right now. */\n readonly permissionArgs: readonly string[]\n readonly permissionEnv: Readonly<Record<string, string>>\n readonly enabled: boolean\n /** The executable was found on this machine. */\n readonly installed: boolean\n /** The exact command line a new tab runs. */\n readonly preview: string\n /** Custom agents only: the badge chosen when it was added. */\n readonly badge: { readonly letter: string; readonly color: string } | null\n}\n\nexport interface AgentSettingsView {\n readonly permissions: 'yolo' | 'manual'\n /** `auto`, `none`, or the id of an existing agent. */\n readonly defaultAgent: string\n /** Agents that support hooks report working, waiting and done (the attention queue). */\n readonly statusHooks: boolean\n readonly agents: readonly AgentSettingsEntry[]\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nconst isStringArray = (value: unknown): value is string[] => Array.isArray(value) && value.every(item => typeof item === 'string')\n\nfunction parseEntry(value: unknown): AgentSettingsEntry {\n if (!isObject(value)) throw new Error('invalid agent settings entry')\n const { id, label, kind, homepageUrl, defaultCommand, command, args, permissionArgs, permissionEnv, enabled, installed, preview, badge } = value\n if (typeof id !== 'string' || typeof label !== 'string' || (kind !== 'known' && kind !== 'custom')\n || (homepageUrl !== null && typeof homepageUrl !== 'string') || typeof defaultCommand !== 'string' || typeof command !== 'string'\n || !isStringArray(args) || !isStringArray(permissionArgs) || !isObject(permissionEnv)\n || !Object.values(permissionEnv).every(item => typeof item === 'string')\n || typeof enabled !== 'boolean' || typeof installed !== 'boolean' || typeof preview !== 'string') {\n throw new Error('invalid agent settings entry')\n }\n const parsedBadge = isObject(badge) && typeof badge.letter === 'string' && typeof badge.color === 'string' ? { letter: badge.letter, color: badge.color } : null\n return { id, label, kind, homepageUrl, defaultCommand, command, args, permissionArgs, permissionEnv: permissionEnv as Record<string, string>, enabled, installed, preview, badge: parsedBadge }\n}\n\n/** @param value - unknown JSON from the settings route. */\nexport function parseAgentSettingsView(value: unknown): AgentSettingsView {\n if (!isObject(value) || (value.permissions !== 'yolo' && value.permissions !== 'manual') || typeof value.defaultAgent !== 'string' || typeof value.statusHooks !== 'boolean' || !Array.isArray(value.agents)) {\n throw new Error('invalid agent settings response')\n }\n return { permissions: value.permissions, defaultAgent: value.defaultAgent, statusHooks: value.statusHooks, agents: value.agents.map(parseEntry) }\n}\n","/**\n * What a terminal tab actually runs for an agent: the command, the arguments and the environment, from the\n * agent's own definition, the user's overrides and the permission mode. Pure: no disk, no process table.\n */\n\nimport type { KnownAgent, PermissionMode } from './known-agents.ts'\n\n/** What the user changed for one agent in Settings. */\nexport interface AgentOverride {\n /** Listed in the \"+\" menu. Off hides it; it can still be opened from an existing tab. */\n readonly enabled: boolean\n /** Replaces the agent's own executable (an absolute path or a bare name). */\n readonly command?: string\n /** Added after the permission flags, one argument per entry. */\n readonly args: readonly string[]\n}\n\nexport const DEFAULT_OVERRIDE: AgentOverride = { enabled: true, args: [] }\n\nexport interface AgentLaunch {\n readonly command: string\n readonly args: readonly string[]\n readonly env?: Readonly<Record<string, string>>\n /** This launch reports its state through hooks of this kind; the Host adds the reporting at start. */\n readonly statusHooks?: 'claude'\n}\n\n/** @returns the launch for a known agent: `yolo` adds the agent's own skip-approvals flags first. */\nexport function planKnownLaunch(agent: KnownAgent, override: AgentOverride, mode: PermissionMode, statusHooks = false): AgentLaunch {\n const yolo = mode === 'yolo'\n const env = yolo ? agent.yoloEnv : undefined\n return {\n command: override.command ?? agent.command,\n args: [...(yolo ? agent.yoloArgs : []), ...override.args],\n ...(env === undefined ? {} : { env }),\n ...(statusHooks && agent.statusHooks !== undefined ? { statusHooks: agent.statusHooks } : {}),\n }\n}\n\n/** The command line for a person to read, with any environment first (`GOOSE_MODE=auto goose`). */\nexport function describeLaunch(launch: AgentLaunch): string {\n const quote = (part: string): string => (/^[A-Za-z0-9._@+:%~/=,*-]+$/.test(part) ? part : JSON.stringify(part))\n const env = Object.entries(launch.env ?? {}).map(([name, value]) => `${name}=${quote(value)}`)\n return [...env, launch.command, ...launch.args].map(quote).join(' ')\n}\n","/**\n * The user's agent preferences: the permission mode, the default agent, and per-agent overrides. Pure rules for\n * reading the stored file and for applying one change at a time; the file itself is a port (`file-store.ts`).\n */\n\nimport { AgentDefinitionError, parseAgentArgs, parseAgentCommand } from './definition.ts'\nimport { DEFAULT_OVERRIDE, type AgentOverride } from './launch.ts'\nimport type { PermissionMode } from './known-agents.ts'\n\n/** `auto`: follow what was opened last. `none`: a blank terminal. Otherwise an agent id. */\nexport type DefaultAgent = string\n\nexport interface AgentPreferences {\n readonly permissions: PermissionMode\n readonly defaultAgent: DefaultAgent\n readonly overrides: Readonly<Record<string, AgentOverride>>\n /** Agents that support hooks report working, waiting and done to ACRYL (the attention queue). */\n readonly statusHooks: boolean\n}\n\n/** Manual is the default: an agent that skips approvals is something the user turns on. */\nexport const DEFAULT_PREFERENCES: AgentPreferences = { permissions: 'manual', defaultAgent: 'auto', overrides: {}, statusHooks: true }\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nconst isMode = (value: unknown): value is PermissionMode => value === 'yolo' || value === 'manual'\n\nfunction parseOverride(value: unknown): AgentOverride {\n if (!isRecord(value)) throw new AgentDefinitionError('an override is an object')\n const { enabled, command, args } = value\n if (enabled !== undefined && typeof enabled !== 'boolean') throw new AgentDefinitionError('enabled is true or false')\n return {\n enabled: enabled ?? true,\n ...(command === undefined ? {} : { command: parseAgentCommand(command) }),\n args: parseAgentArgs(args),\n }\n}\n\n/** @param value - the parsed stored JSON. A damaged file gives the defaults; one bad override is dropped. */\nexport function parseStoredPreferences(value: unknown): AgentPreferences {\n if (!isRecord(value)) return DEFAULT_PREFERENCES\n const overrides: Record<string, AgentOverride> = {}\n if (isRecord(value.overrides)) {\n for (const [id, raw] of Object.entries(value.overrides)) {\n try { overrides[id] = parseOverride(raw) } catch { /* one bad entry does not take the others down */ }\n }\n }\n return {\n permissions: isMode(value.permissions) ? value.permissions : DEFAULT_PREFERENCES.permissions,\n defaultAgent: typeof value.defaultAgent === 'string' && value.defaultAgent !== '' ? value.defaultAgent : DEFAULT_PREFERENCES.defaultAgent,\n overrides,\n statusHooks: typeof value.statusHooks === 'boolean' ? value.statusHooks : DEFAULT_PREFERENCES.statusHooks,\n }\n}\n\n/** One change from Settings. `command: null` clears the override. */\nexport interface PreferencesPatch {\n readonly permissions?: PermissionMode\n readonly defaultAgent?: DefaultAgent\n readonly statusHooks?: boolean\n readonly agent?: {\n readonly id: string\n readonly enabled?: boolean\n readonly command?: string | null\n readonly args?: readonly string[]\n }\n}\n\n/** @param value - untrusted JSON from the route. @throws AgentDefinitionError with a message fit to show. */\nexport function parsePreferencesPatch(value: unknown): PreferencesPatch {\n if (!isRecord(value)) throw new AgentDefinitionError('invalid agent settings request')\n const extra = Object.keys(value).find(key => key !== 'permissions' && key !== 'defaultAgent' && key !== 'agent' && key !== 'statusHooks')\n if (extra !== undefined) throw new AgentDefinitionError(`unknown field: ${extra}`)\n const patch: { permissions?: PermissionMode; defaultAgent?: DefaultAgent; statusHooks?: boolean; agent?: NonNullable<PreferencesPatch['agent']> } = {}\n if (value.permissions !== undefined) {\n if (!isMode(value.permissions)) throw new AgentDefinitionError('permissions is yolo or manual')\n patch.permissions = value.permissions\n }\n if (value.defaultAgent !== undefined) {\n if (typeof value.defaultAgent !== 'string' || value.defaultAgent === '' || value.defaultAgent.length > 40) throw new AgentDefinitionError('defaultAgent is auto, none or an agent id')\n patch.defaultAgent = value.defaultAgent\n }\n if (value.statusHooks !== undefined) {\n if (typeof value.statusHooks !== 'boolean') throw new AgentDefinitionError('statusHooks is true or false')\n patch.statusHooks = value.statusHooks\n }\n if (value.agent !== undefined) {\n const agent = value.agent\n if (!isRecord(agent) || typeof agent.id !== 'string' || agent.id === '' || agent.id.length > 40) throw new AgentDefinitionError('an agent change needs an id')\n const unknown = Object.keys(agent).find(key => !['id', 'enabled', 'command', 'args'].includes(key))\n if (unknown !== undefined) throw new AgentDefinitionError(`unknown field: ${unknown}`)\n if (agent.enabled !== undefined && typeof agent.enabled !== 'boolean') throw new AgentDefinitionError('enabled is true or false')\n patch.agent = {\n id: agent.id,\n ...(agent.enabled === undefined ? {} : { enabled: agent.enabled }),\n ...(agent.command === undefined ? {} : { command: agent.command === null ? null : parseAgentCommand(agent.command) }),\n ...(agent.args === undefined ? {} : { args: parseAgentArgs(agent.args) }),\n }\n }\n return patch\n}\n\n/**\n * @param current - the preferences now.\n * @param patch - one validated change.\n * @param isAgent - whether an id names an agent the Host knows (built in or custom).\n * @throws AgentDefinitionError for an unknown agent.\n */\nexport function applyPreferencesPatch(current: AgentPreferences, patch: PreferencesPatch, isAgent: (id: string) => boolean): AgentPreferences {\n let next = current\n if (patch.permissions !== undefined) next = { ...next, permissions: patch.permissions }\n if (patch.statusHooks !== undefined) next = { ...next, statusHooks: patch.statusHooks }\n if (patch.defaultAgent !== undefined) {\n if (patch.defaultAgent !== 'auto' && patch.defaultAgent !== 'none' && !isAgent(patch.defaultAgent)) throw new AgentDefinitionError(`\"${patch.defaultAgent}\" is not an agent`)\n next = { ...next, defaultAgent: patch.defaultAgent }\n }\n if (patch.agent !== undefined) {\n const { id, enabled, command, args } = patch.agent\n if (!isAgent(id)) throw new AgentDefinitionError(`\"${id}\" is not an agent`)\n const before = next.overrides[id] ?? DEFAULT_OVERRIDE\n const { command: oldCommand, ...rest } = before\n const commandPart = command === undefined ? (oldCommand === undefined ? {} : { command: oldCommand }) : command === null ? {} : { command }\n next = { ...next, overrides: { ...next.overrides, [id]: { ...rest, enabled: enabled ?? before.enabled, args: args ?? before.args, ...commandPart } } }\n }\n return next\n}\n","/** The custom agent catalog and the agent settings, for the app's own page only. */\n\nimport { Acryl } from '@acryldev/blends'\nimport { failure, isRecord, jsonBody, ownPage, readJson, type ReportError } from '../private-route.ts'\nimport type { AgentCatalog } from './catalog.ts'\nimport { WORKSPACE_AGENT_SETTINGS_PATH, WORKSPACE_AGENTS_PATH, WORKSPACE_AGENTS_REMOVE_PATH } from './contract.ts'\nimport { AgentDefinitionError } from './definition.ts'\nimport { parsePreferencesPatch } from './preferences.ts'\nimport type { AgentSettings } from './settings.ts'\n\n/**\n * 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`\n * `{ id }` (idempotent); GET `agents/settings` (with a fresh check of which programs are installed) and POST one change, answered with the whole view.\n */\nexport function agentRoutes(catalog: AgentCatalog, settings: AgentSettings, reportError: ReportError): Acryl {\n return new Acryl()\n .get(WORKSPACE_AGENTS_PATH, ownPage, c => c.json({ agents: catalog.list() }))\n .post(WORKSPACE_AGENTS_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (!isRecord(body) || Object.keys(body).length !== 1 || !('agent' in body)) return c.json(failure('invalid agent request'), 400)\n try {\n await catalog.add(body.agent)\n return c.json({ agents: catalog.list() })\n } catch (cause) {\n if (cause instanceof AgentDefinitionError) return c.json(failure(cause.message), 400)\n reportError('add agent', cause)\n return c.json(failure('the agent could not be saved'), 500)\n }\n })\n .post(WORKSPACE_AGENTS_REMOVE_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (!isRecord(body) || Object.keys(body).length !== 1 || typeof body.id !== 'string') return c.json(failure('invalid agent request'), 400)\n try {\n await catalog.remove(body.id)\n return c.json({ agents: catalog.list() })\n } catch (cause) {\n reportError('remove agent', cause)\n return c.json(failure('the agent could not be removed'), 500)\n }\n })\n .get(WORKSPACE_AGENT_SETTINGS_PATH, ownPage, async c => c.json(await settings.view()))\n .post(WORKSPACE_AGENT_SETTINGS_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n try {\n return c.json(await settings.apply(parsePreferencesPatch(body)))\n } catch (cause) {\n if (cause instanceof AgentDefinitionError) return c.json(failure(cause.message), 400)\n reportError('save agent settings', cause)\n return c.json(failure('the settings could not be saved'), 500)\n }\n })\n}\n","/**\n * The user's custom agents: the use cases (list, add, remove, resolve) over a store.\n *\n * The store and the check that a command really exists are ports, so these rules run with no disk and no\n * process table. The catalog is the only source of custom agents; a worktree can never contribute one.\n */\n\nimport type { AgentLaunch } from './launch.ts'\nimport { AgentDefinitionError, MAX_CUSTOM_AGENTS, parseCustomAgent, type CustomAgent } from './definition.ts'\n\n/** Where the definitions are kept (a file in the user's own ACRYL home). */\nexport interface CatalogStore {\n /** @returns the stored JSON text, or null when nothing was stored yet. */\n read(): Promise<string | null>\n write(text: string): Promise<void>\n}\n\n/** Answers whether a command names a real executable on this machine (it may wait for the login shell's search path). */\nexport type CommandExists = (command: string) => Promise<boolean>\n\nexport class AgentCatalog {\n private agents: readonly CustomAgent[] = []\n private loaded = false\n\n constructor(private readonly store: CatalogStore, private readonly commandExists: CommandExists) {}\n\n /** Read the stored definitions; a damaged file is ignored (built-in agents keep working). */\n async load(): Promise<void> {\n this.loaded = true\n try {\n const text = await this.store.read()\n const parsed: unknown = text === null ? [] : JSON.parse(text)\n if (!Array.isArray(parsed)) return\n const good: CustomAgent[] = []\n for (const item of parsed) {\n try {\n const agent = parseCustomAgent(item)\n if (!good.some(existing => existing.id === agent.id)) good.push(agent)\n } catch {\n // One bad entry does not take the others down.\n }\n }\n this.agents = good.slice(0, MAX_CUSTOM_AGENTS)\n } catch {\n this.agents = []\n }\n }\n\n list(): readonly CustomAgent[] {\n return this.agents\n }\n\n /** @returns what to launch for a custom agent id, or undefined when the id is not one. */\n resolve(id: string): AgentLaunch | undefined {\n const agent = this.agents.find(candidate => candidate.id === id)\n return agent === undefined ? undefined : { command: agent.command, args: agent.args }\n }\n\n /** @throws AgentDefinitionError for an invalid, duplicate, or unrunnable definition. */\n async add(raw: unknown): Promise<CustomAgent> {\n if (!this.loaded) await this.load()\n const agent = parseCustomAgent(raw)\n if (this.agents.some(existing => existing.id === agent.id)) throw new AgentDefinitionError(`\"${agent.id}\" already exists`)\n if (this.agents.length >= MAX_CUSTOM_AGENTS) throw new AgentDefinitionError(`at most ${String(MAX_CUSTOM_AGENTS)} custom agents`)\n if (!await this.commandExists(agent.command)) throw new AgentDefinitionError(`\"${agent.command}\" was not found on this machine`)\n const next = [...this.agents, agent]\n await this.store.write(JSON.stringify(next, null, 2))\n this.agents = next\n return agent\n }\n\n /** Idempotent. */\n async remove(id: string): Promise<void> {\n if (!this.loaded) await this.load()\n if (!this.agents.some(agent => agent.id === id)) return\n const next = this.agents.filter(agent => agent.id !== id)\n await this.store.write(JSON.stringify(next, null, 2))\n this.agents = next\n }\n}\n","/** The catalog's file in the user's ACRYL home, written atomically. */\n\nimport { randomBytes } from 'node:crypto'\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport type { CatalogStore } from './catalog.ts'\n\n/** The catalog file in the app's ACRYL home (from the `appInstance` service: this package never looks up a home itself). */\nexport function agentsFile(appHome: string): string {\n return join(appHome, 'workspace', 'agents.json')\n}\n\n/** The preferences file, next to the catalog. */\nexport function agentSettingsFile(appHome: string): string {\n return join(dirname(agentsFile(appHome)), 'agent-settings.json')\n}\n\nexport function createFileCatalogStore(path: string): CatalogStore {\n return {\n async read() {\n try {\n return await readFile(path, 'utf8')\n } catch (cause) {\n if (typeof cause === 'object' && cause !== null && 'code' in cause && cause.code === 'ENOENT') return null\n throw cause\n }\n },\n async write(text) {\n await mkdir(dirname(path), { recursive: true })\n const temp = `${path}.${randomBytes(6).toString('hex')}.tmp`\n await writeFile(temp, text, { encoding: 'utf8', mode: 0o600 })\n await rename(temp, path)\n },\n }\n}\n","/**\n * Agent settings: the preferences file plus everything a launch and Settings > Agents need from it.\n *\n * It answers three questions: what does this id run (`resolve`), what does Settings show (`view`), and what\n * changed (`apply`). The file and the \"is this program installed\" check are ports, so all of it runs in a test\n * with no disk and no process table. A custom agent is still defined only in the catalog; settings never adds one.\n */\n\nimport type { AgentCatalog, CatalogStore, CommandExists } from './catalog.ts'\nimport type { AgentSettingsEntry, AgentSettingsView } from './contract.ts'\nimport { DEFAULT_OVERRIDE, describeLaunch, planKnownLaunch, type AgentLaunch } from './launch.ts'\nimport { KNOWN_AGENTS, knownAgent } from './known-agents.ts'\nimport { applyPreferencesPatch, DEFAULT_PREFERENCES, parseStoredPreferences, type AgentPreferences, type PreferencesPatch } from './preferences.ts'\n\nexport class AgentSettings {\n private preferences: AgentPreferences = DEFAULT_PREFERENCES\n private loaded = false\n\n constructor(\n private readonly store: CatalogStore,\n private readonly catalog: Pick<AgentCatalog, 'list' | 'resolve'>,\n private readonly commandExists: CommandExists,\n ) {}\n\n /** Read the stored preferences; a damaged file gives the defaults. */\n async load(): Promise<void> {\n this.loaded = true\n try {\n const text = await this.store.read()\n this.preferences = text === null ? DEFAULT_PREFERENCES : parseStoredPreferences(JSON.parse(text))\n } catch {\n this.preferences = DEFAULT_PREFERENCES\n }\n }\n\n /** @returns what to run for an agent id (a known agent with the user's settings, or a custom agent), or undefined. */\n resolve(id: string): AgentLaunch | undefined {\n const known = knownAgent(id)\n if (known !== undefined) return planKnownLaunch(known, this.preferences.overrides[id] ?? DEFAULT_OVERRIDE, this.preferences.permissions, this.preferences.statusHooks)\n return this.catalog.resolve(id)\n }\n\n /** @throws AgentDefinitionError for an unknown agent or an invalid value. */\n async apply(patch: PreferencesPatch): Promise<AgentSettingsView> {\n if (!this.loaded) await this.load()\n const next = applyPreferencesPatch(this.preferences, patch, id => this.isAgent(id))\n await this.store.write(JSON.stringify(next, null, 2))\n this.preferences = next\n return await this.view()\n }\n\n /** The list Settings shows: known agents first, then the user's own. Detection is fresh on every call. */\n async view(): Promise<AgentSettingsView> {\n const { permissions, overrides, statusHooks } = this.preferences\n const known: AgentSettingsEntry[] = await Promise.all(KNOWN_AGENTS.map(async (agent) => {\n const override = overrides[agent.id] ?? DEFAULT_OVERRIDE\n const launch = planKnownLaunch(agent, override, permissions)\n return {\n id: agent.id,\n label: agent.label,\n kind: 'known',\n homepageUrl: agent.homepageUrl,\n defaultCommand: agent.command,\n command: launch.command,\n args: override.args,\n permissionArgs: permissions === 'yolo' ? agent.yoloArgs : [],\n permissionEnv: permissions === 'yolo' ? agent.yoloEnv ?? {} : {},\n enabled: override.enabled,\n installed: await this.commandExists(launch.command),\n preview: describeLaunch(launch),\n badge: null,\n }\n }))\n const custom: AgentSettingsEntry[] = await Promise.all(this.catalog.list().map(async agent => ({\n id: agent.id,\n label: agent.label,\n kind: 'custom',\n homepageUrl: null,\n defaultCommand: agent.command,\n command: agent.command,\n args: agent.args,\n permissionArgs: [],\n permissionEnv: {},\n enabled: (overrides[agent.id] ?? DEFAULT_OVERRIDE).enabled,\n installed: await this.commandExists(agent.command),\n preview: describeLaunch({ command: agent.command, args: agent.args }),\n badge: agent.badge,\n })))\n const agents = [...known, ...custom]\n // A default that no longer names an agent (a removed custom agent) reads as automatic.\n const stored = this.preferences.defaultAgent\n const defaultAgent = stored === 'auto' || stored === 'none' || agents.some(entry => entry.id === stored) ? stored : 'auto'\n return { permissions, defaultAgent, statusHooks, agents }\n }\n\n private isAgent(id: string): boolean {\n return knownAgent(id) !== undefined || this.catalog.list().some(agent => agent.id === id)\n }\n}\n","/**\n * What a terminal agent is doing right now, as the agent itself reports it (spec 040 T127).\n *\n * Reading this off the screen would be guessing, so the agents that support hooks tell ACRYL instead: Claude Code\n * runs a small command on \"prompt submitted\", \"tool finished\", \"needs you\" and \"turn finished\", and that command\n * posts the state here. The store keeps the latest state per terminal and only ever answers for terminals the Host\n * still has.\n */\n\n/** GET from the page: every live terminal's status. POST from an agent's hook: one report. */\nexport const WORKSPACE_AGENT_STATUS_PATH = '/api/acryl-workspace/agent-status'\n\nexport const AGENT_STATES = ['working', 'waiting', 'done'] as const\n/** `working`: busy. `waiting`: it needs you (a permission, a question). `done`: it finished its turn. */\nexport type AgentState = (typeof AGENT_STATES)[number]\n\nexport interface AgentStatus {\n readonly terminalId: string\n readonly state: AgentState\n /** Milliseconds since the epoch when it was reported. */\n readonly at: number\n}\n\nexport class AgentStatusError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'AgentStatusError'\n }\n}\n\nconst isState = (value: unknown): value is AgentState => (AGENT_STATES as readonly unknown[]).includes(value)\n\n/** @param body - untrusted JSON from a hook. @throws AgentStatusError. */\nexport function parseStatusReport(body: unknown): { readonly terminal: string; readonly state: AgentState } {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) throw new AgentStatusError('a report is an object')\n const record = body as Record<string, unknown>\n const extra = Object.keys(record).find(key => key !== 'terminal' && key !== 'state')\n if (extra !== undefined) throw new AgentStatusError(`unknown field: ${extra}`)\n const { terminal, state } = record\n if (typeof terminal !== 'string' || terminal.length === 0 || terminal.length > 80) throw new AgentStatusError('terminal must be a terminal id')\n if (!isState(state)) throw new AgentStatusError('state is working, waiting or done')\n return { terminal, state }\n}\n\nexport class AgentStatusStore {\n private readonly statuses = new Map<string, AgentStatus>()\n\n /** @param isLive - whether the Host still has a terminal with this id. @param now - the clock. */\n constructor(private readonly isLive: (terminalId: string) => boolean, private readonly now: () => number = Date.now) {}\n\n /** @returns false when no such terminal exists (a stale or forged report is ignored). */\n report(terminalId: string, state: AgentState): boolean {\n if (!this.isLive(terminalId)) return false\n this.statuses.set(terminalId, { terminalId, state, at: this.now() })\n return true\n }\n\n /** The latest status of every terminal that still exists; the others are forgotten here. */\n list(): readonly AgentStatus[] {\n for (const id of [...this.statuses.keys()]) {\n if (!this.isLive(id)) this.statuses.delete(id)\n }\n return [...this.statuses.values()]\n }\n}\n","/** The status route: agents POST what they are doing (bearer token, loopback only); the page GETs the list. */\n\nimport { Acryl } from '@acryldev/blends'\nimport { bearerAuth } from '@acryldev/blends/bearer-auth'\nimport { loopbackOnly } from '@acryldev/blends/loopback-only'\nimport { INVALID_JSON, failure, jsonBody, ownPage, readJson, type ReportError } from '../../private-route.ts'\nimport { AgentStatusError, WORKSPACE_AGENT_STATUS_PATH, parseStatusReport, type AgentStatusStore } from './agent-status.ts'\n\n/**\n * GET (from the app's own page): every live terminal's latest status.\n * POST (from an agent's hook, a program and not a page): `{ terminal, state }` with `Authorization: Bearer <token>`. The token is known only to\n * terminals ACRYL started for agents, and the request must come from this machine to the app's own loopback address.\n */\nexport function agentStatusRoutes(token: string, store: AgentStatusStore, reportError: ReportError): Acryl {\n const fromAgent = [\n loopbackOnly({ mutations: 'none', hostnames: ['127.0.0.1'] }),\n // A missing or wrong token is 401 with `WWW-Authenticate`, a malformed header 400; the hook ignores the answer either way.\n bearerAuth({\n token,\n noAuthenticationHeader: { message: failure('a bearer token is required') },\n invalidAuthenticationHeader: { message: failure('invalid authorization header') },\n invalidToken: { message: failure('wrong token') },\n }),\n ] as const\n return new Acryl()\n .get(WORKSPACE_AGENT_STATUS_PATH, ownPage, c => c.json({ statuses: store.list() }))\n .post(WORKSPACE_AGENT_STATUS_PATH, ...fromAgent, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (body === INVALID_JSON) return c.json(failure('invalid report'), 400)\n try {\n const report = parseStatusReport(body)\n // An unknown terminal is not an error for the hook: the agent may have outlived its terminal.\n return c.json({ ok: store.report(report.terminal, report.state) })\n } catch (cause) {\n if (cause instanceof AgentStatusError) return c.json(failure(cause.message), 400)\n reportError('record agent status', cause)\n return c.json(failure('the report could not be recorded'), 500)\n }\n })\n}\n","/** What the Host composition can do for the page, so the page offers only what will work. */\n\nexport const WORKSPACE_CAPABILITIES_PATH = '/api/acryl-workspace/capabilities'\n\nexport interface WorkspaceCapabilities {\n /** The DeepSeek Harness chat (its agent) is running, so \"AcrylDSH Chat\" tabs can be opened and sent from. */\n readonly chat: boolean\n /**\n * Where the Host serves this app's own page, as a path on the frame's origin (`/app` in the ACRYL frame). Present only when the Host hosts an\n * app: the frame then opens that page in a browser tile on first run, instead of an empty canvas.\n */\n readonly appPage?: string\n /** The app's folder: the worktree the frame opens on first run, so the app and its chats share one tab set. */\n readonly appRoot?: string\n /** The app's name, used as the tile's title (`my-app`), instead of the address's host. */\n readonly appName?: string\n}\n\n/** @throws when the body is not exactly the capabilities this page understands. */\nexport function parseWorkspaceCapabilities(value: unknown): WorkspaceCapabilities {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('capabilities must be an object')\n const record = value as Record<string, unknown>\n if (typeof record.chat !== 'boolean') throw new Error('capabilities.chat must be true or false')\n const appPage = record.appPage\n if (appPage !== undefined && (typeof appPage !== 'string' || !appPage.startsWith('/'))) throw new Error('capabilities.appPage must be an absolute path')\n const appRoot = record.appRoot\n if (appRoot !== undefined && (typeof appRoot !== 'string' || appRoot.length === 0)) throw new Error('capabilities.appRoot must be a non-empty path')\n const appName = record.appName\n if (appName !== undefined && (typeof appName !== 'string' || appName.length === 0)) throw new Error('capabilities.appName must be a non-empty name')\n return {\n chat: record.chat,\n ...(appPage === undefined ? {} : { appPage }),\n ...(appRoot === undefined ? {} : { appRoot }),\n ...(appName === undefined ? {} : { appName }),\n }\n}\n","/** What the running composition offers, for the app's own page only. */\n\nimport { Acryl } from '@acryldev/blends'\nimport { ownPage } from '../private-route.ts'\nimport { WORKSPACE_CAPABILITIES_PATH, type WorkspaceCapabilities } from './contract.ts'\n\n/**\n * 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\n * reported as it is now: the truth is the composition, not a flag copied from a Blueprint.\n */\nexport function capabilityRoutes(read: () => WorkspaceCapabilities): Acryl {\n return new Acryl().get(WORKSPACE_CAPABILITIES_PATH, ownPage, c => c.json(read()))\n}\n","/** Loopback routes and JSON shapes for browsing, reading and saving files inside a git worktree. */\n\nexport const WORKSPACE_FILES_TREE_PATH = '/api/acryl-workspace/files/tree'\nexport const WORKSPACE_FILES_READ_PATH = '/api/acryl-workspace/files/read'\nexport const WORKSPACE_FILES_WRITE_PATH = '/api/acryl-workspace/files/write'\nexport const WORKSPACE_FILES_ENTRY_PATH = '/api/acryl-workspace/files/entry'\n\n/** The largest file the editor opens or saves. */\nexport const MAX_EDITABLE_BYTES = 2 * 1024 * 1024\n\nexport type FileEntryKind = 'file' | 'dir'\n\nexport interface FileEntry {\n /** Base name, without any directory part. */\n readonly name: string\n readonly kind: FileEntryKind\n /** Git ignores it (build output, dependencies, local settings); the tree shows it dimmed. */\n readonly ignored?: boolean\n}\n\n/** One directory of a worktree. */\nexport interface FilesTreeView {\n /** Absolute worktree path. */\n readonly path: string\n /** Directory relative to the worktree, `''` for its root. */\n readonly dir: string\n /** Directories first, then files, each alphabetical. */\n readonly entries: readonly FileEntry[]\n /** True when the directory had more entries than the cap. */\n readonly truncated: boolean\n}\n\nexport interface FileContentView {\n readonly path: string\n readonly file: string\n /** UTF-8 text; empty when `binary`. */\n readonly content: string\n readonly binary: boolean\n readonly size: number\n /** Modification time on disk, sent back when saving to detect an outside change. */\n readonly mtimeMs: number\n}\n\nexport interface FileSavedView {\n readonly path: string\n readonly file: string\n readonly size: number\n readonly mtimeMs: number\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isEntry(value: unknown): value is FileEntry {\n return isRecord(value) && typeof value.name === 'string' && (value.kind === 'file' || value.kind === 'dir')\n && (value.ignored === undefined || typeof value.ignored === 'boolean')\n}\n\n/** @param value - unknown JSON from the tree route. */\nexport function parseFilesTreeView(value: unknown): FilesTreeView {\n if (!isRecord(value) || typeof value.path !== 'string' || typeof value.dir !== 'string'\n || typeof value.truncated !== 'boolean' || !Array.isArray(value.entries) || !value.entries.every(isEntry)) {\n throw new Error('invalid files tree response')\n }\n return { path: value.path, dir: value.dir, entries: value.entries, truncated: value.truncated }\n}\n\n/** @param value - unknown JSON from the read route. */\nexport function parseFileContentView(value: unknown): FileContentView {\n if (!isRecord(value) || typeof value.path !== 'string' || typeof value.file !== 'string'\n || typeof value.content !== 'string' || typeof value.binary !== 'boolean'\n || typeof value.size !== 'number' || typeof value.mtimeMs !== 'number') {\n throw new Error('invalid file response')\n }\n return { path: value.path, file: value.file, content: value.content, binary: value.binary, size: value.size, mtimeMs: value.mtimeMs }\n}\n\n/** @param value - unknown JSON from the write route. */\nexport function parseFileSavedView(value: unknown): FileSavedView {\n if (!isRecord(value) || typeof value.path !== 'string' || typeof value.file !== 'string'\n || typeof value.size !== 'number' || typeof value.mtimeMs !== 'number') {\n throw new Error('invalid file save response')\n }\n return { path: value.path, file: value.file, size: value.size, mtimeMs: value.mtimeMs }\n}\n\n/**\n * One structural change to a worktree's files. Deliberately small: create a file or an empty folder,\n * rename or move an entry, delete a file or an empty folder. Nothing overwrites, nothing recurses.\n */\nexport type FileEntryChange =\n | { readonly op: 'create'; readonly kind: FileEntryKind; readonly file: string }\n | { readonly op: 'rename'; readonly file: string; readonly to: string }\n | { readonly op: 'delete'; readonly file: string }\n\n/** The result of a structural change: what now exists (null after a delete). */\nexport interface FileEntryChangedView {\n readonly path: string\n readonly op: FileEntryChange['op']\n readonly file: string | null\n}\n\n/** @param value - unknown JSON from the entry route. */\nexport function parseFileEntryChangedView(value: unknown): FileEntryChangedView {\n if (!isRecord(value) || typeof value.path !== 'string'\n || (value.op !== 'create' && value.op !== 'rename' && value.op !== 'delete')\n || (value.file !== null && typeof value.file !== 'string')) {\n throw new Error('invalid file change response')\n }\n return { path: value.path, op: value.op, file: value.file }\n}\n\n/** Validate an untrusted request body into a change, or null when it is not one. */\nexport function parseFileEntryChange(value: unknown): FileEntryChange | null {\n if (!isRecord(value)) return null\n const keys = Object.keys(value).filter(key => key !== 'path').sort().join(',')\n if (value.op === 'create' && keys === 'file,kind,op' && typeof value.file === 'string' && (value.kind === 'file' || value.kind === 'dir')) {\n return { op: 'create', kind: value.kind, file: value.file }\n }\n if (value.op === 'rename' && keys === 'file,op,to' && typeof value.file === 'string' && typeof value.to === 'string') {\n return { op: 'rename', file: value.file, to: value.to }\n }\n if (value.op === 'delete' && keys === 'file,op' && typeof value.file === 'string') return { op: 'delete', file: value.file }\n return null\n}\n","/**\n * Browsing, reading and saving files inside one git worktree.\n *\n * This is the only part of the package that writes user files, so every path is confined: the worktree\n * must be the root of a git worktree (checked by the injected resolver), a file path is relative and\n * free of `..` and `.git` segments, and the real path (after symlinks) must stay inside the worktree.\n * Saves are atomic (temp file then rename) and refuse to overwrite a file that changed on disk since it\n * was read.\n */\n\nimport { randomBytes } from 'node:crypto'\nimport { chmod, lstat, mkdir, readdir, readFile, realpath, rename, rmdir, stat, unlink, writeFile } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, join, sep } from 'node:path'\nimport {\n MAX_EDITABLE_BYTES,\n type FileContentView,\n type FileEntryChange,\n type FileEntryChangedView,\n type FileEntry,\n type FileSavedView,\n type FilesTreeView,\n} from './contract.ts'\n\nexport type WorkspaceFilesErrorKind = 'invalid' | 'not-found' | 'conflict' | 'too-large' | 'failed'\n\nexport class WorkspaceFilesError extends Error {\n constructor(message: string, readonly kind: WorkspaceFilesErrorKind) {\n super(message)\n this.name = 'WorkspaceFilesError'\n }\n}\n\nconst MAX_ENTRIES = 3000\nconst BINARY_SNIFF_BYTES = 8192\n\nexport interface WorkspaceFilesOptions {\n /** Validates that a path is the root of a git worktree and returns its real path. */\n readonly resolveWorktree: (path: string) => Promise<string>\n /** Which of the given root-relative paths git ignores (a directory ends in `/`); without it nothing is marked. */\n readonly ignored?: (root: string, paths: readonly string[]) => Promise<ReadonlySet<string>>\n}\n\nexport class WorkspaceFiles {\n constructor(private readonly options: WorkspaceFilesOptions) {}\n\n async tree(worktree: string, dir: string): Promise<FilesTreeView> {\n const root = await this.options.resolveWorktree(worktree)\n const target = dir === '' ? root : await confine(root, dir)\n let dirents\n try {\n if (!(await stat(target)).isDirectory()) throw new Error('not a directory')\n dirents = await readdir(target, { withFileTypes: true })\n } catch {\n throw new WorkspaceFilesError('that directory cannot be read', 'not-found')\n }\n const entries: FileEntry[] = []\n for (const dirent of dirents) {\n if (dirent.name === '.git') continue\n if (dirent.isDirectory()) entries.push({ name: dirent.name, kind: 'dir' })\n else if (dirent.isFile()) entries.push({ name: dirent.name, kind: 'file' })\n else if (dirent.isSymbolicLink()) {\n const kind = await symlinkKind(root, join(target, dirent.name))\n if (kind !== null) entries.push({ name: dirent.name, kind })\n }\n }\n entries.sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name, 'en', { sensitivity: 'base' }) : a.kind === 'dir' ? -1 : 1))\n const shown = entries.slice(0, MAX_ENTRIES)\n const pathOf = (entry: FileEntry): string => `${dir === '' ? '' : `${dir}/`}${entry.name}${entry.kind === 'dir' ? '/' : ''}`\n const ignored = this.options.ignored === undefined ? new Set<string>() : await this.options.ignored(root, shown.map(pathOf))\n return {\n path: root,\n dir,\n entries: ignored.size === 0 ? shown : shown.map(entry => (ignored.has(pathOf(entry)) ? { ...entry, ignored: true } : entry)),\n truncated: entries.length > MAX_ENTRIES,\n }\n }\n\n async read(worktree: string, file: string): Promise<FileContentView> {\n const root = await this.options.resolveWorktree(worktree)\n const real = await confine(root, file)\n const info = await statFile(real)\n if (info.size > MAX_EDITABLE_BYTES) throw new WorkspaceFilesError('the file is too large to edit here', 'too-large')\n const buffer = await readFile(real)\n const binary = buffer.subarray(0, BINARY_SNIFF_BYTES).includes(0)\n return {\n path: root,\n file,\n content: binary ? '' : buffer.toString('utf8'),\n binary,\n size: info.size,\n mtimeMs: info.mtimeMs,\n }\n }\n\n /**\n * Replace an existing file's text.\n * @param expectedMtimeMs - the `mtimeMs` from the read this edit is based on.\n * @throws WorkspaceFilesError `conflict` when the file changed on disk since that read.\n */\n async write(worktree: string, file: string, content: string, expectedMtimeMs: number): Promise<FileSavedView> {\n const root = await this.options.resolveWorktree(worktree)\n const real = await confine(root, file)\n const info = await statFile(real)\n if (Buffer.byteLength(content, 'utf8') > MAX_EDITABLE_BYTES) throw new WorkspaceFilesError('the text is too large to save here', 'too-large')\n if (info.mtimeMs !== expectedMtimeMs) {\n throw new WorkspaceFilesError('the file changed on disk since you opened it', 'conflict')\n }\n const temp = join(dirname(real), `.${basename(real)}.acryl-${randomBytes(6).toString('hex')}.tmp`)\n try {\n await writeFile(temp, content, { encoding: 'utf8', flag: 'wx' })\n await chmod(temp, info.mode & 0o7777)\n await rename(temp, real)\n } catch {\n await unlink(temp).catch(() => {})\n throw new WorkspaceFilesError('the file could not be saved', 'failed')\n }\n const saved = await stat(real)\n return { path: root, file, size: saved.size, mtimeMs: saved.mtimeMs }\n }\n\n /**\n * Create, rename or delete one entry. Never overwrites, never recurses: a delete removes a file or an\n * empty folder only, and a create or rename refuses a name that is already taken.\n */\n async change(worktree: string, change: FileEntryChange): Promise<FileEntryChangedView> {\n const root = await this.options.resolveWorktree(worktree)\n if (change.op === 'create') {\n const target = await confineNew(root, change.file)\n try {\n if (change.kind === 'dir') await mkdir(target)\n else await writeFile(target, '', { flag: 'wx' })\n } catch {\n throw new WorkspaceFilesError('that could not be created', 'failed')\n }\n return { path: root, op: 'create', file: change.file }\n }\n if (change.op === 'rename') {\n const source = await confineEntry(root, change.file)\n const target = await confineNew(root, change.to)\n try {\n await rename(source, target)\n } catch {\n throw new WorkspaceFilesError('that could not be renamed', 'failed')\n }\n return { path: root, op: 'rename', file: change.to }\n }\n const target = await confineEntry(root, change.file)\n try {\n if ((await lstat(target)).isDirectory()) await rmdir(target)\n else await unlink(target)\n } catch (cause) {\n const code = typeof cause === 'object' && cause !== null && 'code' in cause ? cause.code : undefined\n if (code === 'ENOTEMPTY' || code === 'EEXIST') throw new WorkspaceFilesError('only an empty folder can be deleted', 'conflict')\n throw new WorkspaceFilesError('that could not be deleted', 'failed')\n }\n return { path: root, op: 'delete', file: null }\n }\n}\n\nasync function statFile(real: string): Promise<{ size: number; mtimeMs: number; mode: number }> {\n try {\n const info = await stat(real)\n if (!info.isFile()) throw new Error('not a file')\n return { size: info.size, mtimeMs: info.mtimeMs, mode: info.mode }\n } catch {\n throw new WorkspaceFilesError('that file does not exist', 'not-found')\n }\n}\n\n/** A symlink is listed only when it points at a file or directory inside the worktree. */\nasync function symlinkKind(root: string, path: string): Promise<'file' | 'dir' | null> {\n try {\n const real = await realpath(path)\n if (!isInside(root, real)) return null\n const info = await stat(real)\n return info.isDirectory() ? 'dir' : info.isFile() ? 'file' : null\n } catch {\n return null\n }\n}\n\nfunction isInside(root: string, real: string): boolean {\n return real === root || real.startsWith(root.endsWith(sep) ? root : root + sep)\n}\n\n/**\n * Turn a worktree-relative path into a real path that is guaranteed to be inside `root`.\n * Rejects absolute paths, NUL, `..` and `.git` segments, and symlinks that leave the worktree.\n */\nexport async function confine(root: string, relative: string): Promise<string> {\n if (typeof relative !== 'string' || relative.length === 0 || relative.includes('\\0') || isAbsolute(relative)) {\n throw new WorkspaceFilesError('path must be relative to the worktree', 'invalid')\n }\n const segments = relative.split(/[\\\\/]+/).filter(segment => segment.length > 0)\n if (segments.length === 0 || segments.some(segment => segment === '..' || segment.toLowerCase() === '.git')) {\n throw new WorkspaceFilesError('that path is not allowed', 'invalid')\n }\n let real: string\n try {\n real = await realpath(join(root, ...segments))\n } catch {\n throw new WorkspaceFilesError('that path does not exist', 'not-found')\n }\n if (!isInside(root, real)) throw new WorkspaceFilesError('that path leaves the worktree', 'invalid')\n return real\n}\n\nfunction segmentsOf(relative: string): string[] {\n if (typeof relative !== 'string' || relative.length === 0 || relative.includes('\\0') || isAbsolute(relative)) {\n throw new WorkspaceFilesError('path must be relative to the worktree', 'invalid')\n }\n const segments = relative.split(/[\\\\/]+/).filter(segment => segment.length > 0)\n if (segments.length === 0 || segments.some(segment => segment === '..' || segment === '.' || segment.toLowerCase() === '.git')) {\n throw new WorkspaceFilesError('that path is not allowed', 'invalid')\n }\n return segments\n}\n\n/**\n * The real path of an entry that will be created: its folder must exist inside the worktree and the name\n * must be free (a dangling symlink counts as taken).\n */\nexport async function confineNew(root: string, relative: string): Promise<string> {\n const segments = segmentsOf(relative)\n const name = segments[segments.length - 1] as string\n let parent: string\n try {\n parent = await realpath(join(root, ...segments.slice(0, -1)))\n } catch {\n throw new WorkspaceFilesError('the folder does not exist', 'not-found')\n }\n if (!isInside(root, parent)) throw new WorkspaceFilesError('that path leaves the worktree', 'invalid')\n const target = join(parent, name)\n try {\n await lstat(target)\n } catch {\n return target\n }\n throw new WorkspaceFilesError('something with that name already exists', 'conflict')\n}\n\n/** The path of an existing entry itself: a symlink is renamed or deleted as the link, never followed. */\nasync function confineEntry(root: string, relative: string): Promise<string> {\n const segments = segmentsOf(relative)\n const name = segments[segments.length - 1] as string\n let parent: string\n try {\n parent = await realpath(join(root, ...segments.slice(0, -1)))\n } catch {\n throw new WorkspaceFilesError('that path does not exist', 'not-found')\n }\n if (!isInside(root, parent)) throw new WorkspaceFilesError('that path leaves the worktree', 'invalid')\n const target = join(parent, name)\n try {\n await lstat(target)\n } catch {\n throw new WorkspaceFilesError('that path does not exist', 'not-found')\n }\n return target\n}\n","/** The worktree file routes: two reads and two changes, for the app's own page only. */\n\nimport { Acryl, type Context } from '@acryldev/blends'\nimport { INVALID_JSON, failure, isRecord, jsonBody, ownPage, readJson, type ReportError } from '../private-route.ts'\nimport {\n MAX_EDITABLE_BYTES,\n WORKSPACE_FILES_ENTRY_PATH,\n WORKSPACE_FILES_READ_PATH,\n WORKSPACE_FILES_TREE_PATH,\n WORKSPACE_FILES_WRITE_PATH,\n parseFileEntryChange,\n} from './contract.ts'\nimport { WorkspaceFilesError, type WorkspaceFiles } from './service.ts'\n\nconst STATUS = { invalid: 400, 'not-found': 404, conflict: 409, 'too-large': 413, failed: 500 } as const\n\nfunction required(c: Context, name: string): string {\n const value = c.req.query(name)\n if (value === undefined || value.length === 0) throw new WorkspaceFilesError(`missing ${name}`, 'invalid')\n return value\n}\n\n/**\n * GET `tree?path=<worktree>&dir=<relative, empty for the root>` and `read?path=&file=`; POST `write` `{ path, file, content, expectedMtimeMs }`\n * to replace an existing file's text and `entry` `{ path, op: 'create' | 'rename' | 'delete', file, kind?, to? }` for one structural change.\n */\nexport function filesRoutes(files: WorkspaceFiles, reportError: ReportError): Acryl {\n const answer = async (c: Context, operation: string, compute: () => Promise<object>): Promise<Response> => {\n try {\n return c.json(await compute())\n } catch (cause) {\n if (cause instanceof WorkspaceFilesError) return c.json(failure(cause.message), STATUS[cause.kind])\n reportError(operation, cause)\n return c.json(failure('file request failed'), 500)\n }\n }\n return new Acryl()\n .get(WORKSPACE_FILES_TREE_PATH, ownPage, c => answer(c, 'list files', () => files.tree(required(c, 'path'), c.req.query('dir') ?? '')))\n .get(WORKSPACE_FILES_READ_PATH, ownPage, c => answer(c, 'read file', () => files.read(required(c, 'path'), required(c, 'file'))))\n .post(WORKSPACE_FILES_WRITE_PATH, ownPage, jsonBody(MAX_EDITABLE_BYTES + 64 * 1024), async (c) => {\n const body = await readJson(c)\n if (body === INVALID_JSON || !isRecord(body)\n || typeof body.path !== 'string' || typeof body.file !== 'string'\n || typeof body.content !== 'string' || typeof body.expectedMtimeMs !== 'number'\n || Object.keys(body).length !== 4) {\n return c.json(failure('invalid save request'), 400)\n }\n const { path, file, content, expectedMtimeMs } = body\n return answer(c, 'save file', () => files.write(path, file, content, expectedMtimeMs))\n })\n .post(WORKSPACE_FILES_ENTRY_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n const change = body === INVALID_JSON ? null : parseFileEntryChange(body)\n if (change === null || !isRecord(body) || typeof body.path !== 'string') return c.json(failure('invalid change request'), 400)\n const { path } = body\n return answer(c, 'change file', () => files.change(path, change))\n })\n}\n","/**\n * Opens the operating system's own folder chooser and reports the folder picked. The Host serves a\n * loopback-only Web server (`@acryldev/workspace` refuses to start otherwise), so a dialog raised here is on\n * the same machine as the person using the page - the reason this is safe to offer at all, unlike a\n * chooser on a remote server nobody is sitting at.\n */\n\nimport { execFile } from 'node:child_process'\n\n/** Runs a program and resolves its stdout; rejects with `code` set to the exit code or 'ENOENT'. */\nexport type RunProgram = (file: string, args: readonly string[]) => Promise<string>\n\n/** No native chooser exists on this machine (no dialog program installed). */\nexport class FolderPickerUnavailableError extends Error {\n constructor() {\n super('no native folder chooser is available on this machine')\n this.name = 'FolderPickerUnavailableError'\n }\n}\n\nconst defaultRun: RunProgram = (file, args) => new Promise((resolve, reject) => {\n // No shell: the arguments are passed as an array, never interpolated into a command line.\n execFile(file, [...args], { maxBuffer: 1024 * 1024 }, (cause, stdout) => {\n if (cause === null) resolve(stdout)\n else reject(cause)\n })\n})\n\nfunction exitCode(cause: unknown): unknown {\n return typeof cause === 'object' && cause !== null && 'code' in cause ? (cause as { code?: unknown }).code : undefined\n}\n\n/** A trailing separator is dropped (the chooser adds one), except for a filesystem root. */\nexport function normalizePickedPath(raw: string): string | null {\n const text = raw.trim()\n if (text === '') return null\n const stripped = text.replace(/[\\\\/]+$/, '')\n return stripped === '' ? text : stripped\n}\n\nconst MAC_SCRIPT = [\n 'try',\n 'POSIX path of (choose folder with prompt \"Choose a workspace folder\")',\n 'on error number -128',\n 'return \"\"',\n 'end try',\n]\n\nconst WINDOWS_SCRIPT = [\n 'Add-Type -AssemblyName System.Windows.Forms',\n '$d = New-Object System.Windows.Forms.FolderBrowserDialog',\n '$d.Description = \"Choose a workspace folder\"',\n \"if ($d.ShowDialog() -eq 'OK') { Write-Output $d.SelectedPath }\",\n].join('; ')\n\n/**\n * @param platform - `process.platform`.\n * @param run - process runner; injected so the tests never open a dialog.\n * @returns the absolute path picked, or null when the chooser was cancelled.\n * @throws FolderPickerUnavailableError when this machine has no chooser program.\n */\nexport async function pickFolderNatively(platform: NodeJS.Platform, run: RunProgram = defaultRun): Promise<string | null> {\n if (platform === 'darwin') {\n return normalizePickedPath(await run('osascript', MAC_SCRIPT.flatMap(line => ['-e', line])))\n }\n if (platform === 'win32') {\n return normalizePickedPath(await run('powershell.exe', ['-NoProfile', '-STA', '-Command', WINDOWS_SCRIPT]))\n }\n // Linux and others: zenity, then kdialog. Cancelling either exits 1 with nothing on stdout.\n const candidates: ReadonlyArray<readonly [string, readonly string[]]> = [\n ['zenity', ['--file-selection', '--directory', '--title=Choose a workspace folder']],\n ['kdialog', ['--getexistingdirectory', '.', '--title', 'Choose a workspace folder']],\n ]\n for (const [file, args] of candidates) {\n try {\n return normalizePickedPath(await run(file, args))\n } catch (cause) {\n if (exitCode(cause) === 'ENOENT') continue\n return null // the person closed the dialog\n }\n }\n throw new FolderPickerUnavailableError()\n}\n\n/** One chooser at a time: a second request while one is open waits for that answer instead of stacking dialogs. */\nexport function singleFlight<T>(task: () => Promise<T>): () => Promise<T> {\n let inflight: Promise<T> | undefined\n return () => {\n inflight ??= task().finally(() => { inflight = undefined })\n return inflight\n }\n}\n","/** Same-origin route that opens the operating system's own folder chooser on the machine running the Host. */\nexport const WORKSPACE_PICK_FOLDER_PATH = '/api/acryl-workspace/pick-folder'\n\n/** What the chooser answered: the picked absolute path, or null when it was cancelled. */\nexport interface PickFolderView {\n readonly path: string | null\n}\n\n/** HTTP status the route uses when this machine has no native chooser (a headless Linux box, say). */\nexport const PICK_FOLDER_UNAVAILABLE_STATUS = 501\n\nexport function parsePickFolderView(value: unknown): PickFolderView {\n if (typeof value !== 'object' || value === null || !('path' in value)) throw new Error('invalid folder chooser response')\n const path = (value as { path?: unknown }).path\n if (path !== null && typeof path !== 'string') throw new Error('invalid folder chooser response')\n return { path }\n}\n","/** The native folder chooser, for the app's own page only. */\n\nimport { Acryl } from '@acryldev/blends'\nimport { failure, ownPage, type ReportError } from '../private-route.ts'\nimport { PICK_FOLDER_UNAVAILABLE_STATUS, WORKSPACE_PICK_FOLDER_PATH, type PickFolderView } from './contract.ts'\nimport { FolderPickerUnavailableError } from './picker.ts'\n\n/** POST: open the OS's chooser and answer the folder, or `null` when it was cancelled. */\nexport function pickFolderRoutes(pick: () => Promise<string | null>, reportError: ReportError): Acryl {\n return new Acryl()\n .post(WORKSPACE_PICK_FOLDER_PATH, ownPage, async (c) => {\n // It raises a window on the person's screen: a JSON request only, which a plain HTML form cannot send.\n if (c.req.header('content-type')?.split(';', 1)[0]?.trim().toLowerCase() !== 'application/json') return c.json(failure('forbidden'), 403)\n try {\n return c.json({ path: await pick() } satisfies PickFolderView)\n } catch (cause) {\n if (cause instanceof FolderPickerUnavailableError) return c.json(failure(cause.message), PICK_FOLDER_UNAVAILABLE_STATUS)\n reportError('open the folder chooser', cause)\n return c.json(failure('the folder chooser failed'), 500)\n }\n })\n}\n","/** Read-only git routes and view types shared by the ACRYL Workspace Host and Client. */\n\nexport const WORKSPACE_GIT_REPO_PATH = '/api/acryl-workspace/git/repo'\nexport const WORKSPACE_GIT_STATUS_PATH = '/api/acryl-workspace/git/status'\nexport const WORKSPACE_GIT_DIFF_PATH = '/api/acryl-workspace/git/diff'\nexport const WORKSPACE_GIT_WORKTREE_PATH = '/api/acryl-workspace/git/worktree'\nexport const WORKSPACE_GIT_CHECKS_PATH = '/api/acryl-workspace/git/checks'\nexport const WORKSPACE_GIT_SEARCH_PATH = '/api/acryl-workspace/git/search'\nexport const WORKSPACE_GIT_STAGE_PATH = '/api/acryl-workspace/git/stage'\nexport const WORKSPACE_GIT_UNSTAGE_PATH = '/api/acryl-workspace/git/unstage'\nexport const WORKSPACE_GIT_COMMIT_PATH = '/api/acryl-workspace/git/commit'\n\n/** The most hits one search returns. */\nexport const MAX_SEARCH_RESULTS = 200\n/** The longest query the search route accepts. */\nexport const MAX_SEARCH_QUERY = 200\n\n/** The most files one stage or unstage request may name. */\nexport const MAX_STAGE_FILES = 1000\n/** The longest commit message the commit route accepts. */\nexport const MAX_COMMIT_MESSAGE = 5000\n\n/** One worktree of a repository, as `git worktree list` reports it. */\nexport interface GitWorktree {\n /** Absolute path of the worktree directory. */\n readonly path: string\n /** Checked-out branch name, or null when HEAD is detached or bare. */\n readonly branch: string | null\n /** Full commit id HEAD points at. */\n readonly head: string\n /** True for the repository's main worktree (git always lists it first). */\n readonly main: boolean\n}\n\n/** A repository and every worktree attached to it. */\nexport interface GitRepoView {\n /** Display name: the main worktree's directory name. */\n readonly name: string\n /** Absolute path of the main worktree. */\n readonly root: string\n /** Path of the worktree that contains the directory the request named. */\n readonly current: string\n readonly worktrees: readonly GitWorktree[]\n}\n\n/** Status letters shown next to a changed file. `?` is untracked, `U` is unmerged. */\nexport type GitChangeCode = 'M' | 'A' | 'D' | 'R' | 'U' | '?'\n\nexport interface GitChange {\n /** Path relative to the worktree root, forward slashes. */\n readonly path: string\n readonly code: GitChangeCode\n /** True when the index already holds a change for this path. */\n readonly staged: boolean\n /** Lines added versus HEAD, or null for binary and untracked files. */\n readonly added: number | null\n /** Lines removed versus HEAD, or null for binary and untracked files. */\n readonly removed: number | null\n /** Previous path for a rename. */\n readonly oldPath?: string\n}\n\nexport interface GitStatusView {\n /** Worktree path this status describes. */\n readonly path: string\n /** Current branch, or null when detached. */\n readonly branch: string | null\n readonly changes: readonly GitChange[]\n /** True when the change list was cut at the entry cap. */\n readonly truncated: boolean\n}\n\nexport interface GitDiffView {\n readonly path: string\n readonly file: string\n /** Unified diff text against HEAD; empty for binary files. */\n readonly text: string\n readonly binary: boolean\n /** True when the diff exceeded the output cap and was cut. */\n readonly truncated: boolean\n}\n\n/** The result of creating a branch and its worktree. */\nexport interface GitWorktreeCreatedView {\n /** Absolute path of the new worktree. */\n readonly path: string\n readonly branch: string\n /** The repository after the change, so the caller does not need a second request. */\n readonly repo: GitRepoView\n}\n\nexport type CheckManager = 'pnpm' | 'npm' | 'yarn' | 'bun'\n\nexport interface CheckScript {\n /** A plain script name (letters, digits and `:_.-`), safe to type into a shell. */\n readonly name: string\n /** The script's command line, for display only. */\n readonly command: string\n /** True for check-like names (check, test, lint, typecheck, build, format, ...). */\n readonly primary: boolean\n}\n\n/** What a worktree can run: its package scripts and the package manager its lockfile names. */\nexport interface GitChecksView {\n readonly path: string\n /** The project's own manager, or null when no lockfile says (then `npm` is the neutral default). */\n readonly manager: CheckManager | null\n readonly scripts: readonly CheckScript[]\n}\n\nexport type GitSearchMode = 'name' | 'content'\n\n/** One search hit: a file, and for a content search the line and its text. */\nexport interface GitSearchHit {\n readonly file: string\n readonly line?: number\n readonly text?: string\n}\n\n/** Search results over the tracked and untracked (not ignored) files of a worktree. */\nexport interface GitSearchView {\n readonly path: string\n readonly query: string\n readonly mode: GitSearchMode\n readonly hits: readonly GitSearchHit[]\n /** True when there were more matches than the cap. */\n readonly truncated: boolean\n}\n\n/** The result of a commit: the new commit and the worktree's status afterwards. */\nexport interface GitCommitView {\n /** Abbreviated hash of the new commit. */\n readonly hash: string\n /** First line of its message. */\n readonly subject: string\n readonly status: GitStatusView\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction isWorktree(value: unknown): value is GitWorktree {\n return isRecord(value)\n && typeof value.path === 'string'\n && (value.branch === null || typeof value.branch === 'string')\n && typeof value.head === 'string'\n && typeof value.main === 'boolean'\n}\n\n/** @param value - unknown JSON from the repo route. */\nexport function parseGitRepoView(value: unknown): GitRepoView {\n if (!isRecord(value) || typeof value.name !== 'string' || typeof value.root !== 'string'\n || typeof value.current !== 'string'\n || !Array.isArray(value.worktrees) || !value.worktrees.every(isWorktree)) {\n throw new Error('invalid git repo response')\n }\n return { name: value.name, root: value.root, current: value.current, worktrees: value.worktrees }\n}\n\nconst CHANGE_CODES = new Set<string>(['M', 'A', 'D', 'R', 'U', '?'])\n\nfunction isChange(value: unknown): value is GitChange {\n return isRecord(value)\n && typeof value.path === 'string'\n && typeof value.code === 'string' && CHANGE_CODES.has(value.code)\n && typeof value.staged === 'boolean'\n && (value.added === null || typeof value.added === 'number')\n && (value.removed === null || typeof value.removed === 'number')\n && (value.oldPath === undefined || typeof value.oldPath === 'string')\n}\n\n/** @param value - unknown JSON from the status route. */\nexport function parseGitStatusView(value: unknown): GitStatusView {\n if (!isRecord(value) || typeof value.path !== 'string'\n || (value.branch !== null && typeof value.branch !== 'string')\n || typeof value.truncated !== 'boolean'\n || !Array.isArray(value.changes) || !value.changes.every(isChange)) {\n throw new Error('invalid git status response')\n }\n return { path: value.path, branch: value.branch, changes: value.changes, truncated: value.truncated }\n}\n\n/** @param value - unknown JSON from the diff route. */\nexport function parseGitDiffView(value: unknown): GitDiffView {\n if (!isRecord(value) || typeof value.path !== 'string' || typeof value.file !== 'string'\n || typeof value.text !== 'string' || typeof value.binary !== 'boolean'\n || typeof value.truncated !== 'boolean') {\n throw new Error('invalid git diff response')\n }\n return { path: value.path, file: value.file, text: value.text, binary: value.binary, truncated: value.truncated }\n}\n\n/** @param value - unknown JSON from the worktree route. */\nexport function parseGitWorktreeCreatedView(value: unknown): GitWorktreeCreatedView {\n if (!isRecord(value) || typeof value.path !== 'string' || typeof value.branch !== 'string') {\n throw new Error('invalid git worktree response')\n }\n return { path: value.path, branch: value.branch, repo: parseGitRepoView(value.repo) }\n}\n\nconst MANAGERS = new Set<string>(['pnpm', 'npm', 'yarn', 'bun'])\nconst SAFE_NAME = /^[A-Za-z0-9][A-Za-z0-9:_.-]{0,63}$/\n\nfunction isCheckScript(value: unknown): value is CheckScript {\n return isRecord(value)\n && typeof value.name === 'string' && SAFE_NAME.test(value.name)\n && typeof value.command === 'string'\n && typeof value.primary === 'boolean'\n}\n\n/** @param value - unknown JSON from the checks route. */\nexport function parseGitChecksView(value: unknown): GitChecksView {\n if (!isRecord(value) || typeof value.path !== 'string'\n || (value.manager !== null && !(typeof value.manager === 'string' && MANAGERS.has(value.manager)))\n || !Array.isArray(value.scripts) || !value.scripts.every(isCheckScript)) {\n throw new Error('invalid git checks response')\n }\n return { path: value.path, manager: value.manager as CheckManager | null, scripts: value.scripts }\n}\n\n/** The command line to type for one script, using the project's own package manager. */\nexport function checkCommandLine(manager: CheckManager | null, script: string): string {\n if (!SAFE_NAME.test(script)) throw new Error('unsafe script name')\n return `${manager ?? 'npm'} run ${script}`\n}\n\n/** @param value - unknown JSON from the commit route. */\nexport function parseGitCommitView(value: unknown): GitCommitView {\n if (!isRecord(value) || typeof value.hash !== 'string' || typeof value.subject !== 'string') {\n throw new Error('invalid git commit response')\n }\n return { hash: value.hash, subject: value.subject, status: parseGitStatusView(value.status) }\n}\n\nfunction isHit(value: unknown): value is GitSearchHit {\n return isRecord(value) && typeof value.file === 'string'\n && (value.line === undefined || typeof value.line === 'number')\n && (value.text === undefined || typeof value.text === 'string')\n}\n\n/** @param value - unknown JSON from the search route. */\nexport function parseGitSearchView(value: unknown): GitSearchView {\n if (!isRecord(value) || typeof value.path !== 'string' || typeof value.query !== 'string'\n || (value.mode !== 'name' && value.mode !== 'content') || typeof value.truncated !== 'boolean'\n || !Array.isArray(value.hits) || !value.hits.every(isHit)) {\n throw new Error('invalid git search response')\n }\n return { path: value.path, query: value.query, mode: value.mode, hits: value.hits, truncated: value.truncated }\n}\n","/** Errors of the Workspace git modules. */\n\n/**\n * A request the caller got wrong (400), a directory that is not a repository (404), something that\n * already exists (409), or a git failure (500).\n */\nexport class WorkspaceGitError extends Error {\n constructor(message: string, readonly kind: 'invalid' | 'not-repo' | 'conflict' | 'failed') {\n super(message)\n this.name = 'WorkspaceGitError'\n }\n}\n","/** Checks on what a caller may hand to git, before git sees it. */\n\nimport { MAX_STAGE_FILES } from './contract.ts'\nimport { WorkspaceGitError } from './errors.ts'\n\n/**\n * A conservative first filter, before git's own check: letters, digits, `.`, `_`, `-` and `/`\n * separators, starting with a letter, digit or underscore. It keeps the branch usable as one folder\n * name and can never look like an option or a path escape.\n */\nexport function assertBranchName(branch: string): void {\n if (typeof branch !== 'string' || branch.length === 0 || branch.length > 200\n || !/^[A-Za-z0-9_][A-Za-z0-9._/-]*$/.test(branch)\n || branch.includes('..') || branch.includes('//') || branch.endsWith('/') || branch.endsWith('.') || branch.endsWith('.lock')) {\n throw new WorkspaceGitError('branch names use letters, digits, \".\", \"_\", \"-\" and \"/\", and start with a letter, digit or \"_\"', 'invalid')\n }\n}\n\nexport function assertFileList(files: readonly string[]): void {\n if (!Array.isArray(files) || files.length === 0 || files.length > MAX_STAGE_FILES) {\n throw new WorkspaceGitError(`name between 1 and ${String(MAX_STAGE_FILES)} files`, 'invalid')\n }\n for (const file of files) assertRelativeFile(file)\n}\n\nexport function assertRelativeFile(file: string): void {\n if (typeof file !== 'string' || file.length === 0 || file.length > 4096 || file.includes('\\0')\n || file.startsWith('/') || file.startsWith('-') || /(^|[\\\\/])\\.\\.([\\\\/]|$)/.test(file)) {\n throw new WorkspaceGitError('file must be a relative path inside the worktree', 'invalid')\n }\n}\n","/** Parsers for the machine-readable output of `git worktree`, `git diff --numstat` and `git status`. */\n\nimport { normalize } from 'node:path'\nimport type { GitChange, GitChangeCode, GitWorktree } from './contract.ts'\n\n/** 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`). */\nexport function parseWorktrees(text: string): GitWorktree[] {\n const worktrees: GitWorktree[] = []\n for (const block of text.split(/\\n\\n+/)) {\n let path: string | undefined\n let head = ''\n let branch: string | null = null\n for (const line of block.split('\\n')) {\n if (line.startsWith('worktree ')) path = line.slice('worktree '.length)\n else if (line.startsWith('HEAD ')) head = line.slice('HEAD '.length)\n else if (line.startsWith('branch ')) branch = line.slice('branch '.length).replace(/^refs\\/heads\\//, '')\n }\n if (path !== undefined) worktrees.push({ path: normalize(path), head, branch, main: worktrees.length === 0 })\n }\n return worktrees\n}\n\ninterface LineCount {\n readonly added: number | null\n readonly removed: number | null\n}\n\n/** Parse `git diff --numstat -z`. Binary files report `-` and map to null counts. */\nexport function parseNumstat(text: string): Map<string, LineCount> {\n const counts = new Map<string, LineCount>()\n const tokens = text.split('\\0')\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index]\n if (token === undefined || token === '') continue\n const match = /^(\\d+|-)\\t(\\d+|-)\\t([\\s\\S]*)$/.exec(token)\n if (match === null) continue\n let path = match[3] ?? ''\n // A rename carries an empty path here, then the old and new paths as the next two tokens.\n if (path === '') {\n path = tokens[index + 2] ?? ''\n index += 2\n }\n counts.set(path, {\n added: match[1] === '-' ? null : Number(match[1]),\n removed: match[2] === '-' ? null : Number(match[2]),\n })\n }\n return counts\n}\n\nfunction classify(x: string, y: string): { code: GitChangeCode; staged: boolean } {\n if (x === '?' && y === '?') return { code: '?', staged: false }\n if (x === 'U' || y === 'U' || (x === 'A' && y === 'A') || (x === 'D' && y === 'D')) {\n return { code: 'U', staged: false }\n }\n const staged = x !== ' '\n let code: string\n if (x === 'A' || x === 'C') code = 'A'\n else if (x === 'R') code = 'R'\n else code = y !== ' ' ? y : x\n if (code === 'T') code = 'M'\n return { code: (['M', 'A', 'D', 'R'].includes(code) ? code : 'M') as GitChangeCode, staged }\n}\n\n/** Parse `git status --porcelain=v1 -z`, attaching line counts where git reported them. */\nexport function parsePorcelain(text: string, counts: ReadonlyMap<string, LineCount>): GitChange[] {\n const changes: GitChange[] = []\n const tokens = text.split('\\0')\n for (let index = 0; index < tokens.length; index += 1) {\n const token = tokens[index]\n if (token === undefined || token.length < 4) continue\n const x = token[0] ?? ' '\n const y = token[1] ?? ' '\n if (x === '!' && y === '!') continue\n const path = token.slice(3)\n let oldPath: string | undefined\n if (x === 'R' || x === 'C' || y === 'R' || y === 'C') {\n oldPath = tokens[index + 1]\n index += 1\n }\n const { code, staged } = classify(x, y)\n const count = counts.get(path)\n changes.push({\n path,\n code,\n staged,\n added: count?.added ?? null,\n removed: count?.removed ?? null,\n ...(oldPath === undefined ? {} : { oldPath }),\n })\n }\n return changes\n}\n","/**\n * The confined way to run git: an argument array (never a shell), a timeout, an output cap, and a record\n * of every in-flight process so disposal can abort and reap them. Set `GIT_OPTIONAL_LOCKS=0` so a status\n * poll never takes the index lock an agent's own `git` call may need.\n */\n\nimport { execFile } from 'node:child_process'\nimport { realpath, stat } from 'node:fs/promises'\nimport { isAbsolute } from 'node:path'\nimport { WorkspaceGitError } from './errors.ts'\n\nconst DEFAULT_MAX_OUTPUT_BYTES = 1024 * 1024\nconst DEFAULT_TIMEOUT_MS = 10_000\n\nconst GLOBAL_ARGS = ['-c', 'core.quotepath=false', '-c', 'color.ui=false', '-c', 'core.fsmonitor=false'] as const\n\nexport interface GitRunnerOptions {\n /** Executable to run. Defaults to `git`. */\n readonly gitPath?: string\n /** Output cap per command; longer output is cut and flagged. */\n readonly maxOutputBytes?: number\n readonly timeoutMs?: number\n}\n\nexport interface RunResult {\n readonly stdout: string\n readonly truncated: boolean\n}\n\ninterface Inflight {\n readonly abort: () => void\n readonly done: Promise<void>\n}\n\n\nexport function emptyResult(): RunResult {\n return { stdout: '', truncated: false }\n}\n\nexport class GitRunner {\n private readonly gitPath: string\n private readonly maxOutputBytes: number\n private readonly timeoutMs: number\n private readonly inflight = new Set<Inflight>()\n private disposed = false\n\n constructor(options: GitRunnerOptions = {}) {\n this.gitPath = options.gitPath ?? 'git'\n this.maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n }\n\n /** Abort every in-flight `git` process and wait for each to exit. Later calls reject. */\n async dispose(): Promise<void> {\n this.disposed = true\n const pending = [...this.inflight]\n for (const entry of pending) entry.abort()\n await Promise.all(pending.map(entry => entry.done))\n }\n\n async resolveDirectory(path: string): Promise<string> {\n if (typeof path !== 'string' || path.length === 0 || path.includes('\\0') || !isAbsolute(path)) {\n throw new WorkspaceGitError('path must be an absolute directory', 'invalid')\n }\n let real: string\n try {\n real = await realpath(path)\n if (!(await stat(real)).isDirectory()) throw new Error('not a directory')\n } catch {\n throw new WorkspaceGitError('path is not an existing directory', 'invalid')\n }\n return real\n }\n\n run(args: readonly string[], cwd: string, acceptExit?: number, timeoutMs?: number): Promise<RunResult> {\n if (this.disposed) return Promise.reject(new WorkspaceGitError('git service is disposed', 'failed'))\n const controller = new AbortController()\n let settle!: () => void\n const done = new Promise<void>((resolve) => { settle = resolve })\n const entry: Inflight = { abort: () => { controller.abort() }, done }\n this.inflight.add(entry)\n const env: NodeJS.ProcessEnv = {\n ...process.env,\n GIT_OPTIONAL_LOCKS: '0',\n GIT_TERMINAL_PROMPT: '0',\n GIT_PAGER: 'cat',\n LC_ALL: 'C',\n }\n delete env.GIT_DIR\n delete env.GIT_WORK_TREE\n delete env.GIT_INDEX_FILE\n return new Promise<RunResult>((resolve, reject) => {\n const child = execFile(\n this.gitPath,\n [...GLOBAL_ARGS, ...args],\n {\n cwd,\n env,\n encoding: 'utf8',\n maxBuffer: this.maxOutputBytes,\n timeout: timeoutMs ?? this.timeoutMs,\n signal: controller.signal,\n },\n (failure, stdout, stderr) => {\n if (failure === null) {\n resolve({ stdout, truncated: false })\n return\n }\n const info = failure as NodeJS.ErrnoException & { stdout?: string }\n if (info.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {\n resolve({ stdout: info.stdout ?? stdout, truncated: true })\n return\n }\n if (typeof info.code === 'number' && info.code === acceptExit) {\n resolve({ stdout, truncated: false })\n return\n }\n if (/not a git repository/i.test(stderr)) {\n reject(new WorkspaceGitError('not a git repository', 'not-repo'))\n return\n }\n reject(new WorkspaceGitError(`git ${args[0] ?? ''} failed`, 'failed'))\n },\n )\n // execFile's callback fires as soon as an abort is requested, before the process has exited.\n // Only the child's `close` (or a spawn `error`) proves it is gone, so that is what disposal awaits.\n const finished = (): void => {\n this.inflight.delete(entry)\n settle()\n }\n child.once('close', finished)\n child.once('error', finished)\n })\n }\n}\n","/** What changed in a worktree: the status list, one file's diff, and staging. Nothing here commits. */\n\nimport type { GitDiffView, GitStatusView } from './contract.ts'\nimport { WorkspaceGitError } from './errors.ts'\nimport { assertFileList, assertRelativeFile } from './guards.ts'\nimport { parseNumstat, parsePorcelain } from './parsing.ts'\nimport { emptyResult, type GitRunner, type RunResult } from './runner.ts'\n\nexport class WorkspaceChanges {\n constructor(private readonly git: GitRunner, private readonly maxChanges: number) {}\n\n /**\n * Changed files in one worktree, versus HEAD.\n * @param path - absolute worktree directory.\n */\n async status(path: string): Promise<GitStatusView> {\n const dir = await this.git.resolveDirectory(path)\n const [porcelain, numstat, branch] = await Promise.all([\n this.git.run(['status', '--porcelain=v1', '-z', '--untracked-files=all'], dir),\n this.git.run(['diff', '--numstat', '-z', 'HEAD', '--'], dir).catch(emptyResult),\n this.git.run(['branch', '--show-current'], dir).catch(emptyResult),\n ])\n const counts = parseNumstat(numstat.stdout)\n const all = parsePorcelain(porcelain.stdout, counts)\n const truncated = porcelain.truncated || all.length > this.maxChanges\n const name = branch.stdout.trim()\n return {\n path: dir,\n branch: name === '' ? null : name,\n changes: all.slice(0, this.maxChanges),\n truncated,\n }\n }\n\n /**\n * Unified diff of one file against HEAD (untracked files diff against nothing).\n * @param path - absolute worktree directory.\n * @param file - path relative to that worktree.\n */\n async diff(path: string, file: string): Promise<GitDiffView> {\n const dir = await this.git.resolveDirectory(path)\n assertRelativeFile(file)\n const untracked = (await this.git.run(['ls-files', '--others', '--exclude-standard', '-z', '--', file], dir)).stdout.length > 0\n const flags = ['--no-color', '--no-ext-diff', '--no-textconv'] as const\n let result: RunResult\n if (untracked) {\n // `git diff --no-index` exits 1 when the files differ, which is the normal case here.\n result = await this.git.run(['diff', '--no-index', ...flags, '--', '/dev/null', file], dir, 1)\n } else {\n try {\n result = await this.git.run(['diff', ...flags, 'HEAD', '--', file], dir)\n } catch (cause) {\n // A repository with no commits has no HEAD; fall back to the index against the empty tree.\n if (!(cause instanceof WorkspaceGitError) || cause.kind !== 'failed') throw cause\n result = await this.git.run(['diff', '--cached', ...flags, '--', file], dir)\n }\n }\n const binary = /^Binary files .* differ$/m.test(result.stdout) || result.stdout.includes('GIT binary patch')\n return { path: dir, file, text: binary ? '' : result.stdout, binary, truncated: result.truncated }\n }\n\n /**\n * Stage files (`git add`), then report the worktree's status.\n * @param path - absolute worktree directory.\n * @param files - paths relative to that worktree.\n */\n async stage(path: string, files: readonly string[]): Promise<GitStatusView> {\n const dir = await this.git.resolveDirectory(path)\n assertFileList(files)\n await this.git.run(['add', '--', ...files], dir)\n return this.status(dir)\n }\n\n /**\n * Unstage files, keeping their working-tree changes, then report the status. Works before the first commit too.\n */\n async unstage(path: string, files: readonly string[]): Promise<GitStatusView> {\n const dir = await this.git.resolveDirectory(path)\n assertFileList(files)\n try {\n await this.git.run(['reset', '-q', 'HEAD', '--', ...files], dir)\n } catch {\n // No HEAD yet (an empty repository): dropping the paths from the index is the same thing.\n await this.git.run(['rm', '--cached', '-r', '-q', '--', ...files], dir)\n }\n return this.status(dir)\n }\n}\n","/** Read-only discovery of the checks a worktree can run: its package.json scripts and package manager. */\n\nimport { readFile, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { CheckManager, CheckScript, GitChecksView } from './contract.ts'\n\nconst MAX_PACKAGE_JSON_BYTES = 256 * 1024\nconst MAX_SCRIPTS = 60\n/** A script name is typed into a shell on the user's behalf, so only plain names are ever offered. */\nconst SAFE_SCRIPT_NAME = /^[A-Za-z0-9][A-Za-z0-9:_.-]{0,63}$/\nconst PRIMARY = /^(check|verify|ci|test|tests|lint|typecheck|type-check|build|format)([:._-].*)?$/i\n\nconst LOCKFILES: readonly (readonly [string, CheckManager])[] = [\n ['pnpm-lock.yaml', 'pnpm'],\n ['yarn.lock', 'yarn'],\n ['bun.lock', 'bun'],\n ['bun.lockb', 'bun'],\n ['package-lock.json', 'npm'],\n]\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path)\n return true\n } catch {\n return false\n }\n}\n\n/** The manager the project itself uses: its lockfile, else null (the caller then runs plain `npm`). */\nexport async function detectManager(dir: string): Promise<CheckManager | null> {\n for (const [file, manager] of LOCKFILES) {\n if (await exists(join(dir, file))) return manager\n }\n return null\n}\n\n/** Parse `package.json` scripts; a missing, oversized or malformed file simply means \"no scripts\". */\nexport function parseScripts(text: string): CheckScript[] {\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return []\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return []\n const scripts = (parsed as { scripts?: unknown }).scripts\n if (typeof scripts !== 'object' || scripts === null || Array.isArray(scripts)) return []\n const out: CheckScript[] = []\n for (const [name, command] of Object.entries(scripts)) {\n if (typeof command !== 'string' || !SAFE_SCRIPT_NAME.test(name)) continue\n out.push({ name, command: command.slice(0, 300), primary: PRIMARY.test(name) })\n }\n // Check-like scripts first, otherwise keep the file's order.\n out.sort((a, b) => Number(b.primary) - Number(a.primary))\n return out.slice(0, MAX_SCRIPTS)\n}\n\n/** @param dir - an already validated absolute worktree directory. */\nexport async function readWorktreeChecks(dir: string): Promise<GitChecksView> {\n let scripts: CheckScript[] = []\n try {\n const file = join(dir, 'package.json')\n if ((await stat(file)).size <= MAX_PACKAGE_JSON_BYTES) scripts = parseScripts(await readFile(file, 'utf8'))\n } catch {\n scripts = []\n }\n return { path: dir, manager: await detectManager(dir), scripts }\n}\n","/** Committing what is staged. It never pushes and never bypasses hooks. */\n\nimport type { GitCommitView } from './contract.ts'\nimport { MAX_COMMIT_MESSAGE } from './contract.ts'\nimport type { WorkspaceChanges } from './changes.ts'\nimport { WorkspaceGitError } from './errors.ts'\nimport type { GitRunner } from './runner.ts'\n\nconst COMMIT_TIMEOUT_MS = 120_000\n\nexport class WorkspaceCommits {\n constructor(private readonly git: GitRunner, private readonly changes: WorkspaceChanges) {}\n\n /**\n * Commit what is staged. Refuses an empty message, nothing staged, or a missing git identity with a reason the\n * user can act on; never pushes, and never bypasses hooks.\n */\n async commit(path: string, message: string): Promise<GitCommitView> {\n const dir = await this.git.resolveDirectory(path)\n const text = typeof message === 'string' ? message.trim() : ''\n if (text === '' || text.length > MAX_COMMIT_MESSAGE || text.includes('\\0')) {\n throw new WorkspaceGitError('write a commit message (up to 5000 characters)', 'invalid')\n }\n if ((await this.git.run(['diff', '--cached', '--name-only', '-z'], dir)).stdout === '') {\n throw new WorkspaceGitError('nothing is staged to commit', 'conflict')\n }\n try {\n await this.git.run(['var', 'GIT_AUTHOR_IDENT'], dir)\n } catch {\n throw new WorkspaceGitError('git does not know who you are: set user.name and user.email first', 'conflict')\n }\n try {\n await this.git.run(['commit', '-q', '-m', text], dir, undefined, COMMIT_TIMEOUT_MS)\n } catch {\n throw new WorkspaceGitError('git could not commit (a commit hook may have refused it)', 'conflict')\n }\n const [hash, subject] = await Promise.all([\n this.git.run(['rev-parse', '--short', 'HEAD'], dir),\n this.git.run(['log', '-1', '--format=%s'], dir),\n ])\n return { hash: hash.stdout.trim(), subject: subject.stdout.trim(), status: await this.changes.status(dir) }\n }\n}\n","/** Which entries of one directory git ignores, for the file tree to show them dimmed. */\n\nimport type { GitRunner } from './runner.ts'\n\n/**\n * @param git - the runner.\n * @param root - absolute worktree root (its real path).\n * @param paths - entries relative to the root, `/`-separated; a directory ends in `/`, so directory-only patterns (`build/`) apply.\n * @returns the given paths git ignores; none when git cannot answer (the tree then shows everything undimmed).\n */\nexport async function ignoredPaths(git: GitRunner, root: string, paths: readonly string[]): Promise<ReadonlySet<string>> {\n if (paths.length === 0) return new Set()\n try {\n // Exit 1 means none of them is ignored. One path per line (`-z` needs `--stdin`, which the runner has no input for); a name git still\n // quotes (a newline or a quote in it) does not match and is shown undimmed.\n const result = await git.run(['-c', 'core.quotePath=false', 'check-ignore', '--', ...paths], root, 1)\n return new Set(result.stdout.split('\\n').filter(path => path !== ''))\n } catch {\n return new Set()\n }\n}\n","/** Repo-wide search over the files git tracks or would track: by name or by content. */\n\nimport type { GitSearchMode, GitSearchView } from './contract.ts'\nimport { MAX_SEARCH_QUERY, MAX_SEARCH_RESULTS } from './contract.ts'\nimport { WorkspaceGitError } from './errors.ts'\nimport type { GitRunner } from './runner.ts'\n\nexport class WorkspaceSearch {\n constructor(private readonly git: GitRunner) {}\n\n /**\n * Find files by name, or lines by content, among the tracked and untracked files git does not ignore.\n * Case-insensitive and literal (the query is never a pattern), so it cannot be a regular-expression trap.\n * @param path - absolute worktree directory.\n * @param query - what to look for.\n */\n async search(path: string, query: string, mode: GitSearchMode): Promise<GitSearchView> {\n const dir = await this.git.resolveDirectory(path)\n const text = typeof query === 'string' ? query.trim() : ''\n if (text === '' || text.length > MAX_SEARCH_QUERY || text.includes('\\0') || (mode !== 'name' && mode !== 'content')) {\n throw new WorkspaceGitError('type something to search for (up to 200 characters)', 'invalid')\n }\n if (mode === 'name') {\n const listed = await this.git.run(['ls-files', '-z', '--cached', '--others', '--exclude-standard'], dir)\n const needle = text.toLowerCase()\n const matches = listed.stdout.split('\\0').filter(file => file !== '' && file.toLowerCase().includes(needle))\n // A match in the file's own name outranks one in a folder name; then shorter and alphabetical.\n const inName = (file: string): boolean => (file.split('/').pop() ?? file).toLowerCase().includes(needle)\n matches.sort((a, b) => Number(inName(b)) - Number(inName(a)) || a.length - b.length || a.localeCompare(b))\n return {\n path: dir, query: text, mode,\n hits: matches.slice(0, MAX_SEARCH_RESULTS).map(file => ({ file })),\n truncated: matches.length > MAX_SEARCH_RESULTS || listed.truncated,\n }\n }\n const found = await this.git.run(['grep', '-n', '-I', '-i', '-F', '-z', '--untracked', '-e', text, '--'], dir, 1)\n const hits: { file: string; line: number; text: string }[] = []\n let truncated = found.truncated\n // With -z each hit is `file NUL line NUL text` and hits are separated by a newline.\n for (const record of found.stdout.split('\\n')) {\n if (record === '') continue\n const [file, line, ...rest] = record.split('\\0')\n if (file === undefined || line === undefined || !/^\\d+$/.test(line)) continue\n if (hits.length >= MAX_SEARCH_RESULTS) { truncated = true; break }\n hits.push({ file, line: Number(line), text: rest.join('\\0').slice(0, 300) })\n }\n return { path: dir, query: text, mode, hits, truncated }\n }\n}\n","/** Repositories and their worktrees: listing them, confirming a path is one, and creating one. */\n\nimport { mkdir, realpath, stat } from 'node:fs/promises'\nimport { basename, dirname, join, normalize } from 'node:path'\nimport type { GitRepoView, GitWorktreeCreatedView } from './contract.ts'\nimport { WorkspaceGitError } from './errors.ts'\nimport { assertBranchName } from './guards.ts'\nimport { parseWorktrees } from './parsing.ts'\nimport type { GitRunner } from './runner.ts'\n\n/** Checking out a large repository can take far longer than a status call. */\nconst WORKTREE_ADD_TIMEOUT_MS = 120_000\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path)\n return true\n } catch {\n return false\n }\n}\n\nexport class WorkspaceWorktrees {\n constructor(private readonly git: GitRunner) {}\n\n /**\n * List the repository's worktrees.\n * @param cwd - any directory inside the repository.\n * @returns the repository view, or null when `cwd` is not inside a git repository.\n */\n async repo(cwd: string): Promise<GitRepoView | null> {\n const dir = await this.git.resolveDirectory(cwd)\n let current: string\n try {\n // Git reports `C:/repo` on Windows; the rest of the app speaks `C:\\repo`.\n current = normalize((await this.git.run(['rev-parse', '--show-toplevel'], dir)).stdout.trim())\n } catch (cause) {\n if (cause instanceof WorkspaceGitError && cause.kind === 'not-repo') return null\n throw cause\n }\n const listed = await this.git.run(['worktree', 'list', '--porcelain'], dir)\n const worktrees = parseWorktrees(listed.stdout)\n const main = worktrees[0]\n if (main === undefined) throw new WorkspaceGitError('git listed no worktrees', 'failed')\n return { name: basename(main.path), root: main.path, current, worktrees }\n }\n\n /**\n * Confirm `path` is the root of a git worktree and return its real path. The file routes use this so\n * they only ever touch a checkout, never an arbitrary directory.\n * @throws WorkspaceGitError `invalid` when the path is not a worktree root.\n */\n async worktreeRoot(path: string): Promise<string> {\n const dir = await this.git.resolveDirectory(path)\n const top = (await this.git.run(['rev-parse', '--show-toplevel'], dir)).stdout.trim()\n let real: string\n try {\n real = await realpath(top)\n } catch {\n throw new WorkspaceGitError('path is not a git worktree', 'invalid')\n }\n if (real !== dir) throw new WorkspaceGitError('path is not the root of a git worktree', 'invalid')\n return dir\n }\n\n /**\n * Create a branch and a worktree for it in the repository's sibling `<repo>.worktrees/` folder,\n * which never dirties the repository. The branch starts at the main worktree's current commit.\n * @param cwd - any directory inside the repository.\n * @param branch - the new branch name.\n */\n async createWorktree(cwd: string, branch: string): Promise<GitWorktreeCreatedView> {\n assertBranchName(branch)\n const view = await this.repo(cwd)\n if (view === null) throw new WorkspaceGitError('not a git repository', 'not-repo')\n // Git has the last word on what a valid branch name is.\n try {\n await this.git.run(['check-ref-format', '--branch', branch], view.root)\n } catch {\n throw new WorkspaceGitError('that is not a valid branch name', 'invalid')\n }\n if ((await this.git.run(['branch', '--list', branch], view.root)).stdout.trim() !== '') {\n throw new WorkspaceGitError(`the branch ${branch} already exists`, 'conflict')\n }\n const parent = join(dirname(view.root), `${basename(view.root)}.worktrees`)\n const target = join(parent, branch.replace(/\\//g, '-'))\n if (await pathExists(target)) throw new WorkspaceGitError('that worktree folder already exists', 'conflict')\n await mkdir(parent, { recursive: true })\n await this.git.run(['worktree', 'add', '-b', branch, target], view.root, undefined, WORKTREE_ADD_TIMEOUT_MS)\n const path = await realpath(target)\n const after = await this.repo(path)\n if (after === null) throw new WorkspaceGitError('the new worktree is not readable', 'failed')\n return { path, branch, repo: after }\n }\n}\n","/**\n * The Workspace's git access, as one facade over focused modules.\n *\n * Each use case lives in its own module and reaches git only through the confined {@link GitRunner}\n * (argument arrays, timeouts, output caps, no shell):\n * - `worktrees.ts` repositories and worktrees\n * - `changes.ts` status, diff, stage, unstage\n * - `commits.ts` commit (never pushes)\n * - `search.ts` repo-wide search\n * - `checks.ts` package scripts a worktree can run\n * The facade exists so the routes and the file routes keep one collaborator to depend on.\n */\n\nimport type {\n GitChecksView,\n GitCommitView,\n GitDiffView,\n GitRepoView,\n GitSearchMode,\n GitSearchView,\n GitStatusView,\n GitWorktreeCreatedView,\n} from './contract.ts'\nimport { WorkspaceChanges } from './changes.ts'\nimport { readWorktreeChecks } from './checks.ts'\nimport { WorkspaceCommits } from './commits.ts'\nimport { ignoredPaths } from './ignored.ts'\nimport { GitRunner, type GitRunnerOptions } from './runner.ts'\nimport { WorkspaceSearch } from './search.ts'\nimport { WorkspaceWorktrees } from './worktrees.ts'\n\nexport { WorkspaceGitError } from './errors.ts'\nexport { parseNumstat, parsePorcelain, parseWorktrees } from './parsing.ts'\n\nconst DEFAULT_MAX_CHANGES = 1000\n\nexport interface WorkspaceGitOptions extends GitRunnerOptions {\n /** Cap on entries returned by `status`. */\n readonly maxChanges?: number\n}\n\nexport class WorkspaceGit {\n private readonly runner: GitRunner\n private readonly worktrees: WorkspaceWorktrees\n private readonly changes: WorkspaceChanges\n private readonly commits: WorkspaceCommits\n private readonly searcher: WorkspaceSearch\n\n constructor(options: WorkspaceGitOptions = {}) {\n this.runner = new GitRunner(options)\n this.worktrees = new WorkspaceWorktrees(this.runner)\n this.changes = new WorkspaceChanges(this.runner, options.maxChanges ?? DEFAULT_MAX_CHANGES)\n this.commits = new WorkspaceCommits(this.runner, this.changes)\n this.searcher = new WorkspaceSearch(this.runner)\n }\n\n /** The repository containing `cwd`, or null when it is not inside a git repository. */\n repo(cwd: string): Promise<GitRepoView | null> { return this.worktrees.repo(cwd) }\n\n /** Confirm `path` is the root of a git worktree and return its real path. */\n worktreeRoot(path: string): Promise<string> { return this.worktrees.worktreeRoot(path) }\n\n /** Create a branch and a worktree for it in the repository's sibling `<repo>.worktrees/` folder. */\n createWorktree(cwd: string, branch: string): Promise<GitWorktreeCreatedView> { return this.worktrees.createWorktree(cwd, branch) }\n\n /** Changed files in one worktree, versus HEAD. */\n status(path: string): Promise<GitStatusView> { return this.changes.status(path) }\n\n /** Unified diff of one file against HEAD (untracked files diff against nothing). */\n diff(path: string, file: string): Promise<GitDiffView> { return this.changes.diff(path, file) }\n\n /** Stage files, then report the worktree's status. */\n stage(path: string, files: readonly string[]): Promise<GitStatusView> { return this.changes.stage(path, files) }\n\n /** Unstage files, keeping their working-tree changes, then report the status. */\n unstage(path: string, files: readonly string[]): Promise<GitStatusView> { return this.changes.unstage(path, files) }\n\n /** Commit what is staged; never pushes. */\n commit(path: string, message: string): Promise<GitCommitView> { return this.commits.commit(path, message) }\n\n /** Find files by name, or lines by content, literally and case-insensitively. */\n search(path: string, query: string, mode: GitSearchMode): Promise<GitSearchView> { return this.searcher.search(path, query, mode) }\n\n /** Which of the given worktree-relative paths git ignores (a directory ends in `/`); none when git cannot say. */\n ignored(root: string, paths: readonly string[]): Promise<ReadonlySet<string>> { return ignoredPaths(this.runner, root, paths) }\n\n /** The scripts a worktree can run as checks, and its package manager. */\n async checks(path: string): Promise<GitChecksView> {\n return readWorktreeChecks(await this.runner.resolveDirectory(path))\n }\n\n /** Abort every in-flight `git` process and wait for each to exit. Later calls reject. */\n dispose(): Promise<void> { return this.runner.dispose() }\n}\n","/** The workspace git routes: five reads, and the writes the Changes panel makes (worktree, stage, unstage, commit), for the app's own page only. */\n\nimport { Acryl, type Context } from '@acryldev/blends'\nimport { INVALID_JSON, failure, isRecord, jsonBody, ownPage, readJson, type ReportError } from '../private-route.ts'\nimport {\n WORKSPACE_GIT_CHECKS_PATH,\n WORKSPACE_GIT_COMMIT_PATH,\n WORKSPACE_GIT_DIFF_PATH,\n WORKSPACE_GIT_REPO_PATH,\n WORKSPACE_GIT_SEARCH_PATH,\n WORKSPACE_GIT_STAGE_PATH,\n WORKSPACE_GIT_STATUS_PATH,\n WORKSPACE_GIT_UNSTAGE_PATH,\n WORKSPACE_GIT_WORKTREE_PATH,\n} from './contract.ts'\nimport { WorkspaceGitError, type WorkspaceGit } from './service.ts'\n\nfunction required(c: Context, name: string): string {\n const value = c.req.query(name)\n if (value === undefined || value.length === 0) throw new WorkspaceGitError(`missing ${name}`, 'invalid')\n return value\n}\n\ntype Parse<T> = (body: Record<string, unknown>) => T | undefined\n\nfunction parseFiles(body: Record<string, unknown>): { path: string, files: string[] } | undefined {\n if (Object.keys(body).length !== 2 || typeof body.path !== 'string' || !Array.isArray(body.files)) return undefined\n if (!body.files.every((file): file is string => typeof file === 'string')) return undefined\n return { path: body.path, files: body.files }\n}\n\nfunction parseWorktree(body: Record<string, unknown>): { cwd: string, branch: string } | undefined {\n if (Object.keys(body).length !== 2 || typeof body.cwd !== 'string' || typeof body.branch !== 'string') return undefined\n return { cwd: body.cwd, branch: body.branch }\n}\n\nfunction parseCommit(body: Record<string, unknown>): { path: string, message: string } | undefined {\n if (Object.keys(body).length !== 2 || typeof body.path !== 'string' || typeof body.message !== 'string') return undefined\n return { path: body.path, message: body.message }\n}\n\n/**\n * GET `repo?cwd=`, `status?path=`, `checks?path=`, `search?path=&q=&mode=name|content` and `diff?path=&file=`; POST `worktree` `{ cwd, branch }`\n * (create a branch and its worktree), `stage` and `unstage` `{ path, files }`, and `commit` `{ path, message }` (never pushes).\n */\nexport function gitRoutes(git: WorkspaceGit, reportError: ReportError): Acryl {\n const answer = async (c: Context, operation: string, compute: () => Promise<object | null>): Promise<Response> => {\n try {\n const view = await compute()\n if (view === null) return c.json(failure('not a git repository'), 404)\n return c.json(view)\n } catch (cause) {\n if (cause instanceof WorkspaceGitError) {\n if (cause.kind === 'invalid') return c.json(failure(cause.message), 400)\n if (cause.kind === 'conflict') return c.json(failure(cause.message), 409)\n if (cause.kind === 'not-repo') return c.json(failure('not a git repository'), 404)\n }\n reportError(operation, cause)\n return c.json(failure('git request failed'), 500)\n }\n }\n /** A small JSON body, parsed strictly, then one git write answered with its result. */\n const write = <T>(operation: string, invalid: string, parse: Parse<T>, compute: (input: T) => Promise<object>) => async (c: Context): Promise<Response> => {\n const body = await readJson(c)\n const input = body === INVALID_JSON || !isRecord(body) ? undefined : parse(body)\n if (input === undefined) return c.json(failure(invalid), 400)\n return answer(c, operation, () => compute(input))\n }\n return new Acryl()\n // 200 with `{ repo: null }` for a directory that is not a repository: that is an ordinary answer, and a 404 would print a console error for\n // every temporary folder a chat session uses.\n .get(WORKSPACE_GIT_REPO_PATH, ownPage, c => answer(c, 'read git repo', async () => ({ repo: await git.repo(required(c, 'cwd')) })))\n .get(WORKSPACE_GIT_STATUS_PATH, ownPage, c => answer(c, 'read git status', () => git.status(required(c, 'path'))))\n .get(WORKSPACE_GIT_CHECKS_PATH, ownPage, c => answer(c, 'read checks', () => git.checks(required(c, 'path'))))\n .get(WORKSPACE_GIT_SEARCH_PATH, ownPage, c => answer(c, 'search', () =>\n git.search(required(c, 'path'), required(c, 'q'), c.req.query('mode') === 'content' ? 'content' : 'name')))\n .get(WORKSPACE_GIT_DIFF_PATH, ownPage, c => answer(c, 'read git diff', () => git.diff(required(c, 'path'), required(c, 'file'))))\n .post(WORKSPACE_GIT_WORKTREE_PATH, ownPage, jsonBody(), write('create git worktree', 'invalid worktree request', parseWorktree,\n input => git.createWorktree(input.cwd, input.branch)))\n .post(WORKSPACE_GIT_STAGE_PATH, ownPage, jsonBody(), write('stage', 'invalid stage request', parseFiles, input => git.stage(input.path, input.files)))\n .post(WORKSPACE_GIT_UNSTAGE_PATH, ownPage, jsonBody(), write('unstage', 'invalid unstage request', parseFiles,\n input => git.unstage(input.path, input.files)))\n .post(WORKSPACE_GIT_COMMIT_PATH, ownPage, jsonBody(), write('commit', 'invalid commit request', parseCommit, input => git.commit(input.path, input.message)))\n}\n","/**\n * 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\n * `@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\n * way round.\n */\n\nexport const WORKSPACE_PROJECTS_PATH = '/api/acryl-workspace/projects'\n/** A server-sent event stream of the registry's view: one message now, then one per change (an agent's tool call, another window). */\nexport const WORKSPACE_PROJECTS_EVENTS_PATH = '/api/acryl-workspace/projects/events'\n\n/** How a workspace is organized (spec 043): separate projects, projects that share context with every agent, or a remote machine. */\nexport type WorkspaceKind = 'individual' | 'shared' | 'remote'\n\nexport const WORKSPACE_KINDS: readonly WorkspaceKind[] = ['individual', 'shared', 'remote']\n\n/** The workspace every app has: it cannot be deleted, and the folders added before workspaces existed are its projects. */\nexport const DEFAULT_WORKSPACE_ID = 'default'\n\n/** One workspace as the page sees it. */\nexport interface WorkspaceSummary {\n readonly id: string\n readonly name: string\n readonly kind: WorkspaceKind\n /** Absolute folder paths, in the order they were added. */\n readonly projects: readonly string[]\n /** For a remote workspace: the SSH target saved for the connection that comes later. */\n readonly remote?: { readonly host: string, readonly user?: string, readonly path?: string }\n}\n\nexport interface ProjectRegistryView {\n /** The shown workspace's folders, in the order the user added them. */\n readonly paths: readonly string[]\n /** The projects that already existed as DSH workspaces were taken over once (see `adopt`). */\n readonly adopted: boolean\n /** Every workspace, Default first. */\n readonly workspaces: readonly WorkspaceSummary[]\n /** The id of the workspace the sidebar shows. */\n readonly current: string\n}\n\nexport type ProjectRequest =\n | { readonly op: 'add'; readonly path: string }\n | { readonly op: 'remove'; readonly path: string }\n /** Take over folders that were registered before ACRYL owned the list. Applied once; later calls change nothing. */\n | { readonly op: 'adopt'; readonly paths: readonly string[] }\n | { readonly op: 'create-workspace'; readonly name: string; readonly kind: WorkspaceKind; readonly remote?: { readonly host: string, readonly user?: string, readonly path?: string } }\n | { readonly op: 'switch-workspace'; readonly id: string }\n | { readonly op: 'rename-workspace'; readonly id: string; readonly name: string }\n | { readonly op: 'delete-workspace'; readonly id: string }\n\nexport type ProjectResponse =\n | { readonly ok: true; readonly view: ProjectRegistryView }\n | { readonly ok: false; readonly code: 'invalid' | 'not-a-folder' | 'workspace'; readonly message: string }\n\nexport class ProjectRequestError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ProjectRequestError'\n }\n}\n\nconst MAX_ADOPTED = 500\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction only(record: Record<string, unknown>, allowed: readonly string[]): void {\n const extra = Object.keys(record).find(key => key !== 'op' && !allowed.includes(key))\n if (extra !== undefined) throw new ProjectRequestError(`unknown field \"${extra}\"`)\n}\n\nfunction pathOf(value: unknown): string {\n if (typeof value !== 'string' || value.trim() === '' || value.length > 4096) throw new ProjectRequestError('path must be the absolute path of a folder')\n return value\n}\n\n/** @throws ProjectRequestError naming what is wrong; nothing is coerced. */\nexport function parseProjectRequest(value: unknown): ProjectRequest {\n if (!isRecord(value) || typeof value.op !== 'string') throw new ProjectRequestError('the request must be an object with an op')\n switch (value.op) {\n case 'add':\n case 'remove':\n only(value, ['path'])\n return { op: value.op, path: pathOf(value.path) }\n case 'adopt': {\n only(value, ['paths'])\n 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`)\n return { op: 'adopt', paths: value.paths.map(pathOf) }\n }\n case 'create-workspace': {\n only(value, ['name', 'kind', 'remote'])\n if (typeof value.kind !== 'string' || !(WORKSPACE_KINDS as readonly string[]).includes(value.kind)) throw new ProjectRequestError(`kind must be one of ${WORKSPACE_KINDS.join(', ')}`)\n const remote = value.remote === undefined ? undefined : remoteOf(value.remote)\n return { op: 'create-workspace', name: textOf(value.name, 'name'), kind: value.kind as WorkspaceKind, ...(remote === undefined ? {} : { remote }) }\n }\n case 'switch-workspace':\n case 'delete-workspace':\n only(value, ['id'])\n return { op: value.op, id: textOf(value.id, 'id') }\n case 'rename-workspace':\n only(value, ['id', 'name'])\n return { op: 'rename-workspace', id: textOf(value.id, 'id'), name: textOf(value.name, 'name') }\n default:\n throw new ProjectRequestError(`unknown op \"${value.op}\"`)\n }\n}\n\nfunction textOf(value: unknown, field: string): string {\n if (typeof value !== 'string' || value.length > 200) throw new ProjectRequestError(`${field} must be a short text`)\n return value\n}\n\nfunction remoteOf(value: unknown): { host: string, user?: string, path?: string } {\n if (!isRecord(value)) throw new ProjectRequestError('remote must be an object with a host')\n const extra = Object.keys(value).find(key => !['host', 'user', 'path'].includes(key))\n if (extra !== undefined) throw new ProjectRequestError(`unknown remote field \"${extra}\"`)\n return {\n host: textOf(value.host, 'remote.host'),\n ...(value.user === undefined ? {} : { user: textOf(value.user, 'remote.user') }),\n ...(value.path === undefined ? {} : { path: textOf(value.path, 'remote.path') }),\n }\n}\n\nfunction isStringList(value: unknown): value is string[] {\n return Array.isArray(value) && value.every(item => typeof item === 'string')\n}\n\nfunction workspaceOf(value: unknown): WorkspaceSummary {\n if (!isRecord(value) || typeof value.id !== 'string' || typeof value.name !== 'string' || !(WORKSPACE_KINDS as readonly unknown[]).includes(value.kind) || !isStringList(value.projects)) {\n throw new ProjectRequestError('the registry view is malformed')\n }\n const remote = value.remote === undefined ? undefined : remoteOf(value.remote)\n return { id: value.id, name: value.name, kind: value.kind as WorkspaceKind, projects: value.projects, ...(remote === undefined ? {} : { remote }) }\n}\n\nexport function parseProjectRegistryView(value: unknown): ProjectRegistryView {\n if (!isRecord(value) || !isStringList(value.paths) || typeof value.adopted !== 'boolean' || !Array.isArray(value.workspaces) || typeof value.current !== 'string') {\n throw new ProjectRequestError('the registry view is malformed')\n }\n return { paths: value.paths, adopted: value.adopted, workspaces: value.workspaces.map(workspaceOf), current: value.current }\n}\n","/**\n * The project registry: the folders the user added, grouped into workspaces (spec 043), in one `@acryldev/settings` section, changed one write at a time.\n * 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\n * existed. A project can be in several workspaces; removing it from one never touches the others or the disk.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { statSync } from 'node:fs'\nimport { isAbsolute, resolve } from 'node:path'\nimport type { SettingsScope } from '@acryldev/settings'\nimport z from '@deepseek-ai/schemastery'\nimport { DEFAULT_WORKSPACE_ID, type ProjectRegistryView, type WorkspaceKind, type WorkspaceSummary } from './contract.ts'\n\nexport const PROJECTS_NAMESPACE = 'workspace'\n\nexport { DEFAULT_WORKSPACE_ID }\n\nexport interface RemoteTarget {\n host: string\n user?: string\n path?: string\n}\n\nexport interface WorkspaceRecord {\n id: string\n name: string\n kind: WorkspaceKind\n projects: string[]\n remote?: RemoteTarget\n}\n\nexport interface ProjectsSection {\n /** The folders added before workspaces existed: read once to build Default, then left empty. */\n projects: string[]\n adopted: boolean\n workspaces: WorkspaceRecord[]\n current: string\n}\n\nconst WorkspaceSchema: z<WorkspaceRecord> = z.object({\n id: z.string().required(),\n name: z.string().required(),\n kind: z.union(['individual', 'shared', 'remote']).default('individual'),\n projects: z.array(z.string()).default([]),\n // Validated in code (validRemote) where it applies: a schema-required host would also be demanded of workspaces that have no remote.\n remote: z.object({ host: z.string(), user: z.string(), path: z.string() }),\n})\n\n/** The section's schema: the workspaces with their folders, the one shown, and whether the pre-existing folders were taken over. */\nexport const ProjectsSchema: z<ProjectsSection> = z.object({\n projects: z.array(z.string()).default([]).description('Folders added before workspaces existed; moved into the Default workspace.'),\n adopted: z.boolean().default(false).description('Projects registered before ACRYL owned the list were taken over once.'),\n workspaces: z.array(WorkspaceSchema).default([]).description('Workspaces: named sets of projects, Default first.'),\n current: z.string().default(DEFAULT_WORKSPACE_ID).description('The workspace the sidebar shows.'),\n})\n\n/** A request the registry refuses (an unknown workspace, a duplicate name, deleting Default). */\nexport class WorkspaceError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'WorkspaceError'\n }\n}\n\nconst MAX_NAME_LENGTH = 60\n\nexport class ProjectFolderError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ProjectFolderError'\n }\n}\n\n/** The canonical form of a project folder: absolute, no trailing separator. @throws ProjectFolderError for anything that is not an existing folder. */\nexport function normalizeProjectFolder(path: string): string {\n if (!isAbsolute(path)) throw new ProjectFolderError(`${path} is not an absolute path`)\n const folder = resolve(path)\n let stat\n try {\n stat = statSync(folder)\n } catch {\n throw new ProjectFolderError(`${folder} does not exist`)\n }\n if (!stat.isDirectory()) throw new ProjectFolderError(`${folder} is not a folder`)\n return folder\n}\n\nexport class ProjectRegistry {\n private readonly listeners = new Set<(view: ProjectRegistryView) => void>()\n\n constructor(private readonly scope: SettingsScope<ProjectsSection>) {}\n\n /** Observe every saved change, whoever made it (a page, an agent's tool). @returns disposer. */\n onChange(listener: (view: ProjectRegistryView) => void): () => void {\n this.listeners.add(listener)\n return () => { this.listeners.delete(listener) }\n }\n\n view(): ProjectRegistryView {\n const section = this.scope.get()\n const workspaces = this.workspaces()\n const current = this.current(workspaces)\n return {\n paths: [...current.projects],\n adopted: section.adopted,\n workspaces: workspaces.map(summary),\n current: current.id,\n }\n }\n\n /** Add a folder to the workspace shown. */\n async add(path: string): Promise<ProjectRegistryView> {\n const folder = normalizeProjectFolder(path)\n const workspaces = this.workspaces()\n const current = this.current(workspaces)\n if (current.projects.includes(folder)) return this.view()\n return this.save(workspaces.map(workspace => (workspace.id === current.id ? { ...workspace, projects: [...workspace.projects, folder] } : workspace)), current.id)\n }\n\n /** 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. */\n async remove(path: string): Promise<ProjectRegistryView> {\n const folder = resolve(path)\n const workspaces = this.workspaces()\n const current = this.current(workspaces)\n if (!current.projects.includes(folder)) return this.view()\n return this.save(workspaces.map(workspace => (workspace.id === current.id ? { ...workspace, projects: workspace.projects.filter(candidate => candidate !== folder) } : workspace)), current.id)\n }\n\n /** Take over folders registered elsewhere, once, into Default. Folders that no longer exist are skipped, not fatal. */\n async adopt(paths: readonly string[]): Promise<ProjectRegistryView> {\n if (this.scope.get().adopted) return this.view()\n const workspaces = this.workspaces()\n const merged = [...this.defaultOf(workspaces).projects]\n for (const path of paths) {\n try {\n const folder = normalizeProjectFolder(path)\n if (!merged.includes(folder)) merged.push(folder)\n } catch {\n // A project that has since been deleted is not carried over.\n }\n }\n return this.save(workspaces.map(workspace => (workspace.id === DEFAULT_WORKSPACE_ID ? { ...workspace, projects: merged } : workspace)), this.current(workspaces).id, true)\n }\n\n /** Create a workspace and show it. @throws WorkspaceError for an empty or taken name, or a remote one without a host. */\n async createWorkspace(input: { readonly name: string, readonly kind: WorkspaceKind, readonly remote?: RemoteTarget }): Promise<ProjectRegistryView> {\n const workspaces = this.workspaces()\n const name = this.validName(input.name, workspaces)\n const remote = input.kind === 'remote' ? validRemote(input.remote) : undefined\n const record: WorkspaceRecord = { id: `ws-${randomUUID().slice(0, 8)}`, name, kind: input.kind, projects: [], ...(remote === undefined ? {} : { remote }) }\n return this.save([...workspaces, record], record.id)\n }\n\n /** Show another workspace. */\n async switchWorkspace(id: string): Promise<ProjectRegistryView> {\n const workspaces = this.workspaces()\n this.find(workspaces, id)\n return this.save(workspaces, id)\n }\n\n async renameWorkspace(id: string, name: string): Promise<ProjectRegistryView> {\n const workspaces = this.workspaces()\n this.find(workspaces, id)\n const valid = this.validName(name, workspaces.filter(workspace => workspace.id !== id))\n return this.save(workspaces.map(workspace => (workspace.id === id ? { ...workspace, name: valid } : workspace)), this.current(workspaces).id)\n }\n\n /** Delete a workspace (never Default). Its projects stay in other workspaces and on disk; the sidebar shows Default if it was shown. */\n async deleteWorkspace(id: string): Promise<ProjectRegistryView> {\n if (id === DEFAULT_WORKSPACE_ID) throw new WorkspaceError('The Default workspace cannot be deleted.')\n const workspaces = this.workspaces()\n this.find(workspaces, id)\n const current = this.current(workspaces).id\n return this.save(workspaces.filter(workspace => workspace.id !== id), current === id ? DEFAULT_WORKSPACE_ID : current)\n }\n\n /** The workspaces, Default first; before the first workspace write, Default is built from the pre-workspace folder list. */\n private workspaces(): WorkspaceRecord[] {\n const section = this.scope.get()\n const stored = section.workspaces.map(({ remote, ...workspace }): WorkspaceRecord => ({\n ...workspace,\n projects: [...workspace.projects],\n ...(workspace.kind === 'remote' && remote !== undefined && typeof remote.host === 'string' && remote.host !== '' ? { remote } : {}),\n }))\n if (stored.some(workspace => workspace.id === DEFAULT_WORKSPACE_ID)) return stored\n return [{ id: DEFAULT_WORKSPACE_ID, name: 'Default', kind: 'individual', projects: [...section.projects] }, ...stored]\n }\n\n private current(workspaces: readonly WorkspaceRecord[]): WorkspaceRecord {\n const id = this.scope.get().current\n return workspaces.find(workspace => workspace.id === id) ?? this.defaultOf(workspaces)\n }\n\n private defaultOf(workspaces: readonly WorkspaceRecord[]): WorkspaceRecord {\n const found = workspaces.find(workspace => workspace.id === DEFAULT_WORKSPACE_ID)\n if (found === undefined) throw new WorkspaceError('The Default workspace is missing.')\n return found\n }\n\n private find(workspaces: readonly WorkspaceRecord[], id: string): WorkspaceRecord {\n const found = workspaces.find(workspace => workspace.id === id)\n if (found === undefined) throw new WorkspaceError(`There is no workspace \"${id}\".`)\n return found\n }\n\n private validName(raw: string, others: readonly WorkspaceRecord[]): string {\n const name = raw.trim()\n if (name === '') throw new WorkspaceError('A workspace needs a name.')\n if (name.length > MAX_NAME_LENGTH) throw new WorkspaceError(`A workspace name has at most ${String(MAX_NAME_LENGTH)} characters.`)\n if (others.some(workspace => workspace.name.toLowerCase() === name.toLowerCase())) throw new WorkspaceError(`There is already a workspace called \"${name}\".`)\n return name\n }\n\n /** One write: the workspaces become the only list (the pre-workspace one is emptied, its folders now in Default). */\n private async save(workspaces: readonly WorkspaceRecord[], current: string, adopted?: boolean): Promise<ProjectRegistryView> {\n await this.scope.update({ workspaces: [...workspaces], current, projects: [], ...(adopted === undefined ? {} : { adopted }) })\n const view = this.view()\n for (const listener of [...this.listeners]) listener(view)\n return view\n }\n}\n\nfunction summary(workspace: WorkspaceRecord): WorkspaceSummary {\n return {\n id: workspace.id,\n name: workspace.name,\n kind: workspace.kind,\n projects: [...workspace.projects],\n ...(workspace.remote === undefined ? {} : { remote: { ...workspace.remote } }),\n }\n}\n\nfunction validRemote(remote: RemoteTarget | undefined): RemoteTarget {\n const host = remote?.host.trim() ?? ''\n if (host === '') throw new WorkspaceError('A remote workspace needs the SSH host.')\n const user = remote?.user?.trim()\n const path = remote?.path?.trim()\n return { host, ...(user === undefined || user === '' ? {} : { user }), ...(path === undefined || path === '' ? {} : { path }) }\n}\n","/** The project registry, for the app's own page only: the list, its changes, and a stream of the list as it changes. */\n\nimport { Acryl } from '@acryldev/blends'\nimport { streamSSE } from '@acryldev/blends/streaming'\nimport { INVALID_JSON, failure, jsonBody, ownPage, readJson, type ReportError } from '../private-route.ts'\nimport {\n ProjectRequestError,\n WORKSPACE_PROJECTS_EVENTS_PATH,\n WORKSPACE_PROJECTS_PATH,\n parseProjectRequest,\n type ProjectRegistryView,\n type ProjectRequest,\n type ProjectResponse,\n} from './contract.ts'\nimport { ProjectFolderError, WorkspaceError, type ProjectRegistry } from './registry.ts'\n\n/** A comment line this often keeps an idle event stream open through proxies and the browser's own timeout. */\nconst KEEP_ALIVE_MS = 25_000\n\n/** One timer for every open stream, owned by the plugin's effect rather than by a request: `stop()` is its disposer. */\nexport interface KeepAlive {\n onBeat(listener: () => void): () => void\n stop(): void\n}\n\nexport function createKeepAlive(intervalMs: number = KEEP_ALIVE_MS): KeepAlive {\n const listeners = new Set<() => void>()\n const timer = setInterval(() => { for (const listener of listeners) listener() }, intervalMs)\n timer.unref()\n return {\n onBeat(listener) {\n listeners.add(listener)\n return () => { listeners.delete(listener) }\n },\n stop() {\n clearInterval(timer)\n listeners.clear()\n },\n }\n}\n\nfunction change(registry: ProjectRegistry, request: ProjectRequest): Promise<ProjectRegistryView> {\n switch (request.op) {\n case 'add': return registry.add(request.path)\n case 'remove': return registry.remove(request.path)\n case 'adopt': return registry.adopt(request.paths)\n case 'create-workspace': return registry.createWorkspace(request)\n case 'switch-workspace': return registry.switchWorkspace(request.id)\n case 'rename-workspace': return registry.renameWorkspace(request.id, request.name)\n case 'delete-workspace': return registry.deleteWorkspace(request.id)\n }\n}\n\n/**\n * GET `projects` (the list) and POST `{ op, ... }` to add, remove or adopt, a refusal being a 400 whose message says what to fix. GET\n * `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):\n * 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.\n */\nexport function projectRoutes(registry: ProjectRegistry, keepAlive: KeepAlive, reportError: ReportError): Acryl {\n return new Acryl()\n .get(WORKSPACE_PROJECTS_PATH, ownPage, c => c.json({ ok: true, view: registry.view() } satisfies ProjectResponse))\n .post(WORKSPACE_PROJECTS_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (body === INVALID_JSON) return c.json({ ok: false, code: 'invalid', message: 'invalid request body' } satisfies ProjectResponse, 400)\n try {\n const view = await change(registry, parseProjectRequest(body))\n return c.json({ ok: true, view } satisfies ProjectResponse)\n } catch (cause) {\n if (cause instanceof ProjectRequestError) return c.json({ ok: false, code: 'invalid', message: cause.message } satisfies ProjectResponse, 400)\n if (cause instanceof ProjectFolderError) return c.json({ ok: false, code: 'not-a-folder', message: cause.message } satisfies ProjectResponse, 400)\n if (cause instanceof WorkspaceError) return c.json({ ok: false, code: 'workspace', message: cause.message } satisfies ProjectResponse, 400)\n reportError('change the project list', cause)\n return c.json(failure('the project list could not be saved'), 500)\n }\n })\n .get(WORKSPACE_PROJECTS_EVENTS_PATH, ownPage, c => streamSSE(c, async (stream) => {\n const ended = new Promise<void>(resolve => { stream.onAbort(resolve) })\n // Writes are asynchronous; chaining them keeps messages in the order the list changed.\n let queue: Promise<unknown> = Promise.resolve()\n const enqueue = (write: () => Promise<unknown>): void => { queue = queue.then(write).catch(() => {}) }\n const send = (view: ProjectRegistryView): void => { enqueue(() => stream.writeSSE({ data: JSON.stringify(view) })) }\n send(registry.view())\n const stopFollowing = registry.onChange(send)\n const stopBeating = keepAlive.onBeat(() => { enqueue(() => stream.write(': keep-alive\\n\\n')) })\n try {\n await ended\n } finally {\n stopBeating()\n stopFollowing()\n }\n }))\n}\n","/**\n * Agent Control's workspace tools (spec 043 T007, spec 041's `workspace.*` vocabulary): typed tools provided by the package that owns the\n * project registry, so an agent lists, switches and creates workspaces and adds projects through the same registry the sidebar uses, with\n * its rules and refusals. Every open page follows the change through the registry's event stream. Creating a workspace and adding a\n * project are asked about every time; listing and switching are not (switching only changes what the sidebar shows, and is undone the same way).\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport { defineAcrylTool, type AcrylToolCall, type AcrylToolDecision } from '@acryldev/control'\nimport { WORKSPACE_KINDS, type ProjectRegistryView, type WorkspaceKind, type WorkspaceSummary } from './contract.ts'\nimport type { ProjectRegistry } from './registry.ts'\n\nexport const WORKSPACE_LIST_TOOL = 'acryl_workspace_list'\nexport const WORKSPACE_SWITCH_TOOL = 'acryl_workspace_switch'\nexport const WORKSPACE_CREATE_TOOL = 'acryl_workspace_create'\nexport const WORKSPACE_ADD_PROJECT_TOOL = 'acryl_workspace_add_project'\n\n/** The registry's view as the tools return it: every workspace, and which one is shown. */\nexport interface WorkspacesValue {\n readonly current: string\n readonly workspaces: readonly WorkspaceSummary[]\n}\n\nconst WORKSPACES_SCHEMA = {\n type: 'object', additionalProperties: false,\n properties: {\n current: { type: 'string', required: true },\n workspaces: {\n type: 'array', required: true,\n items: {\n type: 'object', additionalProperties: false,\n properties: {\n id: { type: 'string', required: true }, name: { type: 'string', required: true }, kind: { type: 'string', required: true },\n projects: { type: 'array', required: true, items: { type: 'string' } },\n remote: { type: 'object', additionalProperties: false, properties: { host: { type: 'string', required: true }, user: { type: 'string' }, path: { type: 'string' } } },\n },\n },\n },\n },\n} as const\n\nconst value = (view: ProjectRegistryView): WorkspacesValue => ({ current: view.current, workspaces: view.workspaces })\n\n/** What the model reads: one line per workspace, the shown one marked. */\nexport function renderWorkspaces(view: WorkspacesValue): string {\n return view.workspaces.map((workspace) => {\n const projects = workspace.projects.length === 0 ? 'no projects' : workspace.projects.join(', ')\n const remote = workspace.remote === undefined ? '' : ` (SSH ${workspace.remote.user === undefined ? '' : `${workspace.remote.user}@`}${workspace.remote.host})`\n return `${workspace.id === view.current ? '* ' : ' '}${workspace.name} [${workspace.id}, ${workspace.kind}]${remote}: ${projects}`\n }).join('\\n')\n}\n\nfunction isKind(candidate: string): candidate is WorkspaceKind {\n return (WORKSPACE_KINDS as readonly string[]).includes(candidate)\n}\n\n/** Words for the approval prompt. */\nexport function describeWorkspaceChange(name: string, args: unknown, view: ProjectRegistryView): string {\n const a = (typeof args === 'object' && args !== null ? args : {}) as Record<string, unknown>\n if (name === WORKSPACE_CREATE_TOOL) return `Create the workspace \"${String(a.name)}\" (${String(a.kind ?? 'individual')}) and show it`\n const shown = view.workspaces.find(workspace => workspace.id === view.current)?.name ?? view.current\n return `Add the folder ${String(a.path)} to the workspace \"${shown}\"`\n}\n\n/** Register the four tools and the approval for the two that add something. @returns disposer. */\nexport function registerWorkspaceTools(ctx: Context, registry: ProjectRegistry): () => void {\n const output = { schema: WORKSPACES_SCHEMA, render: (_args: unknown, view: WorkspacesValue) => [{ type: 'text' as const, text: renderWorkspaces(view) }] }\n\n const list = defineAcrylTool({\n name: WORKSPACE_LIST_TOOL,\n description: 'List the workspaces (sets of project folders in the sidebar), their projects, and the shown one (*).',\n parameters: {},\n output,\n execute: () => value(registry.view()),\n })\n\n const switchTo = defineAcrylTool({\n name: WORKSPACE_SWITCH_TOOL,\n description: 'Show another workspace by id (from acryl_workspace_list).',\n parameters: { id: { type: 'string', required: true } },\n output,\n execute: async args => value(await registry.switchWorkspace(args.id)),\n })\n\n const create = defineAcrylTool({\n name: WORKSPACE_CREATE_TOOL,\n description: 'Create a workspace and show it. kind: individual (default), shared (projects share context) or remote (SSH: host, optional user and path).',\n parameters: {\n name: { type: 'string', required: true },\n kind: { type: 'string' },\n host: { type: 'string' },\n user: { type: 'string' },\n path: { type: 'string' },\n },\n output,\n execute: async (args) => {\n const kind = args.kind ?? 'individual'\n if (!isKind(kind)) throw new Error(`unknown workspace kind \"${kind}\"; use individual, shared or remote`)\n const remote = kind === 'remote'\n ? { host: args.host ?? '', ...(args.user === undefined ? {} : { user: args.user }), ...(args.path === undefined ? {} : { path: args.path }) }\n : undefined\n return value(await registry.createWorkspace({ name: args.name, kind, ...(remote === undefined ? {} : { remote }) }))\n },\n })\n\n const addProject = defineAcrylTool({\n name: WORKSPACE_ADD_PROJECT_TOOL,\n description: 'Add a folder (absolute path) as a project of the shown workspace.',\n parameters: { path: { type: 'string', required: true } },\n output,\n execute: async args => value(await registry.add(args.path)),\n })\n\n const disposers = [list, switchTo, create, addProject].map(tool => ctx.acrylTools.register(tool))\n const removePolicy = ctx.acrylTools.policy(async (exec: AcrylToolCall, next: () => Promise<AcrylToolDecision>): Promise<AcrylToolDecision> => {\n const decision = await next()\n if ((exec.name !== WORKSPACE_CREATE_TOOL && exec.name !== WORKSPACE_ADD_PROJECT_TOOL) || decision.kind === 'deny') return decision\n return { kind: 'ask', reason: describeWorkspaceChange(exec.name, exec.arguments, registry.view()) }\n })\n return () => { removePolicy(); for (const dispose of disposers.reverse()) dispose() }\n}\n","/** The adapter that starts a real process behind a terminal with node-pty (a native module). */\n\nimport { spawn as spawnPty } from 'node-pty'\nimport type { WorkspacePtyProcess, WorkspacePtySpawn } from './service.ts'\n\nexport const spawnNodePty: WorkspacePtySpawn = (command, args, options): WorkspacePtyProcess =>\n spawnPty(command, [...args], {\n cwd: options.cwd,\n env: options.env as Record<string, string>,\n name: options.name,\n cols: options.cols,\n rows: options.rows,\n })\n","/** The workspace terminal routes: start, snapshot, input, resize and close, for the app's own page only. The output streams over the PTY WebSocket. */\n\nimport { Acryl } from '@acryldev/blends'\nimport { INVALID_JSON, failure, isRecord, jsonBody, ownPage, readJson, type ReportError } from '../private-route.ts'\nimport type { WorkspacePtyRegistry } from './service.ts'\nimport {\n WORKSPACE_PTY_CLOSE_PATH,\n WORKSPACE_PTY_INPUT_PATH,\n WORKSPACE_PTY_PATH,\n WORKSPACE_PTY_RESIZE_PATH,\n} from './contract.ts'\n\nconst START_KEYS = new Set(['commandId', 'cwd', 'cols', 'rows'])\n\n/**\n * GET `pty?id=` (the session's snapshot) and POST `pty` `{ commandId, cwd?, cols?, rows? }` (start one); POST `input` `{ id, data }`, `resize`\n * `{ id, cols, rows }` and `close` `{ id }` (idempotent) for a live session.\n */\nexport function ptyRoutes(registry: WorkspacePtyRegistry, reportError: ReportError): Acryl {\n return new Acryl()\n .get(WORKSPACE_PTY_PATH, ownPage, (c) => {\n const id = c.req.query('id')\n if (id === undefined || id.length === 0) return c.json(failure('invalid workspace PTY request'), 400)\n try {\n return c.json(registry.read(id))\n } catch (cause) {\n reportError('read workspace PTY', cause)\n return c.json(failure('unknown workspace PTY session'), 404)\n }\n })\n .post(WORKSPACE_PTY_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (body === INVALID_JSON || !isRecord(body) || Object.keys(body).some(key => !START_KEYS.has(key))\n || typeof body.commandId !== 'string' || body.commandId.length === 0 || body.commandId.length > 32\n || (body.cwd !== undefined && (typeof body.cwd !== 'string' || body.cwd.length === 0))) {\n return c.json(failure('invalid workspace PTY request'), 400)\n }\n const size = typeof body.cols === 'number' && typeof body.rows === 'number' ? { cols: body.cols, rows: body.rows } : undefined\n if ((body.cols !== undefined || body.rows !== undefined) && size === undefined) return c.json(failure('invalid workspace PTY request'), 400)\n try {\n return c.json(await registry.start(body.commandId, body.cwd as string | undefined, size))\n } catch (cause) {\n reportError('start workspace PTY', cause)\n return c.json(failure(cause instanceof Error ? cause.message : 'workspace PTY spawn failed'), 500)\n }\n })\n .post(WORKSPACE_PTY_INPUT_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (!isRecord(body) || typeof body.id !== 'string' || typeof body.data !== 'string' || Object.keys(body).length !== 2) {\n return c.json(failure('invalid workspace PTY input'), 400)\n }\n try {\n registry.write(body.id, body.data)\n return c.json({ accepted: true })\n } catch (cause) {\n reportError('write workspace PTY', cause)\n return c.json(failure('unknown workspace PTY session'), 404)\n }\n })\n .post(WORKSPACE_PTY_RESIZE_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (!isRecord(body) || typeof body.id !== 'string'\n || typeof body.cols !== 'number' || typeof body.rows !== 'number'\n || !Number.isInteger(body.cols) || !Number.isInteger(body.rows)\n || body.cols < 2 || body.cols > 500 || body.rows < 1 || body.rows > 200\n || Object.keys(body).length !== 3) {\n return c.json(failure('invalid workspace PTY resize'), 400)\n }\n try {\n registry.resize(body.id, body.cols, body.rows)\n return c.json({ accepted: true })\n } catch (cause) {\n reportError('resize workspace PTY', cause)\n return c.json(failure('unknown workspace PTY session'), 404)\n }\n })\n .post(WORKSPACE_PTY_CLOSE_PATH, ownPage, jsonBody(), async (c) => {\n const body = await readJson(c)\n if (!isRecord(body) || typeof body.id !== 'string' || Object.keys(body).length !== 1) return c.json(failure('invalid workspace PTY close'), 400)\n try {\n await registry.close(body.id)\n return c.json({ accepted: true })\n } catch (cause) {\n reportError('close workspace PTY', cause)\n return c.json(failure('workspace PTY could not be closed'), 500)\n }\n })\n}\n","/**\n * The hook settings ACRYL adds to a Claude Code launch so Claude reports what it is doing.\n *\n * They travel as `--settings <json>`, which Claude merges with the user's own settings; nothing is written to the\n * user's files. Each hook runs one `curl` to ACRYL's loopback status route. The secret and the terminal id are read\n * from the environment ACRYL gives that terminal, never written into the JSON. A failing or slow hook is silent\n * and can never block Claude (`-m 2`, `|| true`).\n */\n\nimport type { AgentState } from './agent-status.ts'\n\n/** The environment a status-reporting terminal is started with. */\nexport const STATUS_ENV = {\n terminal: 'ACRYL_TERMINAL_ID',\n url: 'ACRYL_STATUS_URL',\n token: 'ACRYL_STATUS_TOKEN',\n} as const\n\nconst report = (state: AgentState): string =>\n `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`\n\nconst hook = (state: AgentState, matcher?: string) => [{ ...(matcher === undefined ? {} : { matcher }), hooks: [{ type: 'command', command: report(state) }] }]\n\n/** @returns the JSON text for `claude --settings`. */\nexport function claudeStatusSettings(): string {\n return JSON.stringify({\n hooks: {\n UserPromptSubmit: hook('working'),\n // After an approved tool runs Claude is working again, though no prompt was submitted.\n PostToolUse: hook('working', '*'),\n Notification: hook('waiting'),\n Stop: hook('done'),\n },\n })\n}\n\n/** The extra launch arguments for an agent that reports through hooks. */\nexport function statusHookArgs(kind: 'claude'): readonly string[] {\n return kind === 'claude' ? ['--settings', claudeStatusSettings()] : []\n}\n","/**\n * The retained tail of one terminal's output, addressed by an ever-growing cursor.\n *\n * The cursor is the total number of characters the process has written, so a client that remembers the\n * cursor it reached can ask for exactly what it missed, with no gap and no repeat. Only the tail is kept;\n * a client that fell behind the kept part is told to start over from the tail instead.\n */\n\nexport interface Replay {\n /** Output from the requested cursor (or from the start of the kept tail when `replace`). */\n readonly data: string\n /** The cursor after `data`. */\n readonly cursor: number\n /** True when the client must clear its terminal first: what it missed is no longer kept. */\n readonly replace: boolean\n}\n\nconst DEFAULT_LIMIT = 1024 * 1024\n/** After a cut, look this far for a line break so the tail does not start in the middle of a line. */\nconst LINE_SEARCH = 4096\n\nexport class Scrollback {\n private tail = ''\n private start = 0\n\n constructor(private readonly limit: number = DEFAULT_LIMIT) {}\n\n /** Total characters ever appended. */\n get cursor(): number {\n return this.start + this.tail.length\n }\n\n append(chunk: string): void {\n if (chunk.length === 0) return\n this.tail += chunk\n if (this.tail.length <= this.limit) return\n let cut = this.tail.length - this.limit\n const lineBreak = this.tail.indexOf('\\n', cut)\n if (lineBreak !== -1 && lineBreak - cut < LINE_SEARCH) cut = lineBreak + 1\n this.tail = this.tail.slice(cut)\n this.start += cut\n }\n\n /** @param since - the cursor the client reached, or 0 for a fresh attach. */\n replay(since: number): Replay {\n if (since >= this.start && since <= this.cursor) {\n return { data: this.tail.slice(since - this.start), cursor: this.cursor, replace: false }\n }\n return { data: this.tail, cursor: this.cursor, replace: true }\n }\n}\n","/**\n * The Host's own picture of one terminal's screen.\n *\n * It is fed the same bytes the process writes, so at any moment it can say exactly what is on screen\n * (including a full-screen program's alternate screen, colours, and cursor position). A view that attaches\n * late, reconnects after a long gap, or reloads is given that picture instead of a replay of raw history,\n * which cannot reproduce a screen that was drawn by cursor movement.\n */\n\nimport serializeModule from '@xterm/addon-serialize'\nimport type { SerializeAddon as SerializeAddonType } from '@xterm/addon-serialize'\nimport headlessModule from '@xterm/headless'\nimport type { Terminal as HeadlessTerminal } from '@xterm/headless'\n\n// Both packages are CommonJS, whose named exports Node's ESM loader cannot see; take them from the default.\nconst { Terminal } = headlessModule\nconst { SerializeAddon } = serializeModule\n\nconst SCROLLBACK_LINES = 5000\n\nexport interface ScreenSnapshot {\n /** Escape sequences that redraw the screen and scrollback from empty. */\n readonly screen: string\n /** The cursor of the output this snapshot already includes. Anything after it is still to be sent. */\n readonly cursor: number\n}\n\nexport class ScreenModel {\n private readonly terminal: HeadlessTerminal\n private readonly serializer: SerializeAddonType = new SerializeAddon()\n private applied = 0\n\n constructor(cols: number, rows: number) {\n this.terminal = new Terminal({ cols, rows, scrollback: SCROLLBACK_LINES, allowProposedApi: true })\n this.terminal.loadAddon(this.serializer)\n }\n\n /** @param endCursor - the output cursor after this chunk, so a snapshot can say how far it reaches. */\n write(chunk: string, endCursor: number): void {\n // The terminal parses asynchronously; the snapshot only claims what the parser has really reached.\n this.terminal.write(chunk, () => { this.applied = endCursor })\n }\n\n resize(cols: number, rows: number): void {\n this.terminal.resize(cols, rows)\n }\n\n snapshot(): ScreenSnapshot {\n return { screen: this.serializer.serialize(), cursor: this.applied }\n }\n\n dispose(): void {\n this.terminal.dispose()\n }\n}\n","/** Host-owned ACRYL Workspace PTY sessions. UI observes; this module owns lifetime. */\n\nimport { spawn } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport { statSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { extname, isAbsolute, join } from 'node:path'\nimport type { AgentId, WorkspacePtyCommandId, WorkspacePtyStatus, WorkspacePtyView } from './contract.ts'\nimport { knownAgent } from '../agents/known-agents.ts'\nimport { STATUS_ENV, statusHookArgs } from '../agents/status/claude-hooks.ts'\nimport { MAX_PTY_COLS, MAX_PTY_ROWS, isWorkspacePtyCommandId } from './contract.ts'\nimport { Scrollback, type Replay } from './scrollback.ts'\nimport { ScreenModel } from './screen-model.ts'\n\nconst KILL_GRACE_MS = 1_000\nconst DEFAULT_COLS = 120\nconst DEFAULT_ROWS = 40\n\nconst PROBE_TIMEOUT_MS = 3_000\n\n/** What `shell args` printed on stdout, or `undefined` when it failed, timed out or could not start. Never blocks the event loop. */\nfunction probe(shell: string, args: readonly string[], env: NodeJS.ProcessEnv): Promise<string | undefined> {\n return new Promise((resolve) => {\n let out = ''\n let child: ReturnType<typeof spawn>\n try {\n child = spawn(shell, args, { env, stdio: ['ignore', 'pipe', 'ignore'], timeout: PROBE_TIMEOUT_MS, windowsHide: true })\n } catch {\n resolve(undefined)\n return\n }\n child.stdout?.setEncoding('utf8')\n child.stdout?.on('data', (chunk: string) => { out += chunk })\n child.on('error', () => { resolve(undefined) })\n child.on('close', (code) => { resolve(code === 0 ? out : undefined) })\n })\n}\n\nasync function lookUpSpawnDirs(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): Promise<readonly string[]> {\n const dirs: string[] = []\n const add = (raw: string | undefined): void => {\n if (raw === undefined) return\n for (const dir of raw.split(platform === 'win32' ? ';' : ':')) {\n if (dir.length > 0 && !dirs.includes(dir)) dirs.push(dir)\n }\n }\n add(env.PATH)\n const shell = env.SHELL ?? (platform === 'win32' ? env.ComSpec ?? 'cmd.exe' : '/bin/sh')\n const probes = platform === 'win32'\n ? [['/d', '/s', '/c', 'echo %PATH%']]\n : [['-lic', 'echo $PATH'], ['-lc', 'echo $PATH']]\n for (const args of probes) {\n const out = await probe(shell, args, env)\n // Log-in shell not available: keep the env PATH we already have.\n if (out === undefined) continue\n add(out.trimEnd())\n if (dirs.length > 0) break\n }\n return Object.freeze(dirs)\n}\n\n/** 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. */\nconst spawnDirsCache = new Map<string, Promise<readonly string[]>>()\n\n/**\n * A Finder-launched macOS app gets a minimal PATH (`/usr/bin:/bin:…`), so a\n * bare agent name such as `claude` fails to spawn even when it is installed.\n * Resolve bare commands to an absolute executable by merging `env.PATH` with\n * the user's login-shell PATH. The login shell is asked asynchronously (an\n * interactive zsh takes about a second, which must not stall the Host), once\n * per shell, home and PATH; callers wait for the answer.\n */\nexport function workspacePtySpawnDirs(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): Promise<readonly string[]> {\n const key = [platform, env.SHELL ?? env.ComSpec ?? '', env.HOME ?? env.USERPROFILE ?? '', env.PATH ?? ''].join('\\0')\n let dirs = spawnDirsCache.get(key)\n if (dirs === undefined) {\n dirs = lookUpSpawnDirs(env, platform)\n spawnDirsCache.set(key, dirs)\n }\n return dirs\n}\n\n/**\n * Return an absolute executable path for `command`, or `undefined` when none of\n * `dirs` contains an executable `command`. Absolute/relative paths pass through.\n */\nexport function resolveWorkspacePtyCommand(\n command: string,\n dirs: readonly string[],\n platform: NodeJS.Platform,\n): string | undefined {\n if (isAbsolute(command) || command.includes('/') || command.includes('\\\\')) return command\n // Windows runs only these; npm also puts an extensionless shell shim (`pi`) beside `pi.cmd`, and spawning that fails.\n const runnable = ['.exe', '.cmd', '.bat', '.com']\n const names = platform !== 'win32'\n ? [command]\n : runnable.includes(extname(command).toLowerCase()) ? [command] : runnable.map((ext) => `${command}${ext}`)\n for (const dir of dirs) {\n for (const name of names) {\n try {\n const candidate = join(dir, name)\n const stat = statSync(candidate)\n if (stat.isFile() && (platform === 'win32' || (stat.mode & 0o111) !== 0)) return candidate\n } catch {\n // Not present here; keep searching.\n }\n }\n }\n return undefined\n}\n\n/** The spawn cwd: process.cwd() when it exists, else the user's home directory. */\nfunction defaultSpawnCwd(): string {\n try {\n if (statSync(process.cwd()).isDirectory()) return process.cwd()\n } catch {\n // Fall through to the home directory.\n }\n return homedir()\n}\n\nexport interface WorkspacePtyProcess {\n onData(listener: (data: string) => void): { dispose(): void }\n onExit(listener: (event: { exitCode: number; signal?: number }) => void): { dispose(): void }\n write(data: string): void\n resize(cols: number, rows: number): void\n kill(signal?: string): void\n}\n\n/** PTY spawn injected so unit tests never launch a real process. */\nexport type WorkspacePtySpawn = (\n command: string,\n args: readonly string[],\n options: {\n readonly cwd: string\n readonly env: NodeJS.ProcessEnv\n readonly name: string\n readonly cols: number\n readonly rows: number\n },\n) => WorkspacePtyProcess\n\nexport interface WorkspacePtySpawnPlan {\n readonly command: string\n readonly args: readonly string[]\n /** Added to the terminal's environment for this launch. */\n readonly env?: Readonly<Record<string, string>>\n /** The agent reports its state through hooks of this kind; the registry adds the reporting when it can. */\n readonly statusHooks?: 'claude'\n}\n\n/** Says what an agent id runs: the user's settings for a known agent, or a custom agent's definition. */\nexport interface AgentResolver {\n resolve(id: string): WorkspacePtySpawnPlan | undefined\n}\n\n/** What an agent started in a folder is given beyond its own launch: the shared workspace context (spec 043), or nothing. */\nexport interface LaunchContextProvider {\n launchFor(agentId: string, cwd: string): { readonly args: readonly string[], readonly env: Readonly<Record<string, string>> } | undefined\n}\n\nexport interface WorkspacePtyRegistryOptions {\n readonly agents?: AgentResolver\n /** Looked up at each agent start, so the context is the workspace's as it is then. */\n readonly launchContext?: LaunchContextProvider\n /** Where agents report their state, and the secret they present. Without it no reporting is added. */\n readonly agentStatus?: { readonly url: string; readonly token: string }\n /** Starts a real process behind a terminal. Injected: the policy here never loads a native module. */\n readonly spawn: WorkspacePtySpawn\n readonly env?: NodeJS.ProcessEnv\n readonly cwd?: string\n readonly platform?: NodeJS.Platform\n readonly createId?: () => string\n}\n\ninterface LiveSession {\n readonly id: string\n readonly process: WorkspacePtyProcess\n readonly subscriptions: readonly { dispose(): void }[]\n status: WorkspacePtyStatus\n readonly scrollback: Scrollback\n readonly screen: ScreenModel\n readonly listeners: Set<(event: WorkspacePtyEvent) => void>\n exitCode: number | null\n error: string | null\n}\n\n/** What a live subscriber to one session is told. */\nexport type WorkspacePtyEvent =\n | { readonly kind: 'data'; readonly data: string; readonly cursor: number }\n | { readonly kind: 'exit'; readonly exitCode: number | null; readonly error: string | null }\n\n/**\n * Resolve argv for one allowlisted workspace command.\n * @param commandId - catalog id from the tab.\n * @param platform - Host process.platform.\n * @param env - environment used to pick SHELL / ComSpec.\n */\nexport function planWorkspacePtyCommand(\n commandId: WorkspacePtyCommandId,\n platform: NodeJS.Platform,\n env: NodeJS.ProcessEnv,\n): WorkspacePtySpawnPlan {\n if (commandId === 'shell') {\n if (platform === 'win32') {\n return { command: env.ComSpec ?? 'cmd.exe', args: [] }\n }\n return { command: env.SHELL ?? '/bin/sh', args: [] }\n }\n return { command: commandId, args: [] }\n}\n\n/**\n * The environment a terminal process starts with: a real terminal type, true color, and a UTF-8 locale\n * (an app launched from Finder has none, which makes shells and TUIs draw wrong glyphs).\n */\nexport function terminalEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const locale = env.LC_ALL ?? env.LC_CTYPE ?? env.LANG\n return {\n ...env,\n TERM: env.TERM ?? 'xterm-256color',\n COLORTERM: env.COLORTERM ?? 'truecolor',\n TERM_PROGRAM: 'ACRYL',\n ...(locale === undefined || !/utf-?8/i.test(locale) ? { LANG: 'en_US.UTF-8' } : {}),\n }\n}\n\nfunction isExistingAbsoluteDirectory(path: string): boolean {\n if (path.length === 0 || path.includes('\\0') || !isAbsolute(path)) return false\n try {\n return statSync(path).isDirectory()\n } catch {\n return false\n }\n}\n\n/** Table of live native PTY sessions for one ACRYL Workspace Host fiber. */\nexport class WorkspacePtyRegistry {\n private readonly sessions = new Map<string, LiveSession>()\n private readonly spawnImpl: WorkspacePtySpawn\n private readonly env: NodeJS.ProcessEnv\n private readonly cwd: string\n private readonly platform: NodeJS.Platform\n private readonly createId: () => string\n /** The search path for bare commands; the login shell's answer arrives after the registry is built (see {@link workspacePtySpawnDirs}). */\n private readonly spawnDirs: Promise<readonly string[]>\n private readonly agents: AgentResolver | undefined\n private readonly agentStatus: { readonly url: string; readonly token: string } | undefined\n private readonly launchContext: LaunchContextProvider | undefined\n /** Set by {@link disposeAll}: a start still waiting for the search path then spawns nothing. */\n private disposed = false\n\n constructor(options: WorkspacePtyRegistryOptions) {\n this.spawnImpl = options.spawn\n this.env = options.env ?? process.env\n this.cwd = options.cwd ?? defaultSpawnCwd()\n this.platform = options.platform ?? process.platform\n this.createId = options.createId ?? (() => `pty_${randomUUID()}`)\n this.spawnDirs = workspacePtySpawnDirs(this.env, this.platform)\n this.agents = options.agents\n this.agentStatus = options.agentStatus\n this.launchContext = options.launchContext\n }\n\n /**\n * Start one allowlisted command inside a real terminal.\n * @param commandId - catalog id from the Terminal/agent tab.\n * @param cwd - optional working directory (a worktree); must be an existing absolute directory.\n */\n async start(commandId: AgentId, cwd?: string, size?: { readonly cols: number; readonly rows: number }): Promise<WorkspacePtyView> {\n // The terminal is planned here; any other id is an agent, and the resolver (when there is one) knows the user's settings.\n const known = isWorkspacePtyCommandId(commandId) ? knownAgent(commandId) : undefined\n const agentPlan: WorkspacePtySpawnPlan | undefined = commandId === 'shell'\n ? undefined\n : this.agents?.resolve(commandId) ?? (known === undefined ? undefined : { command: known.command, args: [] })\n if (commandId !== 'shell' && agentPlan === undefined) {\n throw new Error('@acryldev/workspace: unknown workspace PTY command')\n }\n if (cwd !== undefined && !isExistingAbsoluteDirectory(cwd)) {\n throw new Error('@acryldev/workspace: workspace PTY cwd must be an existing absolute directory')\n }\n const cols = size?.cols ?? DEFAULT_COLS\n const rows = size?.rows ?? DEFAULT_ROWS\n if (!Number.isInteger(cols) || !Number.isInteger(rows) || cols < 2 || cols > MAX_PTY_COLS || rows < 1 || rows > MAX_PTY_ROWS) {\n throw new Error('@acryldev/workspace: workspace PTY size is out of range')\n }\n const plan: WorkspacePtySpawnPlan = agentPlan ?? planWorkspacePtyCommand('shell', this.platform, this.env)\n const dirs = await this.spawnDirs\n if (this.disposed) throw new Error('@acryldev/workspace: workspace PTY registry is disposed')\n const id = this.createId()\n let process: WorkspacePtyProcess\n try {\n const resolved = resolveWorkspacePtyCommand(plan.command, dirs, this.platform)\n if (resolved === undefined && !plan.command.includes('/') && !plan.command.includes('\\\\')) {\n throw new Error(`workspace PTY command not found in PATH: ${plan.command}`)\n }\n // An agent that reports through hooks gets the reporting launch settings and the terminal's own credentials.\n const reporting = plan.statusHooks !== undefined && this.agentStatus !== undefined\n // In a Shared Context workspace an agent also gets the workspace's context, in its own way; the shell gets nothing.\n const shared = commandId === 'shell' ? undefined : this.launchContext?.launchFor(commandId, cwd ?? this.cwd)\n const args = [...(reporting && plan.statusHooks !== undefined ? statusHookArgs(plan.statusHooks) : []), ...(shared?.args ?? []), ...plan.args]\n const reportingEnv = reporting && this.agentStatus !== undefined\n ? { [STATUS_ENV.terminal]: id, [STATUS_ENV.url]: this.agentStatus.url, [STATUS_ENV.token]: this.agentStatus.token }\n : {}\n process = this.spawnImpl(resolved ?? plan.command, args, {\n cwd: cwd ?? this.cwd,\n env: { ...terminalEnvironment(this.env), ...plan.env, ...shared?.env, ...reportingEnv },\n name: 'xterm-256color',\n cols,\n rows,\n })\n } catch (cause) {\n throw new Error(\n `@acryldev/workspace: workspace PTY spawn failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n )\n }\n const subscriptions: { dispose(): void }[] = []\n const session: LiveSession = {\n id,\n process,\n subscriptions,\n status: 'running',\n scrollback: new Scrollback(),\n screen: new ScreenModel(cols, rows),\n listeners: new Set(),\n exitCode: null,\n error: null,\n }\n subscriptions.push(process.onData((chunk) => {\n session.scrollback.append(chunk)\n session.screen.write(chunk, session.scrollback.cursor)\n const event: WorkspacePtyEvent = { kind: 'data', data: chunk, cursor: session.scrollback.cursor }\n for (const listener of [...session.listeners]) listener(event)\n }))\n subscriptions.push(process.onExit(({ exitCode, signal }) => {\n session.status = 'exited'\n session.exitCode = exitCode\n if (session.error === null && signal !== undefined && signal !== 0) {\n session.error = `signal ${String(signal)}`\n }\n const event: WorkspacePtyEvent = { kind: 'exit', exitCode: session.exitCode, error: session.error }\n for (const listener of [...session.listeners]) listener(event)\n }))\n this.sessions.set(id, session)\n return this.view(session)\n }\n\n /** True when a live terminal has this id. */\n has(id: string): boolean {\n return this.sessions.has(id)\n }\n\n /** True when `command` is an absolute executable file or a program on the search path. */\n async canRun(command: string): Promise<boolean> {\n if (isAbsolute(command)) {\n try {\n const info = statSync(command)\n return info.isFile() && (this.platform === 'win32' || (info.mode & 0o111) !== 0)\n } catch {\n return false\n }\n }\n return resolveWorkspacePtyCommand(command, await this.spawnDirs, this.platform) !== undefined\n }\n\n /** Write exact terminal input bytes. */\n write(id: string, data: string): void {\n const session = this.require(id)\n if (session.status !== 'running') {\n throw new Error('@acryldev/workspace: workspace PTY is not running')\n }\n session.process.write(data)\n }\n\n /** Resize one live terminal. */\n resize(id: string, cols: number, rows: number): void {\n const session = this.require(id)\n if (session.status !== 'running') return\n session.process.resize(cols, rows)\n session.screen.resize(cols, rows)\n }\n\n /**\n * Follow one session live. `replay` is what the subscriber has not seen yet (from `since`, or the kept\n * tail when it missed more than is kept); everything after it arrives through `listener`, in order,\n * with nothing lost or repeated in between.\n * @param since - the cursor the subscriber already reached, 0 for a first attach.\n */\n subscribe(id: string, since: number, listener: (event: WorkspacePtyEvent) => void): {\n readonly replay: Replay\n readonly status: WorkspacePtyStatus\n readonly exitCode: number | null\n readonly error: string | null\n dispose(): void\n } {\n const session = this.require(id)\n session.listeners.add(listener)\n return {\n replay: this.replayFor(session, since),\n status: session.status,\n exitCode: session.exitCode,\n error: session.error,\n dispose: () => { session.listeners.delete(listener) },\n }\n }\n\n /**\n * A subscriber that can resume from its cursor gets just what it missed. Any other (first attach,\n * reload, a gap larger than the kept tail) gets the screen as it is now, then what was written since.\n */\n private replayFor(session: LiveSession, since: number): Replay {\n if (since > 0) {\n const direct = session.scrollback.replay(since)\n if (!direct.replace) return direct\n }\n const { screen, cursor } = session.screen.snapshot()\n const tail = session.scrollback.replay(cursor)\n return tail.replace\n ? tail\n : { data: screen + tail.data, cursor: tail.cursor, replace: true }\n }\n\n /** Snapshot one session for the renderer. */\n read(id: string): WorkspacePtyView {\n return this.view(this.require(id))\n }\n\n /** Stop one session. Idempotent. */\n async close(id: string): Promise<void> {\n const session = this.sessions.get(id)\n if (session === undefined) return\n await stopPty(session)\n for (const subscription of session.subscriptions) subscription.dispose()\n session.screen.dispose()\n this.sessions.delete(id)\n }\n\n /** Stop every session owned by this fiber. */\n async disposeAll(): Promise<void> {\n this.disposed = true\n const ids = [...this.sessions.keys()]\n await Promise.all(ids.map(async id => this.close(id)))\n }\n\n private require(id: string): LiveSession {\n const session = this.sessions.get(id)\n if (session === undefined) {\n throw new Error('@acryldev/workspace: unknown workspace PTY session')\n }\n return session\n }\n\n private view(session: LiveSession): WorkspacePtyView {\n return {\n id: session.id,\n status: session.status,\n output: session.scrollback.replay(0).data,\n exitCode: session.exitCode,\n error: session.error,\n }\n }\n}\n\nasync function stopPty(session: LiveSession): Promise<void> {\n if (session.status !== 'running') return\n await new Promise<void>((resolve) => {\n let done = false\n const finish = (): void => {\n if (done) return\n done = true\n clearTimeout(timer)\n exitSubscription.dispose()\n resolve()\n }\n const exitSubscription = session.process.onExit(finish)\n const timer = setTimeout(() => {\n try {\n session.process.kill('SIGKILL')\n } catch {\n // The PTY may have exited between the status check and timeout.\n }\n finish()\n }, KILL_GRACE_MS)\n timer.unref?.()\n try {\n session.process.kill()\n } catch {\n finish()\n }\n })\n}\n","/**\n * The live terminal stream: one WebSocket per open terminal view, on the framework's router.\n *\n * Output goes down and keystrokes and size changes go up over one ordered connection, so nothing is\n * polled, nothing is re-sent, and two keystrokes can never arrive swapped. The route is an ordinary router\n * route: the own-page rule that guards the HTTP routes runs before the upgrade, with the exact `Origin` a\n * socket must show (a WebSocket is not covered by the same-origin policy on its own), and a refusal is a\n * plain status before any handshake. The framework's hub owns the sockets: it pings them, ends dead peers,\n * and closes them with 1001 when the plugin unloads.\n */\n\nimport { Acryl, type MiddlewareHandler } from '@acryldev/blends'\nimport type { UpgradeWebSocket, WSContext, WSEvents } from '@acryldev/blends/ws'\nimport { failure, ownPageSocket, type ReportError } from '../private-route.ts'\nimport { WORKSPACE_PTY_STREAM_PATH, parsePtyClientMessage, type PtyServerMessage } from './contract.ts'\nimport type { WorkspacePtyRegistry } from './service.ts'\n\n/** Output is sent in batches this far apart, so a burst of small writes becomes one frame. */\nconst BATCH_MS = 4\n/** When the socket already holds this much unsent data, wait instead of piling on. */\nconst BACKPRESSURE_BYTES = 1024 * 1024\n/** A client this far behind is dropped; it reconnects and resumes from its cursor. */\nconst MAX_PENDING_CHARS = 8 * 1024 * 1024\n\n/** A well-formed attach request: the session and the cursor its view already shows. */\nconst validAttach: MiddlewareHandler = async (c, next) => {\n const id = c.req.query('id')\n const since = c.req.query('since') ?? '0'\n if (id === undefined || id.length === 0 || !/^\\d{1,15}$/.test(since)) return c.json(failure('invalid terminal stream request'), 400)\n await next()\n}\n\n/** One open view of session `id`, from cursor `since`: the replay, then live output; its input is written to the session. */\nfunction attach(registry: WorkspacePtyRegistry, id: string, since: number): WSEvents {\n let subscription: ReturnType<WorkspacePtyRegistry['subscribe']> | undefined\n let pending = ''\n let pendingCursor = 0\n let timer: NodeJS.Timeout | undefined\n return {\n onOpen(_event, ws) {\n const send = (message: PtyServerMessage): void => {\n if (ws.readyState === 1) ws.send(JSON.stringify(message))\n }\n const flush = (): void => {\n timer = undefined\n if (pending === '') return\n if (ws.bufferedAmount > BACKPRESSURE_BYTES) {\n timer = setTimeout(flush, BATCH_MS * 2)\n return\n }\n send({ t: 'out', data: pending, cursor: pendingCursor, replace: false })\n pending = ''\n }\n try {\n subscription = registry.subscribe(id, since, (event) => {\n if (event.kind === 'data') {\n pending += event.data\n pendingCursor = event.cursor\n if (pending.length > MAX_PENDING_CHARS) { ws.close(1013, 'too slow'); return }\n timer ??= setTimeout(flush, BATCH_MS)\n return\n }\n if (timer !== undefined) clearTimeout(timer)\n flush()\n send({ t: 'exit', exitCode: event.exitCode, error: event.error })\n })\n } catch {\n ws.close(4404, 'unknown session')\n return\n }\n const { replay } = subscription\n if (replay.replace || replay.data.length > 0) send({ t: 'out', data: replay.data, cursor: replay.cursor, replace: replay.replace })\n if (subscription.status !== 'running') send({ t: 'exit', exitCode: subscription.exitCode, error: subscription.error })\n },\n onMessage(event, ws: WSContext) {\n if (subscription === undefined) return\n const message = typeof event.data === 'string' ? parsePtyClientMessage(event.data) : null\n if (message === null) { ws.close(1008, 'invalid message'); return }\n try {\n if (message.t === 'in') registry.write(id, message.data)\n else registry.resize(id, message.cols, message.rows)\n } catch {\n // The process already exited; the exit message has been or will be sent.\n }\n },\n onClose() {\n if (timer !== undefined) clearTimeout(timer)\n subscription?.dispose()\n },\n }\n}\n\n/**\n * GET {@link WORKSPACE_PTY_STREAM_PATH}`?id=&since=` upgraded to the session's stream. `upgrade` is the mounting plugin's\n * `ctx.routerHttp.upgrades()`, so the sockets belong to it; the path must be one the plugin mounted with `upgrade: [path]`.\n */\nexport function ptyStreamRoutes(registry: WorkspacePtyRegistry, upgrade: UpgradeWebSocket, reportError: ReportError): Acryl {\n return new Acryl().get(\n WORKSPACE_PTY_STREAM_PATH,\n ownPageSocket,\n validAttach,\n upgrade((c) => {\n const events = attach(registry, c.req.query('id') ?? '', Number(c.req.query('since') ?? '0'))\n return { ...events, onError: (event) => { reportError('terminal stream', event instanceof ErrorEvent ? event.error : event) } }\n }, { textOnly: true, onError: (cause: unknown) => { reportError('terminal stream', cause) } }),\n )\n}\n","/**\n * The DSH chat's share of the workspace context (spec 043 T010): a `systemPrompt.context` contribution, the harness's dynamic context that is\n * recorded as a durable user-role snapshot per assembly (so a change does not invalidate the cached system prompt). It is keyed by the\n * session's own folder, so a chat in a Shared Context workspace is told about its projects and any other chat gets nothing.\n */\n\n/** The share of DSH's `systemPrompt` service used here (the harness types are not a dependency of this package). */\nexport interface SystemPromptContextPort {\n context(context: { readonly name: string, readonly order: number, readonly text: (assembly: AssemblyLike) => string }): () => void\n}\n\n/** The share of an assembly read here: the session whose prompt is being assembled. */\nexport interface AssemblyLike {\n readonly agent?: { readonly session?: { readonly header?: { readonly cwd?: unknown } } }\n}\n\nexport const WORKSPACE_CONTEXT_NAME = 'acryl:workspace'\n/** After the harness's own runtime contexts (sandbox 110, approval 115, subagents 120). */\nexport const WORKSPACE_CONTEXT_ORDER = 130\n\n/** @returns the prompt block for the session's folder, or '' (no contribution) outside a Shared Context workspace. */\nexport function chatContextText(contextFor: (folder: string) => { readonly prompt: string } | undefined, assembly: AssemblyLike): string {\n const cwd = assembly.agent?.session?.header?.cwd\n return typeof cwd === 'string' && cwd !== '' ? contextFor(cwd)?.prompt ?? '' : ''\n}\n\n/** Register the contribution. @returns disposer. */\nexport function registerChatContext(systemPrompt: SystemPromptContextPort, contextFor: (folder: string) => { readonly prompt: string } | undefined): () => void {\n return systemPrompt.context({ name: WORKSPACE_CONTEXT_NAME, order: WORKSPACE_CONTEXT_ORDER, text: assembly => chatContextText(contextFor, assembly) })\n}\n","/**\n * How a terminal agent started in a Shared Context workspace gets the context, in its own way (spec 043 T010). Only flags each agent\n * documents and its installed `--help` lists: Claude Code gets the other projects and the workspace folder (`--add-dir`) and the context\n * (`--append-system-prompt`); Pi gets the context; Codex gets the same folders (`--add-dir`) and the context as developer instructions\n * (`-c developer_instructions=...`, Codex 0.162). Every agent gets `ACRYL_WORKSPACE_CONTEXT`, the generated document's path.\n *\n * 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\n * kind, is started with. That is how a session moves between agents without adapting one agent to another.\n */\n\n/** The environment variable naming the workspace's generated context document. */\nexport const WORKSPACE_CONTEXT_ENV = 'ACRYL_WORKSPACE_CONTEXT'\n\nexport interface ContextLaunch {\n readonly args: readonly string[]\n readonly env: Readonly<Record<string, string>>\n}\n\nexport interface LaunchContext {\n readonly prompt: string\n readonly documentPath: string\n readonly otherProjects: readonly string[]\n /** `<home>/workspaces/<id>/`: the brief and the generated document. */\n readonly workspaceFolder: string\n}\n\n/** @returns the arguments and environment a known agent is started with in a shared workspace. */\nexport function contextLaunch(agentId: string, context: LaunchContext): ContextLaunch {\n const env = { [WORKSPACE_CONTEXT_ENV]: context.documentPath }\n const folders = [...context.otherProjects, context.workspaceFolder]\n switch (agentId) {\n case 'claude':\n // `--add-dir` takes every folder up to the next flag.\n return { args: ['--add-dir', ...folders, '--append-system-prompt', context.prompt], env }\n case 'pi':\n return { args: ['--append-system-prompt', context.prompt], env }\n case 'codex':\n // The value is parsed as TOML; a JSON string literal is a valid TOML basic string.\n return { args: [...folders.flatMap(folder => ['--add-dir', folder]), '-c', `developer_instructions=${JSON.stringify(context.prompt)}`], env }\n default:\n return { args: [], env }\n }\n}\n","/**\n * The shared context of a Shared Context workspace (spec 043), as text: what an agent is told about the workspace it works in. Pure: the\n * caller reads the files. Two shapes: the prompt block (inside a size budget, so it never floods a model's context) and the full document\n * written to `WORKSPACE.md`.\n */\n\nexport interface ContextProject {\n readonly name: string\n readonly path: string\n /** The project's own agent instructions present at its root (`CLAUDE.md`, `AGENTS.md`, `README.md`), referenced, never copied. */\n readonly instructions: readonly string[]\n}\n\nexport interface ContextInput {\n readonly name: string\n readonly projects: readonly ContextProject[]\n /** The workspace brief, as the user wrote it; empty when there is none. */\n readonly brief: string\n /** Where the full document is, for the agent to read. */\n readonly documentPath: string\n /** Where the brief is, for the agent to know what it may edit. */\n readonly briefPath: string\n}\n\n/** The prompt block's size, in characters (about 900 tokens). */\nexport const CONTEXT_PROMPT_BUDGET = 3200\n/** The XML-style tag of the prompt block, in the style of the other ACRYL sections. */\nexport const CONTEXT_TAG = 'acryl_workspace'\n\nfunction projectLines(projects: readonly ContextProject[]): string[] {\n if (projects.length === 0) return ['- (no projects yet)']\n return projects.map(project => `- ${project.name}: ${project.path}${project.instructions.length === 0 ? '' : ` (instructions: ${project.instructions.join(', ')})`}`)\n}\n\n/** The block the DSH chat and terminal agents get. The brief is cut to fit the budget, and says so. */\nexport function renderContextPrompt(input: ContextInput, budget = CONTEXT_PROMPT_BUDGET): string {\n const head = [\n `<${CONTEXT_TAG}>`,\n `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.`,\n 'Projects:',\n ...projectLines(input.projects),\n ]\n const tail = [`Full context: ${input.documentPath}. The brief is ${input.briefPath} (the user's; edit it only when asked).`, `</${CONTEXT_TAG}>`]\n const brief = input.brief.trim()\n if (brief === '') return [...head, ...tail].join('\\n')\n // What is left for the brief: the block without it, plus the one line break that joins the brief in.\n const room = budget - [...head, 'Brief:', ...tail].join('\\n').length - 1\n const note = '\\n(brief cut here; the rest is in the file)'\n if (room <= note.length + 40) return [...head, ...tail].join('\\n')\n const cut = brief.length <= room ? brief : `${brief.slice(0, room - note.length).trimEnd()}${note}`\n return [...head, 'Brief:', cut, ...tail].join('\\n')\n}\n\n/** The whole document written to `WORKSPACE.md`: the brief in full. */\nexport function renderContextDocument(input: ContextInput): string {\n const brief = input.brief.trim()\n return [\n `# Workspace: ${input.name}`,\n '',\n 'Generated by ACRYL for every agent working in this shared-context workspace. Do not edit: it is rewritten when the workspace changes.',\n `The brief is ${input.briefPath}.`,\n '',\n '## Projects',\n '',\n ...projectLines(input.projects),\n '',\n '## Brief',\n '',\n brief === '' ? '(none yet)' : brief,\n '',\n ].join('\\n')\n}\n","/**\n * `SharedContext`: which Shared Context workspace a folder works in, and what an agent there is told (spec 043 T009). It keeps\n * `<home>/workspaces/<id>/WORKSPACE.md` current for every shared workspace and holds each workspace's brief (`BRIEF.md`, the user's).\n * Provided as the `acrylSharedContext` service, so another mechanism can replace it (FR-005).\n */\n\nimport { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs'\nimport { basename, dirname, join, resolve } from 'node:path'\nimport type { ProjectRegistryView, WorkspaceSummary } from '../projects/contract.ts'\nimport { contextLaunch, type ContextLaunch } from './launch.ts'\nimport { renderContextDocument, renderContextPrompt, type ContextInput } from './render.ts'\n\n/** The service name other plugins read. */\nexport const SHARED_CONTEXT_SERVICE = 'acrylSharedContext'\n\n/** A brief longer than this is refused: it is a page of notes, not a store. */\nexport const MAX_BRIEF_CHARS = 100_000\n\nconst INSTRUCTION_FILES = ['CLAUDE.md', 'AGENTS.md', 'README.md'] as const\n\nexport interface SharedContextRegistry {\n view(): ProjectRegistryView\n onChange(listener: (view: ProjectRegistryView) => void): () => void\n}\n\n/** What a terminal agent or the chat gets for one workspace. */\nexport interface WorkspaceContext {\n readonly workspace: WorkspaceSummary\n /** The prompt block (within the budget). */\n readonly prompt: string\n /** The generated document's path. */\n readonly documentPath: string\n /** The workspace's projects other than the one the agent starts in. */\n readonly otherProjects: (folder: string) => readonly string[]\n}\n\n/** `path` is `folder` or below it, with either separator. */\nexport function isInside(path: string, folder: string): boolean {\n if (path === folder) return true\n const base = folder.replace(/[\\\\/]+$/u, '')\n return path.startsWith(`${base}/`) || path.startsWith(`${base}\\\\`)\n}\n\n/**\n * The checkout a folder belongs to: the nearest folder above it with `.git`; for a linked worktree (`.git` is a file pointing into\n * `<main>/.git/worktrees/<name>`), the main checkout. Synchronous and git-free, so a prompt provider can call it. The main checkout is spelled\n * the way git wrote it (on Windows long names and `/`, turned into native separators here), so compare it with `samePlaceOrInside`, not as text.\n */\nexport function checkoutOf(folder: string): string | undefined {\n for (let current = resolve(folder); ; current = dirname(current)) {\n const marker = join(current, '.git')\n if (existsSync(marker)) {\n try {\n if (statSync(marker).isFile()) {\n const pointer = /^gitdir:\\s*(.+)$/mu.exec(readFileSync(marker, 'utf8'))?.[1]?.trim()\n const at = pointer?.search(/[\\\\/]\\.git[\\\\/]worktrees[\\\\/]/u) ?? -1\n if (pointer !== undefined && at > 0) return resolve(pointer.slice(0, at))\n }\n } catch {\n // An unreadable marker: the folder itself is the checkout.\n }\n return current\n }\n if (dirname(current) === current) return undefined\n }\n}\n\n/** A path as the file system names it (Windows 8.3 short names, letter case and symlinks resolved); a missing path only resolved. */\nfunction canonical(path: string): string {\n try {\n return realpathSync.native(path)\n } catch {\n return resolve(path)\n }\n}\n\n/** `path` is `folder` or below it, however each is spelled (see `canonical`). */\nexport function samePlaceOrInside(path: string, folder: string): boolean {\n return isInside(path, folder) || isInside(canonical(path), canonical(folder))\n}\n\nexport class SharedContext {\n constructor(private readonly deps: { readonly registry: SharedContextRegistry, readonly home: string }) {}\n\n /** `<home>/workspaces/<id>/`. */\n folder(id: string): string {\n return join(this.deps.home, 'workspaces', id)\n }\n\n briefPath(id: string): string {\n return join(this.folder(id), 'BRIEF.md')\n }\n\n documentPath(id: string): string {\n return join(this.folder(id), 'WORKSPACE.md')\n }\n\n /**\n * The Shared Context workspace an agent working in `folder` belongs to: the shown workspace when it is shared and holds the folder, else\n * the first shared one that does; `undefined` in an Individual Projects workspace (nothing crosses projects there).\n */\n forFolder(folder: string): WorkspaceSummary | undefined {\n const view = this.deps.registry.view()\n const checkout = checkoutOf(folder)\n const places = checkout === undefined ? [folder] : [folder, checkout]\n const holds = (workspace: WorkspaceSummary): boolean => workspace.kind === 'shared' && workspace.projects.some(project => places.some(place => samePlaceOrInside(place, project)))\n const shown = view.workspaces.find(workspace => workspace.id === view.current)\n if (shown !== undefined && holds(shown)) return shown\n return view.workspaces.find(holds)\n }\n\n /** What an agent working in `folder` is told, or `undefined` outside a Shared Context workspace. */\n contextFor(folder: string): WorkspaceContext | undefined {\n const workspace = this.forFolder(folder)\n if (workspace === undefined) return undefined\n return {\n workspace,\n prompt: renderContextPrompt(this.input(workspace)),\n documentPath: this.documentPath(workspace.id),\n otherProjects: (start: string) => {\n const checkout = checkoutOf(start) ?? start\n return workspace.projects.filter(project => !samePlaceOrInside(start, project) && !samePlaceOrInside(checkout, project))\n },\n }\n }\n\n /** What a terminal agent started in `cwd` is given (`WorkspacePtyRegistry`'s launch context): nothing outside a shared workspace. */\n launchFor(agentId: string, cwd: string): ContextLaunch | undefined {\n const context = this.contextFor(cwd)\n if (context === undefined) return undefined\n return contextLaunch(agentId, { prompt: context.prompt, documentPath: context.documentPath, otherProjects: context.otherProjects(cwd), workspaceFolder: this.folder(context.workspace.id) })\n }\n\n /** The prompt block for a workspace by id (the tool's answer), or `undefined` when it is not a shared workspace. */\n promptFor(id: string): string | undefined {\n const workspace = this.deps.registry.view().workspaces.find(candidate => candidate.id === id)\n return workspace?.kind === 'shared' ? renderContextPrompt(this.input(workspace)) : undefined\n }\n\n brief(id: string): string {\n try {\n return readFileSync(this.briefPath(id), 'utf8')\n } catch {\n return ''\n }\n }\n\n /** Save a workspace's brief and rewrite its document. @throws when the workspace does not exist or the brief is too long. */\n setBrief(id: string, text: string): void {\n const workspace = this.deps.registry.view().workspaces.find(candidate => candidate.id === id)\n if (workspace === undefined) throw new Error(`there is no workspace ${id}`)\n if (text.length > MAX_BRIEF_CHARS) throw new Error(`the brief is longer than ${String(MAX_BRIEF_CHARS)} characters`)\n writeAtomically(this.briefPath(id), text)\n if (workspace.kind === 'shared') writeAtomically(this.documentPath(id), renderContextDocument(this.input(workspace)))\n }\n\n /** Rewrite `WORKSPACE.md` for every shared workspace. */\n writeDocuments(view: ProjectRegistryView = this.deps.registry.view()): void {\n for (const workspace of view.workspaces) {\n if (workspace.kind === 'shared') writeAtomically(this.documentPath(workspace.id), renderContextDocument(this.input(workspace)))\n }\n }\n\n /** Keep the documents current as the registry changes. @returns disposer, for one owning effect. */\n start(report: (cause: unknown) => void): () => void {\n const write = (view?: ProjectRegistryView): void => {\n try { this.writeDocuments(view) } catch (cause) { report(cause) }\n }\n write()\n return this.deps.registry.onChange(write)\n }\n\n private input(workspace: WorkspaceSummary): ContextInput {\n return {\n name: workspace.name,\n projects: workspace.projects.map(path => ({\n name: basename(path),\n path,\n instructions: INSTRUCTION_FILES.filter(file => existsSync(join(path, file))),\n })),\n brief: this.brief(workspace.id),\n documentPath: this.documentPath(workspace.id),\n briefPath: this.briefPath(workspace.id),\n }\n }\n}\n\nfunction writeAtomically(path: string, text: string): void {\n mkdirSync(dirname(path), { recursive: true })\n const temporary = `${path}.${String(process.pid)}.tmp`\n writeFileSync(temporary, text)\n renameSync(temporary, path)\n}\n","/** 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. */\n\nimport { Acryl } from '@acryldev/blends'\nimport { bodyLimit } from '@acryldev/blends/body-limit'\nimport { INVALID_JSON, ownPage, readJson, WORKSPACE_API_PREFIX } from '../private-route.ts'\nimport { MAX_BRIEF_CHARS, type SharedContext } from './service.ts'\n\nexport const WORKSPACE_BRIEF_PATH = `${WORKSPACE_API_PREFIX}/brief`\n\nexport type BriefResponse =\n | { readonly ok: true, readonly id: string, readonly text: string }\n | { readonly ok: false, readonly message: string }\n\nconst ID = /^[A-Za-z0-9_-]{1,64}$/u\n\nexport function briefRoutes(shared: SharedContext): Acryl {\n return new Acryl()\n .get(WORKSPACE_BRIEF_PATH, ownPage, (c) => {\n const id = c.req.query('id') ?? ''\n if (!ID.test(id)) return c.json({ ok: false, message: 'a workspace id is required' } satisfies BriefResponse, 400)\n return c.json({ ok: true, id, text: shared.brief(id) } satisfies BriefResponse)\n })\n .post(\n WORKSPACE_BRIEF_PATH,\n ownPage,\n bodyLimit({ maxSize: MAX_BRIEF_CHARS * 4 + 1024, onError: c => c.json({ ok: false, message: 'the brief is too long' } satisfies BriefResponse, 413) }),\n async (c) => {\n const body = await readJson(c)\n if (body === INVALID_JSON) return c.json({ ok: false, message: 'invalid request body' } satisfies BriefResponse, 400)\n const { id, text } = (typeof body === 'object' && body !== null ? body : {}) as { id?: unknown, text?: unknown }\n if (typeof id !== 'string' || !ID.test(id) || typeof text !== 'string') return c.json({ ok: false, message: 'send { id, text }' } satisfies BriefResponse, 400)\n try {\n shared.setBrief(id, text)\n return c.json({ ok: true, id, text } satisfies BriefResponse)\n } catch (cause) {\n return c.json({ ok: false, message: cause instanceof Error ? cause.message : String(cause) } satisfies BriefResponse, 400)\n }\n },\n )\n}\n","/**\n * `acryl_workspace_context` (spec 043 T011): any agent reads a Shared Context workspace's context, through the tool registry the DSH chat\n * uses and, for agents ACRYL does not run, the loopback tool gateway (it is on the gateway's default allowlist). Reading only.\n */\n\nimport type { Context } from '@deepseek-ai/cordis'\nimport { defineAcrylTool } from '@acryldev/control'\nimport type { ProjectRegistryView } from '../projects/contract.ts'\n\nexport const WORKSPACE_CONTEXT_TOOL = 'acryl_workspace_context'\n\nexport interface ContextToolValue {\n readonly workspace: string\n readonly shared: boolean\n readonly text: string\n}\n\nexport interface ContextToolDeps {\n view(): ProjectRegistryView\n promptFor(id: string): string | undefined\n}\n\n/** @returns the value for a workspace id, the shown one by default. */\nexport function readWorkspaceContext(deps: ContextToolDeps, id?: string): ContextToolValue {\n const view = deps.view()\n const workspace = id ?? view.current\n if (!view.workspaces.some(candidate => candidate.id === workspace)) throw new Error(`there is no workspace ${workspace}; call acryl_workspace_list`)\n const text = deps.promptFor(workspace)\n return text === undefined\n ? { workspace, shared: false, text: 'This workspace does not share context: its projects are separate.' }\n : { workspace, shared: true, text }\n}\n\n/** @returns disposer. */\nexport function registerContextTool(ctx: Context, deps: ContextToolDeps): () => void {\n return ctx.acrylTools.register(defineAcrylTool({\n name: WORKSPACE_CONTEXT_TOOL,\n description: 'Read a shared-context workspace\\'s projects and brief (default: the shown workspace).',\n parameters: { workspace: { type: 'string' } },\n output: {\n schema: {\n type: 'object', additionalProperties: false,\n properties: { workspace: { type: 'string', required: true }, shared: { type: 'boolean', required: true }, text: { type: 'string', required: true } },\n },\n render: (_args, value: ContextToolValue) => [{ type: 'text', text: value.text }],\n },\n execute: args => readWorkspaceContext(deps, args.workspace),\n }))\n}\n","/** Cordis Host plugin: ACRYL Workspace PTY table and loopback routes. */\n\nimport { randomBytes } from 'node:crypto'\nimport { basename } from 'node:path'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type {} from '@acryldev/control'\nimport type { Acryl } from '@acryldev/blends'\nimport type {} from '@acryldev/blends/cordis/router'\nimport type {} from '@acryldev/blends/cordis/router-http'\nimport { agentRoutes } from './agents/route.ts'\nimport { AgentCatalog } from './agents/catalog.ts'\nimport { agentSettingsFile, agentsFile, createFileCatalogStore } from './agents/file-store.ts'\nimport { AgentSettings } from './agents/settings.ts'\nimport { AgentStatusStore, WORKSPACE_AGENT_STATUS_PATH } from './agents/status/agent-status.ts'\nimport { agentStatusRoutes } from './agents/status/route.ts'\nimport { capabilityRoutes } from './capabilities/route.ts'\nimport { filesRoutes } from './files/route.ts'\nimport { WorkspaceFiles, WorkspaceFilesError } from './files/service.ts'\nimport { pickFolderNatively, singleFlight } from './folder-picker/picker.ts'\nimport { pickFolderRoutes } from './folder-picker/route.ts'\nimport { gitRoutes } from './git/route.ts'\nimport { WorkspaceGit, WorkspaceGitError } from './git/service.ts'\nimport { WORKSPACE_API_PREFIX, privateApi } from './private-route.ts'\nimport { PROJECTS_NAMESPACE, ProjectRegistry, ProjectsSchema } from './projects/registry.ts'\nimport { createKeepAlive, projectRoutes } from './projects/route.ts'\nimport { registerWorkspaceTools } from './projects/tools.ts'\nimport { WORKSPACE_PTY_STREAM_PATH } from './pty/contract.ts'\nimport { spawnNodePty } from './pty/node-pty-spawn.ts'\nimport { ptyRoutes } from './pty/route.ts'\nimport { WorkspacePtyRegistry } from './pty/service.ts'\nimport { ptyStreamRoutes } from './pty/stream.ts'\nimport { registerChatContext, type SystemPromptContextPort } from './shared-context/chat.ts'\nimport { briefRoutes } from './shared-context/route.ts'\nimport { SHARED_CONTEXT_SERVICE, SharedContext } from './shared-context/service.ts'\nimport { registerContextTool } from './shared-context/tool.ts'\n\n/** Stable Cordis plugin name. */\nexport const name = 'acryl-workspace'\n\n/**\n * The part of the runtime's `appInstance` service ACRYL plugins read (a separated interface: plugins do not import the runtime). Every plugin declares\n * exactly this shape, so the Context augmentations agree in any program that loads several of them.\n */\ninterface AppInstanceService {\n readonly home: string\n readonly dshHome: string\n}\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n appInstance: AppInstanceService\n }\n}\n\n/**\n * The row's config, written by the generated overlay when the frame hosts an app: where the app's own page is served (`/app`). The page opens it in a\n * browser tile on first run, so the person starts at the app they are building rather than an empty canvas.\n */\nexport interface WorkspaceConfig {\n readonly appPage?: string\n /** A folder to open on: added to the projects shown at start (`acryl ade` passes the folder it was started in). Not a folder: ignored. */\n readonly openFolder?: string\n}\n\n/**\n * The routes, the terminal's WebSocket among them, are served by the router (`router`, `routerHttp`) under {@link WORKSPACE_API_PREFIX}. The\n * loopback Web server is still needed for its address (agent hooks report to it). The app instance says where this app keeps its data.\n */\nexport const inject = ['acrylWeb', 'appInstance', 'acrylSettings', 'router', 'routerHttp']\n\n/**\n * Activate the workspace's Host half: its services and their routes. Disabling the Loader row unmounts the routes and kills leftover PTY sessions.\n * @param ctx - Host context for this generation.\n */\nexport function apply(ctx: Context, config: WorkspaceConfig = {}): void {\n if (ctx.acrylWeb.host !== '127.0.0.1') {\n throw new Error('@acryldev/workspace: requires a loopback Web server')\n }\n const appPage = typeof config.appPage === 'string' && config.appPage.startsWith('/') ? config.appPage : undefined\n const rendererOrigin = `http://127.0.0.1:${String(ctx.acrylWeb.port)}`\n const reportHostError = (operation: string, cause: unknown): void => {\n ctx.logger.error(\n `@acryldev/workspace: failed to ${operation}: ${cause instanceof Error ? cause.message : String(cause)}`,\n )\n }\n // The services and their routes are built in the effect; the terminal's sockets are taken and the app mounted after it, so on unload the\n // mount goes first (its requests end and are waited for), then the terminal sockets close with 1001, then the PTYs, git and the rest go.\n const built: { routes?: readonly Acryl[]; pty?: WorkspacePtyRegistry } = {}\n ctx.effect(() => {\n // The user's custom agents live in their ACRYL home; the registry asks the catalog what an id means.\n // The registry asks the settings what an id runs; the settings ask the catalog and the registry's own PATH search.\n let settings: AgentSettings | undefined\n // Agents that support hooks report working, waiting and done here; the secret is known only to their terminals.\n const statusToken = randomBytes(24).toString('hex')\n // An agent started in a Shared Context workspace gets its context; the service is set further down, once the registry exists.\n let sharedContext: SharedContext | undefined\n const workspacePty = new WorkspacePtyRegistry({\n spawn: spawnNodePty,\n agents: { resolve: id => settings?.resolve(id) },\n launchContext: { launchFor: (id, cwd) => sharedContext?.launchFor(id, cwd) },\n agentStatus: { url: `${rendererOrigin}${WORKSPACE_AGENT_STATUS_PATH}`, token: statusToken },\n })\n const agentStatus = new AgentStatusStore(id => workspacePty.has(id))\n const catalog = new AgentCatalog(createFileCatalogStore(agentsFile(ctx.appInstance.home)), command => workspacePty.canRun(command))\n const agentSettings = new AgentSettings(createFileCatalogStore(agentSettingsFile(ctx.appInstance.home)), catalog, command => workspacePty.canRun(command))\n settings = agentSettings\n void catalog.load().catch(reportHostError.bind(undefined, 'load custom agents'))\n void agentSettings.load().catch(reportHostError.bind(undefined, 'load agent settings'))\n const workspaceGit = new WorkspaceGit()\n const workspaceFiles = new WorkspaceFiles({\n // Only a git worktree root is a place the editor may touch; a failed check surfaces as a bad path.\n resolveWorktree: async (path) => {\n try {\n return await workspaceGit.worktreeRoot(path)\n } catch (cause) {\n if (cause instanceof WorkspaceGitError && cause.kind === 'invalid') throw new WorkspaceFilesError(cause.message, 'invalid')\n throw cause\n }\n },\n ignored: (root, paths) => workspaceGit.ignored(root, paths),\n })\n const releases: Array<() => void> = []\n try {\n // The project list is ACRYL's own: one section of the ACRYL home's settings, released with this plugin so a reloaded plugin registers it again.\n const projects = new ProjectRegistry(ctx.acrylSettings.register(PROJECTS_NAMESPACE, ProjectsSchema))\n // The app itself is the first project: its own folder, so the left pane has a place for the first chats and the agent works where\n // the app lives. Added once, only while the list is empty; removing it later stays the person's choice and is not undone here.\n const appRoot = (ctx.appInstance as { readonly root?: unknown }).root\n // The folder the app was started on (`acryl ade` in a project) is the one asked for: it is added, and on a first start instead of the app's own.\n const openFolder = typeof config.openFolder === 'string' && config.openFolder !== '' ? config.openFolder : undefined\n const first = openFolder ?? (typeof appRoot === 'string' && projects.view().paths.length === 0 ? appRoot : undefined)\n if (first !== undefined)\n void projects.add(first).catch(cause => { reportHostError(`add ${first} as a project`, cause) })\n // Shared context (spec 043 T009): the generated WORKSPACE.md of every Shared Context workspace stays current, and other plugins can read it.\n const shared = new SharedContext({ registry: projects, home: ctx.appInstance.home })\n sharedContext = shared\n releases.push(shared.start(cause => { reportHostError('write the shared workspace context', cause) }))\n const withdrawSharedContext = ctx.reflect.provide(SHARED_CONTEXT_SERVICE, shared)\n releases.push(() => { void withdrawSharedContext() })\n // The DSH chat in a Shared Context workspace is told about it (T010); present while the harness's system prompt service is.\n const contextFor = (folder: string): { readonly prompt: string } | undefined => sharedContext?.contextFor(folder)\n const chatContextFiber = ctx.inject(['systemPrompt'], (child) => {\n const systemPrompt = (child as unknown as { readonly systemPrompt: SystemPromptContextPort }).systemPrompt\n child.effect(() => registerChatContext(systemPrompt, contextFor), '@acryldev/workspace: shared workspace context for the chat')\n })\n releases.push(() => { void chatContextFiber.dispose() })\n // The context for any agent through the tool registry and the gateway, and the agent's workspace tools (spec 043 T007); present while\n // ACRYL's tool port is.\n const contextToolFiber = ctx.inject(['acrylTools'], (child) => {\n child.effect(() => registerContextTool(child, { view: () => projects.view(), promptFor: id => sharedContext?.promptFor(id) }), '@acryldev/workspace: workspace context tool')\n })\n releases.push(() => { void contextToolFiber.dispose() })\n const toolsFiber = ctx.inject(['acrylTools'], (child) => {\n child.effect(() => registerWorkspaceTools(child, projects), '@acryldev/workspace: workspace agent tools')\n })\n releases.push(() => { void toolsFiber.dispose() })\n const keepAlive = createKeepAlive()\n releases.push(() => { keepAlive.stop() })\n // The chat is the DSH `agents` service; reading it per request, not injecting it, is what lets this plugin stay up when the chat is off.\n const services: { get(name: string): unknown } = ctx\n // The OS's own folder chooser, for the \"+\" on Web (a browser page cannot open one that yields a path).\n const pickFolder = singleFlight(() => pickFolderNatively(process.platform))\n built.pty = workspacePty\n built.routes = [\n ptyRoutes(workspacePty, reportHostError),\n agentRoutes(catalog, agentSettings, reportHostError),\n agentStatusRoutes(statusToken, agentStatus, reportHostError),\n capabilityRoutes(() => ({\n chat: services.get('agents') !== undefined,\n ...(appPage === undefined ? {} : { appPage }),\n ...(typeof appRoot === 'string' ? { appRoot, appName: basename(appRoot) } : {}),\n })),\n projectRoutes(projects, keepAlive, reportHostError),\n briefRoutes(shared),\n filesRoutes(workspaceFiles, reportHostError),\n gitRoutes(workspaceGit, reportHostError),\n pickFolderRoutes(pickFolder, reportHostError),\n ]\n } catch (cause) {\n for (const release of releases.reverse()) release()\n void workspaceGit.dispose()\n throw cause\n }\n return async () => {\n for (const release of releases.reverse()) release()\n await Promise.all([workspacePty.disposeAll(), workspaceGit.dispose()])\n }\n }, '@acryldev/workspace: PTY table, git, files, projects and agents')\n if (built.routes === undefined || built.pty === undefined) throw new Error('@acryldev/workspace: the routes were not built')\n const upgrade = ctx.routerHttp.upgrades()\n // Removing the mount ends the requests still in flight, the project event streams among them.\n ctx.router.route('/', privateApi(...built.routes, ptyStreamRoutes(built.pty, upgrade, reportHostError)))\n ctx.routerHttp.mount(WORKSPACE_API_PREFIX, { upgrade: [WORKSPACE_PTY_STREAM_PATH] })\n}\n\n/** The agent's workspace tools, exported so the runtime can check their schemas against DSH's own compiler. */\nexport { registerWorkspaceTools } from './projects/tools.ts'\n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