@moberg_hr/work-tree 2.0.12 → 2.0.13

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 (67) hide show
  1. package/dist/{attach-M2UXWUMO.js → attach-MFU4KN47.js} +5 -5
  2. package/dist/bin.js +1 -1
  3. package/dist/chunk-4KNBN2OF.js +9 -0
  4. package/dist/{chunk-GWJVU4AS.js → chunk-7GQCPGKQ.js} +2 -2
  5. package/dist/{chunk-UAAH334K.js → chunk-7JPCVEOY.js} +35 -4
  6. package/dist/chunk-7JPCVEOY.js.map +1 -0
  7. package/dist/{chunk-5LZZ73MS.js → chunk-BSFL3WDR.js} +14 -13
  8. package/dist/chunk-BSFL3WDR.js.map +1 -0
  9. package/dist/{chunk-7UU5LPDM.js → chunk-F375JY4M.js} +3 -3
  10. package/dist/{chunk-HBCL77AR.js → chunk-FX4IA5U4.js} +2 -2
  11. package/dist/{chunk-HBXDIRM4.js → chunk-KSIXTTO6.js} +3 -3
  12. package/dist/{chunk-TZWXQ4YZ.js → chunk-KUWFGPGW.js} +5 -5
  13. package/dist/{chunk-ACXPSQJR.js → chunk-MI3PS2SH.js} +18 -1
  14. package/dist/{chunk-ACXPSQJR.js.map → chunk-MI3PS2SH.js.map} +1 -1
  15. package/dist/{chunk-TVMZ4NYY.js → chunk-OZIR2255.js} +2 -2
  16. package/dist/chunk-TNJF7T33.js +17 -0
  17. package/dist/chunk-TNJF7T33.js.map +1 -0
  18. package/dist/{chunk-SRIYY5HL.js → chunk-U4UB4LG6.js} +2 -2
  19. package/dist/{cleanup-MHPHSM5I.js → cleanup-LRT6J36R.js} +8 -8
  20. package/dist/{cli-QF7GRSWT.js → cli-VGUJI5WG.js} +3 -3
  21. package/dist/{fork-CISFOOAQ.js → fork-RJ3ZPPWT.js} +6 -6
  22. package/dist/{move-CE5NIZKL.js → move-OLXCDNA3.js} +2 -2
  23. package/dist/{prune-DS73W7LT.js → prune-UYCQOEUF.js} +7 -7
  24. package/dist/{pty-host-5Z3GYXTW.js → pty-host-X3QK2LSK.js} +115 -14
  25. package/dist/pty-host-X3QK2LSK.js.map +1 -0
  26. package/dist/{remove-DEDH57GP.js → remove-6XACPXUU.js} +6 -6
  27. package/dist/restart-6ZAFDRBO.js +70 -0
  28. package/dist/restart-6ZAFDRBO.js.map +1 -0
  29. package/dist/{sessions-AGFO7W5U.js → sessions-MKXREA2M.js} +5 -5
  30. package/dist/{sync-S4IJT2WR.js → sync-MSU7QJWN.js} +7 -7
  31. package/dist/{tree-7S4DUZRZ.js → tree-MOIO4GQL.js} +5 -5
  32. package/dist/wd-bin.js +2 -2
  33. package/dist/web/assets/{PtyView-CKEfBQ3-.js → PtyView-D1TEpjVE.js} +2 -2
  34. package/dist/web/assets/{PtyView-CKEfBQ3-.js.map → PtyView-D1TEpjVE.js.map} +1 -1
  35. package/dist/web/assets/{index-DJsnmqYW.css → index-BVeughC2.css} +1 -1
  36. package/dist/web/assets/index-DoMf82kx.js +118 -0
  37. package/dist/web/assets/index-DoMf82kx.js.map +1 -0
  38. package/dist/web/index.html +2 -2
  39. package/dist/{web-ISGYHCTC.js → web-6AOR3MIE.js} +399 -71
  40. package/dist/web-6AOR3MIE.js.map +1 -0
  41. package/npm-shrinkwrap.json +2 -2
  42. package/package.json +1 -1
  43. package/dist/chunk-4U52S7AZ.js +0 -9
  44. package/dist/chunk-5LZZ73MS.js.map +0 -1
  45. package/dist/chunk-UAAH334K.js.map +0 -1
  46. package/dist/pty-host-5Z3GYXTW.js.map +0 -1
  47. package/dist/web/assets/index-CHA-bad8.js +0 -118
  48. package/dist/web/assets/index-CHA-bad8.js.map +0 -1
  49. package/dist/web-ISGYHCTC.js.map +0 -1
  50. /package/dist/{attach-M2UXWUMO.js.map → attach-MFU4KN47.js.map} +0 -0
  51. /package/dist/{chunk-4U52S7AZ.js.map → chunk-4KNBN2OF.js.map} +0 -0
  52. /package/dist/{chunk-GWJVU4AS.js.map → chunk-7GQCPGKQ.js.map} +0 -0
  53. /package/dist/{chunk-7UU5LPDM.js.map → chunk-F375JY4M.js.map} +0 -0
  54. /package/dist/{chunk-HBCL77AR.js.map → chunk-FX4IA5U4.js.map} +0 -0
  55. /package/dist/{chunk-HBXDIRM4.js.map → chunk-KSIXTTO6.js.map} +0 -0
  56. /package/dist/{chunk-TZWXQ4YZ.js.map → chunk-KUWFGPGW.js.map} +0 -0
  57. /package/dist/{chunk-TVMZ4NYY.js.map → chunk-OZIR2255.js.map} +0 -0
  58. /package/dist/{chunk-SRIYY5HL.js.map → chunk-U4UB4LG6.js.map} +0 -0
  59. /package/dist/{cleanup-MHPHSM5I.js.map → cleanup-LRT6J36R.js.map} +0 -0
  60. /package/dist/{cli-QF7GRSWT.js.map → cli-VGUJI5WG.js.map} +0 -0
  61. /package/dist/{fork-CISFOOAQ.js.map → fork-RJ3ZPPWT.js.map} +0 -0
  62. /package/dist/{move-CE5NIZKL.js.map → move-OLXCDNA3.js.map} +0 -0
  63. /package/dist/{prune-DS73W7LT.js.map → prune-UYCQOEUF.js.map} +0 -0
  64. /package/dist/{remove-DEDH57GP.js.map → remove-6XACPXUU.js.map} +0 -0
  65. /package/dist/{sessions-AGFO7W5U.js.map → sessions-MKXREA2M.js.map} +0 -0
  66. /package/dist/{sync-S4IJT2WR.js.map → sync-MSU7QJWN.js.map} +0 -0
  67. /package/dist/{tree-7S4DUZRZ.js.map → tree-MOIO4GQL.js.map} +0 -0
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@moberg_hr/work-tree",
3
- "version": "2.0.12",
3
+ "version": "2.0.13",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@moberg_hr/work-tree",
9
- "version": "2.0.12",
9
+ "version": "2.0.13",
10
10
  "hasInstallScript": true,
11
11
  "license": "MIT",
12
12
  "dependencies": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moberg_hr/work-tree",
3
- "version": "2.0.12",
3
+ "version": "2.0.13",
4
4
  "description": "Cross-platform Git worktree manager for multiple repositories",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,9 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/version.ts
4
- var VERSION = true ? "2.0.12" : "dev";
5
-
6
- export {
7
- VERSION
8
- };
9
- //# sourceMappingURL=chunk-4U52S7AZ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/completions/index.ts"],"sourcesContent":["import chalk from 'chalk';\nimport yargs from 'yargs';\nimport type { CommandModule } from 'yargs';\nimport { completionHandler } from './completions/index.js';\nimport { VERSION } from './version.js';\n\n/**\n * Every command, in the order `work --help` lists them, by the words that\n * run it. `work <verb>` imports only that verb's module: loading all of them\n * (node-pty, the servers, SQLite, the prompts) made every command — and\n * Claude's `work sessions --json` — start in ~430 ms. Help, completion and\n * anything unknown load them all. A test keeps the words equal to the\n * commands' own names and aliases.\n */\nexport const COMMANDS: Array<{ names: string[]; load: () => Promise<CommandModule> }> = [\n { names: ['init'], load: async () => (await import('./commands/init.js')).initCommand },\n { names: ['config'], load: async () => (await import('./commands/config.js')).configCommand },\n { names: ['tree', 't'], load: async () => (await import('./commands/tree.js')).treeCommand },\n { names: ['remove'], load: async () => (await import('./commands/remove.js')).removeCommand },\n { names: ['fork'], load: async () => (await import('./commands/fork.js')).forkCommand },\n { names: ['update'], load: async () => (await import('./commands/update.js')).updateCommand },\n { names: ['catchup'], load: async () => (await import('./commands/catchup.js')).catchupCommand },\n { names: ['snooze'], load: async () => (await import('./commands/snooze.js')).snoozeCommand },\n { names: ['pin'], load: async () => (await import('./commands/pin.js')).pinCommand },\n { names: ['section'], load: async () => (await import('./commands/section.js')).sectionCommand },\n { names: ['note'], load: async () => (await import('./commands/note.js')).noteCommand },\n { names: ['block'], load: async () => (await import('./commands/block.js')).blockCommand },\n { names: ['time'], load: async () => (await import('./commands/time.js')).timeCommand },\n { names: ['read'], load: async () => (await import('./commands/read.js')).readCommand },\n { names: ['screen'], load: async () => (await import('./commands/screen.js')).screenCommand },\n { names: ['send'], load: async () => (await import('./commands/send.js')).sendCommand },\n { names: ['wait'], load: async () => (await import('./commands/wait.js')).waitCommand },\n { names: ['start'], load: async () => (await import('./commands/start.js')).startCommand },\n { names: ['stop'], load: async () => (await import('./commands/stop.js')).stopCommand },\n { names: ['answer'], load: async () => (await import('./commands/answer.js')).answerCommand },\n { names: ['list'], load: async () => (await import('./commands/list.js')).listCommand },\n { names: ['status'], load: async () => (await import('./commands/status.js')).statusCommand },\n { names: ['recent'], load: async () => (await import('./commands/recent.js')).recentCommand },\n { names: ['resume'], load: async () => (await import('./commands/resume.js')).resumeCommand },\n { names: ['sessions'], load: async () => (await import('./commands/sessions.js')).sessionsCommand },\n { names: ['digest'], load: async () => (await import('./commands/digest.js')).digestCommand },\n { names: ['cleanup'], load: async () => (await import('./commands/cleanup.js')).cleanupCommand },\n { names: ['overlaps'], load: async () => (await import('./commands/overlaps.js')).overlapsCommand },\n { names: ['search'], load: async () => (await import('./commands/search.js')).searchCommand },\n { names: ['pr'], load: async () => (await import('./commands/pr.js')).prCommand },\n { names: ['timesheet'], load: async () => (await import('./commands/timesheet.js')).timesheetCommand },\n { names: ['prune'], load: async () => (await import('./commands/prune.js')).pruneCommand },\n { names: ['sync'], load: async () => (await import('./commands/sync.js')).syncCommand },\n { names: ['todo'], load: async () => (await import('./commands/todo.js')).todoCommand },\n { names: ['hydrate'], load: async () => (await import('./commands/hydrate.js')).hydrateCommand },\n { names: ['diff'], load: async () => (await import('./commands/diff.js')).diffCommand },\n { names: ['web'], load: async () => (await import('./commands/web.js')).webCommand },\n { names: ['hook'], load: async () => (await import('./commands/hook.js')).hookCommand },\n { names: ['run'], load: async () => (await import('./commands/run.js')).runCommand },\n { names: ['broadcast'], load: async () => (await import('./commands/broadcast.js')).broadcastCommand },\n { names: ['attach', 'a'], load: async () => (await import('./commands/attach.js')).attachCommand },\n { names: ['pty-host'], load: async () => (await import('./commands/pty-host.js')).ptyHostCommand },\n { names: ['state'], load: async () => (await import('./commands/state.js')).stateCommand },\n { names: ['move'], load: async () => (await import('./commands/move.js')).moveCommand },\n { names: ['install-skills'], load: async () => (await import('./commands/install-skills.js')).installSkillsCommand },\n { names: ['completion'], load: async () => (await import('./commands/completion.js')).completionCommand },\n];\n\n/** The commands to register for these arguments: the one named, else all. */\nexport async function commandsFor(argv: string[]): Promise<CommandModule[]> {\n const one = COMMANDS.find((c) => c.names.includes(argv[0] ?? ''));\n return Promise.all((one ? [one] : COMMANDS).map((c) => c.load()));\n}\n\nfunction showHelp() {\n console.log('');\n console.log(chalk.cyan(`Work - Git Worktree Manager ${chalk.gray(`v${VERSION}`)}`));\n console.log(chalk.cyan('============================'));\n console.log('');\n console.log(chalk.green('Usage:'));\n console.log(' work init - Set up configuration');\n console.log(' work config <action> - Manage configuration');\n console.log(' work list [project|group] - List all worktrees');\n console.log(' work tree|t <project|group> <branch> - Create/switch to worktree');\n console.log(' work tree <project|group> <branch> --base <branch> - Create from a specific base branch');\n console.log(' work tree <project|group> <branch> --open - Also open VS Code');\n console.log(' work tree <project|group> <branch> --unsafe - Skip AI tool permission checks');\n console.log(' work remove <project|group> <branch> - Remove worktree');\n console.log(' work remove <project|group> <branch> --force - Force remove worktree');\n console.log(' work status [project|group] [branch] - Show worktree status');\n console.log(' work status --prune - Remove stale entries');\n console.log(' work recent [count] - List recent sessions');\n console.log(' work resume - Resume a recent session');\n console.log(' work sessions [project] [--json] [--changes] - Every session with its status, as the dashboard shows it');\n console.log(' work digest [--since today|yesterday|week] - What each session did (Markdown for a standup; --json)');\n console.log(' work overlaps [--json] - Live sessions changing the same files');\n console.log(' work cleanup [--json] - Which worktrees can go, and why');\n console.log(' work cleanup --apply <id...> [--action …] - Remove / archive / forget them, after a fresh check');\n console.log(' work web - Browser dashboard (one tab, every session)');\n console.log(' work prune - Remove merged worktrees');\n console.log(' work prune --force - Remove all merged (no prompt)');\n console.log(' work sync - Fetch all repos and prune merged (non-interactive)');\n console.log(' work sync --dry-run - Show what sync would prune, remove nothing');\n console.log(' work sync --force - Also remove merged worktrees with uncommitted changes');\n console.log(' work sync --include-squash - Also prune squash-merged branches (lower confidence)');\n console.log(' work hydrate - Seed history from worktrees on disk');\n console.log(' work diff [base] - Open a GitHub-PR-style diff in your browser');\n console.log(' work run <cmd...> - Run a command in every worktree');\n console.log(' work run <cmd...> --target <alias> --parallel - Filter + run concurrently');\n console.log(' work broadcast <prompt> - Queue a prompt to every live session');\n console.log(' work attach [target] [branch] - Attach this terminal to a session (Ctrl+] detaches)');\n console.log(' work todo - List tasks');\n console.log(' work todo add <text> - Add a task');\n console.log(' work todo done <id> - Mark task complete');\n console.log(' work todo rm <id> - Remove a task');\n console.log(' work completion --install - Install shell completions');\n console.log('');\n console.log(chalk.green('Config Actions:'));\n console.log(' work config add <alias> <path> - Add a repository');\n console.log(' work config remove <alias> - Remove a repository');\n console.log(' work config list - List repos and groups');\n console.log(' work config group add <name> <alias1> <alias2> ... - Create a repository group');\n console.log(' work config group remove <name> - Remove a repository group');\n console.log(' work config group regen <name> - Regenerate group CLAUDE.md');\n console.log('');\n console.log(chalk.green('Examples:'));\n console.log(' work init');\n console.log(' work list');\n console.log(' work list ai');\n console.log(' work tree ai feature/login');\n console.log(' work tree frontend feature/login --open');\n console.log(' work tree ai feature/hotfix --unsafe');\n console.log(' work remove ai feature/login');\n console.log('');\n console.log(chalk.gray(' # Groups (multi-repo worktrees):'));\n console.log(' work config group add fullstack api frontend');\n console.log(' work tree fullstack feature/login');\n console.log(' work remove fullstack feature/login');\n console.log('');\n}\n\nexport async function run(argv: string[]): Promise<void> {\n // Show custom colored help when no args given\n if (argv.length === 0) {\n showHelp();\n return;\n }\n\n let cli = yargs(argv).scriptName('work').usage('$0 <command> [options]');\n for (const c of await commandsFor(argv)) cli = cli.command(c);\n cli = cli\n // Hidden: yargs uses this internally for --get-yargs-completions\n .completion('__completions', false, completionHandler)\n .demandCommand(1, 'You need to specify a command. Run work --help for usage.')\n .strict()\n .fail((msg, err, yargs) => {\n if (err?.name === 'ExitPromptError') {\n console.log('\\nCancelled.');\n process.exit(0);\n }\n if (msg) {\n yargs.showHelp();\n console.error('\\n' + msg);\n }\n if (err) console.error(err);\n process.exit(1);\n })\n .help()\n .alias('h', 'help')\n .version(VERSION)\n .alias('v', 'version')\n .wrap(Math.min(100, process.stdout.columns || 80));\n\n // Async handlers' failures land in .fail() above (and the fatal handlers in bin.ts).\n void cli.parse();\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { loadConfig } from '../core/platform/config.js';\nimport { parseWorktreeList, getCurrentBranch } from '../core/git/git.js';\nimport { resolveProjectTarget } from '../core/worktree/resolve.js';\n\ntype Done = (completions: string[]) => void;\n\n/**\n * Dynamic completion handler for yargs.\n * Called when the user presses TAB (via --get-yargs-completions).\n *\n * argv._ = ['<scriptName>', '<command>', '<arg1>', ...., '<current>']\n * We skip the script name and the trailing current word to get the \"completed\" args.\n */\nexport function completionHandler(current: string, argv: Record<string, unknown>, done: Done): void {\n const rawArgs = argv._ as string[];\n\n // Skip the script name (first element) and the trailing current word (last element)\n const args = rawArgs.slice(1, -1);\n const command = args[0] as string | undefined;\n\n const config = loadConfig();\n if (!config) {\n done([]);\n return;\n }\n\n if (!command) {\n done(\n [\n 'tree',\n 't',\n 'remove',\n 'list',\n 'status',\n 'recent',\n 'resume',\n 'prune',\n 'todo',\n 'attach',\n 'hydrate',\n 'diff',\n 'web',\n 'init',\n 'config',\n 'completion',\n ].filter((c) => c.startsWith(current)),\n );\n return;\n }\n\n switch (command) {\n case 'config':\n completeConfig(args, current, config, done);\n return;\n\n case 'tree':\n case 't':\n case 'remove':\n case 'list':\n case 'status':\n completeTreeRemoveList(command, args, current, config, done);\n return;\n\n default:\n done([]);\n }\n}\n\nfunction completeConfig(args: string[], current: string, config: NonNullable<ReturnType<typeof loadConfig>>, done: Done): void {\n const subAction = args[1] as string | undefined;\n\n if (!subAction) {\n const actions = ['add', 'remove', 'list', 'group', 'show', 'edit'];\n done(actions.filter((a) => a.startsWith(current)));\n return;\n }\n\n if (subAction === 'remove' && args.length === 2) {\n const aliases = Object.keys(config.repos);\n done(aliases.filter((a) => a.startsWith(current)));\n return;\n }\n\n if (subAction === 'group') {\n const groupSub = args[2] as string | undefined;\n\n if (!groupSub) {\n const subs = ['add', 'remove', 'regen'];\n done(subs.filter((s) => s.startsWith(current)));\n return;\n }\n\n if ((groupSub === 'remove' || groupSub === 'regen') && args.length === 3) {\n const groups = Object.keys(config.groups);\n done(groups.filter((g) => g.startsWith(current)));\n return;\n }\n\n if (groupSub === 'add' && args.length >= 4) {\n const alreadyUsed = args.slice(3);\n const aliases = Object.keys(config.repos).filter((a) => !alreadyUsed.includes(a));\n done(aliases.filter((a) => a.startsWith(current)));\n return;\n }\n\n done([]);\n return;\n }\n\n done([]);\n}\n\nfunction completeTreeRemoveList(\n command: string,\n args: string[],\n current: string,\n config: NonNullable<ReturnType<typeof loadConfig>>,\n done: Done,\n): void {\n const targetName = args[1] as string | undefined;\n\n if (!targetName) {\n const names = [...Object.keys(config.repos), ...Object.keys(config.groups)];\n done(names.filter((n) => n.startsWith(current)));\n return;\n }\n\n if (args.length === 2) {\n const target = resolveProjectTarget(targetName, config);\n if (!target) {\n done([]);\n return;\n }\n\n if (target.isGroup) {\n completeGroupBranches(target.name, target.repoAliases, current, config, done);\n } else {\n completeRepoBranches(targetName, current, config, done);\n }\n return;\n }\n\n done([]);\n}\n\nfunction completeRepoBranches(alias: string, current: string, config: NonNullable<ReturnType<typeof loadConfig>>, done: Done): void {\n const repoPath = config.repos[alias];\n if (!repoPath || !fs.existsSync(repoPath)) {\n done([]);\n return;\n }\n\n const worktrees = parseWorktreeList(repoPath);\n const branches = worktrees.map((wt) => wt.branch).filter((b): b is string => !!b && b.startsWith(current));\n done(branches);\n}\n\nfunction completeGroupBranches(\n groupName: string,\n repoAliases: string[],\n current: string,\n config: NonNullable<ReturnType<typeof loadConfig>>,\n done: Done,\n): void {\n const groupDir = path.join(config.worktreesRoot, groupName);\n if (!fs.existsSync(groupDir)) {\n done([]);\n return;\n }\n\n try {\n const branchDirs = fs\n .readdirSync(groupDir, { withFileTypes: true })\n .filter((d) => d.isDirectory())\n .map((d) => {\n const bdPath = path.join(groupDir, d.name);\n for (const alias of repoAliases) {\n const repoPath = config.repos[alias];\n if (!repoPath) continue;\n const subPath = path.join(bdPath, path.basename(repoPath));\n if (fs.existsSync(subPath)) {\n const branch = getCurrentBranch(subPath);\n if (branch) return branch;\n }\n }\n return d.name;\n });\n\n done(branchDirs.filter((b) => b.startsWith(current)));\n } catch {\n done([]);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,OAAO,WAAW;AAClB,OAAO,WAAW;;;ACDlB,OAAO,QAAQ;AACf,OAAO,UAAU;AAcV,SAAS,kBAAkB,SAAiB,MAA+B,MAAkB;AAClG,QAAM,UAAU,KAAK;AAGrB,QAAM,OAAO,QAAQ,MAAM,GAAG,EAAE;AAChC,QAAM,UAAU,KAAK,CAAC;AAEtB,QAAM,SAAS,WAAW;AAC1B,MAAI,CAAC,QAAQ;AACX,SAAK,CAAC,CAAC;AACP;AAAA,EACF;AAEA,MAAI,CAAC,SAAS;AACZ;AAAA,MACE;AAAA,QACE;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,EAAE,OAAO,CAAC,MAAM,EAAE,WAAW,OAAO,CAAC;AAAA,IACvC;AACA;AAAA,EACF;AAEA,UAAQ,SAAS;AAAA,IACf,KAAK;AACH,qBAAe,MAAM,SAAS,QAAQ,IAAI;AAC1C;AAAA,IAEF,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,6BAAuB,SAAS,MAAM,SAAS,QAAQ,IAA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KAAK,SAAS,EACpB,KAAK,KAAK,IAAI,KAAK,QAAQ,OAAO,WAAW,EAAE,CAAC;AAGnD,OAAK,IAAI,MAAM;AACjB;","names":["yargs"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/pty/output-status.ts","../src/core/pty/pty-pool.ts","../src/core/sessions/web-state.ts"],"sourcesContent":["import type { SessionAttention } from '../api-types.js';\n\n/**\n * A status for a session whose tool isn't Claude Code (config `aiCommand`,\n * e.g. opencode): no hooks report its turns, so the PTY host's \"last printed\n * anything\" stands in — a working agent redraws its spinner, an idle one\n * prints nothing. Working while it printed in the last `OUTPUT_WORKING_MS`,\n * idle after; never \"done, unseen\" or \"needs input\" (output can't tell a\n * finished turn from a question). Pure.\n */\n\nexport const OUTPUT_WORKING_MS = 10_000;\n\nexport interface PtyOutput {\n /** The tool's binary (the host's spawn spec). */\n tool?: string;\n /** When it last printed (ISO). */\n lastOutputAt?: string;\n startedAt: string;\n}\n\nexport function statusFromOutput(p: PtyOutput, now: number): SessionAttention | null {\n if (!p.tool || p.tool === 'claude' || !p.lastOutputAt) return null;\n const at = Date.parse(p.lastOutputAt);\n if (!Number.isFinite(at)) return null;\n const working = now - at < OUTPUT_WORKING_MS;\n return {\n state: working ? 'working' : 'idle',\n seen: true,\n since: p.lastOutputAt,\n updatedAt: p.lastOutputAt,\n stale: false,\n summary: `${working ? 'Printing' : 'Quiet'} — from its terminal output (${p.tool} has no status hooks)`,\n };\n}\n","import path from 'node:path';\nimport type { AgentAdapter } from '../agents/types.js';\nimport { agentFor, agentSettings, assistantAgent } from '../agents/index.js';\nimport { statusFromOutput, type PtyOutput } from './output-status.js';\nimport type { SessionAttention } from '../api-types.js';\nimport type { HostBeat } from './host-health.js';\nimport { PtyHostBusyError } from './pty-host-client.js';\nimport { noClaudeBecause } from '../archive/archiving.js';\nimport { findSession, sessionIdFor } from '../sessions/web-state.js';\nimport type { WorktreeSession } from '../sessions/history.js';\nimport { hostStartLockPath, type SpawnSpec, type HostInfo, type PtyInfo } from './pty-host-protocol.js';\nimport { dbPtySessions } from './pty-sessions-file.js';\nimport { ensureFile, withFileLock } from '../platform/fs-safe.js';\nimport { forgetPersistedSession } from './pty-sessions-file.js';\nimport { loadConfig } from '../platform/config.js';\nimport { ensureHost, findHost, PtyHostClient, findHostPatient, PtyHostVersionError } from './pty-host-client.js';\nimport { logSwallowed, swallow } from '../platform/best-effort.js';\nimport { ASSISTANT_ID, prepareAssistantDir } from '../agents/assistant.js';\n\n/**\n * `work web`'s view of the Claude PTYs. The PTYs themselves live in the\n * PTY host (`work pty-host`, see core/pty-host.ts), a separate long-lived\n * process — so restarting or rebuilding `work web` never kills an agent,\n * and a real terminal (`work attach`) can share the same session.\n *\n * This module resolves a dashboard session to a spawn spec, asks the host\n * to spawn it on first attach, and keeps a small cache of which sessions\n * have a live PTY for the synchronous badge path (`peekPty`).\n */\n\nlet workBin = process.argv[1] ?? '';\n/** Whether this server may start the PTY host when none runs (not the dev server: see configurePtyPool). */\nlet mayStartHost = true;\nlet client: PtyHostClient | null = null;\nlet live = new Set<string>();\n/** The pids of those PTYs' processes (the Claudes the app runs). */\nlet livePids = new Set<number>();\n/** Each live PTY's tool and last output (for output-status.ts). */\nlet outputs = new Map<string, PtyOutput>();\nlet refreshTimer: NodeJS.Timeout | null = null;\n/** The heartbeat (host-health.ts): each list request is one. */\nconst beat: HostBeat = { known: false, lastOkAt: null, latencyMs: null, lastError: null };\n\n/** How the host answered lately (for GET /api/pty-host/health). */\nexport function hostBeat(): HostBeat {\n return { ...beat };\n}\nconst REFRESH_MS = 2000;\n\n/** Called by `work web` at startup with the resolved `work` binary path,\n * which is what the host is spawned from. */\nexport function configurePtyPool(opts: { workBin: string; startHost?: boolean }): void {\n workBin = opts.workBin;\n // The dev server (`work web --dev`) uses the host that runs and never starts one: started\n // from a checkout's build, the long-lived host that owns every Claude would outlive it,\n // and the installed work would become a client of the checkout's code.\n mayStartHost = opts.startHost ?? true;\n}\n\n/** The `work` binary path, for routes that launch `work attach`. */\nexport function getWorkBin(): string {\n return workBin;\n}\n\nasync function getClient(spawnIfMissing: boolean): Promise<PtyHostClient | null> {\n if (client) {\n // Cheap liveness re-check happens in refresh(); a dead host surfaces\n // as a failed call, which resets `client` below.\n return client;\n }\n const info = spawnIfMissing && mayStartHost ? await ensureHost(workBin) : await findHost();\n if (!info && spawnIfMissing && !mayStartHost)\n throw new Error(\n \"No PTY host is running, and the dev server doesn't start one: start the installed work (its app or `work web`) first.\",\n );\n if (!info) return null;\n client = new PtyHostClient(info);\n startRefresh();\n return client;\n}\n\nasync function refresh(): Promise<void> {\n const t0 = Date.now();\n try {\n const c = await getClient(false);\n if (!c) {\n beat.known = false;\n live = new Set();\n livePids = new Set();\n outputs = new Map();\n return;\n }\n beat.known = true;\n const ptys = await c.list();\n beat.lastOkAt = Date.now();\n beat.latencyMs = beat.lastOkAt - t0;\n beat.lastError = null;\n live = new Set(ptys.filter((p) => !p.exited).map((p) => p.id));\n livePids = new Set(ptys.filter((p) => !p.exited).map((p) => p.pid));\n outputs = new Map(\n ptys.filter((p) => !p.exited).map((p) => [p.id, { tool: p.tool, lastOutputAt: p.lastOutputAt, startedAt: p.startedAt }]),\n );\n } catch (err) {\n // Host went away (or was restarted on a new port) — rediscover next tick.\n // A busy host is still a host (it is there, just not answering).\n beat.known = beat.known || err instanceof PtyHostBusyError;\n beat.lastError = (err as Error).message;\n client = null;\n live = new Set();\n livePids = new Set();\n outputs = new Map();\n }\n}\n\nfunction startRefresh(): void {\n if (refreshTimer) return;\n refreshTimer = setInterval(() => void refresh(), REFRESH_MS);\n refreshTimer.unref?.();\n}\n\n/** Connect to an already-running host at `work web` startup so badges for\n * PTYs that survived a web restart show immediately. Never spawns. */\n/** Re-read the host's PTY list now (the periodic refresh can be seconds old,\n * or not have run at all right after `work web` started). */\nexport async function syncPtyPool(): Promise<void> {\n await refresh();\n}\n\nexport async function initPtyPool(): Promise<void> {\n await refresh().catch(() => {});\n startRefresh();\n}\n\n/**\n * After a reboot (or a host crash) nothing is running but\n * `pty-sessions.json` still lists the sessions that were live. Starting the\n * host restores them; do that when there's something to restore, so\n * reopening `work web` picks up where you left off. Returns how many\n * sessions the host will bring back (0 = nothing to do).\n */\nexport async function resumePersistedSessions(): Promise<number> {\n let count: number;\n try {\n count = Object.keys(dbPtySessions.read()).length;\n } catch {\n return 0;\n }\n if (count === 0) return 0;\n if (await findHost().catch(() => true)) return 0; // already running\n await getClient(true);\n await refresh();\n return count;\n}\n\n/**\n * Where Claude runs for a session — the same directory `work tree` launches\n * in: the worktree for a single repo, the group root (parent of the\n * sub-repos) for a group.\n */\nexport { ASSISTANT_ID };\n\n/** The assistant runs config `assistantAgent` (Claude Code by default), in its folder written for that agent. */\nexport function assistantSpec(): { cwd: string; tool: ReturnType<AgentAdapter['launch']['tool']> } {\n const settings = agentSettings();\n const agent = assistantAgent(settings);\n return { cwd: prepareAssistantDir(agent), tool: agent.launch.tool(settings) };\n}\n\nexport function spawnSpecFor(session: WorktreeSession): SpawnSpec | null {\n const first = session.paths[0];\n if (!first) return null;\n const cwd = session.isGroup ? path.dirname(first) : first;\n const config = loadConfig();\n return { cwd, tool: agentFor(config, session).launch.tool(config), port: session.port };\n}\n\n/**\n * Ensure a live PTY exists for the session (spawning Claude in the host if\n * needed) and return the host WebSocket URL to attach to. Null for an\n * unknown session.\n */\nexport async function ensurePty(sessionId: string, extra: { initialPrompt?: string } = {}): Promise<string | null> {\n // The dashboard assistant (Ctrl+K) is not a worktree: it runs in its own\n // folder, which is (re)written first (assistant.ts).\n const session = sessionId === ASSISTANT_ID ? null : findSession(sessionId);\n // Not for a session being archived, or archived: its Claude was stopped on\n // purpose (a Terminal tab still open on it reconnects and would start it).\n const refused = sessionId === ASSISTANT_ID ? null : noClaudeBecause(session, sessionId);\n if (refused) throw new Error(refused);\n const base = sessionId === ASSISTANT_ID ? assistantSpec() : session ? spawnSpecFor(session) : null;\n if (!base) return null;\n // The first prompt only applies to a fresh spawn (the host ignores the\n // spec when the session's PTY is already running).\n const spec = extra.initialPrompt ? { ...base, initialPrompt: extra.initialPrompt } : base;\n\n let c = await getClient(true);\n if (!c) return null;\n try {\n await c.spawn(sessionId, spec);\n } catch (err) {\n // Stale client (host restarted on a new port) — retry once, fresh.\n client = null;\n c = await getClient(true);\n if (!c) throw err;\n await c.spawn(sessionId, spec);\n }\n live.add(sessionId);\n return c.attachUrl(sessionId);\n}\n\n/** Side-effect-free check: does an active (non-exited) PTY exist for this\n * session? Served from the refresh cache — used by session-meta for the\n * \"running/idle\" badge, which must stay synchronous. */\n/** Every PTY in the host, fresh (never starts a host; [] without one). */\nexport async function listHostPtys(): Promise<PtyInfo[]> {\n const c = await getClient(false);\n return c ? c.list() : [];\n}\n\n/** Pids of the Claudes running in the PTY host (from the refresh cache). */\nexport function ptyPids(): ReadonlySet<number> {\n return livePids;\n}\n\n/** A status from its terminal output, for a session whose tool has no hooks (output-status.ts); null for Claude or no PTY. */\nexport function outputStatus(sessionId: string, now = Date.now()): SessionAttention | null {\n const o = outputs.get(sessionId);\n return o ? statusFromOutput(o, now) : null;\n}\n\nexport function peekPty(sessionId: string): boolean {\n return live.has(sessionId);\n}\n\n/** A session's live PTY screen as text; null when there is none (never spawns). */\nexport async function readPtyScreen(sessionId: string): Promise<string | null> {\n if (!live.has(sessionId)) return null;\n const c = await getClient(false);\n return c ? c.screen(sessionId) : null;\n}\n\n/** Write to a session's live PTY. False when there is none (never spawns). */\nexport async function writeToPty(sessionId: string, data: string): Promise<boolean> {\n if (!live.has(sessionId)) return false;\n const c = await getClient(false);\n return c ? c.write(sessionId, data) : false;\n}\n\n/** Kill one session's PTY (if any). Called before removing a worktree so\n * the Claude process doesn't hold its cwd open (Windows refuses to delete\n * a directory that is some process's working directory). */\nexport async function disposePty(sessionId: string): Promise<void> {\n live.delete(sessionId);\n let c = client;\n if (!c) {\n // A busy host (mid-restore) is waited for, not skipped: skipping left\n // Claude running inside the worktree about to be deleted. A host from\n // another build can't be talked to — nothing to do but proceed.\n let info: HostInfo | null;\n try {\n info = await findHostPatient();\n } catch (err) {\n if (err instanceof PtyHostVersionError) return;\n throw err; // still busy after waiting: let the caller report it\n }\n if (!info) return;\n c = new PtyHostClient(info);\n }\n await c.kill(sessionId).catch(swallow(`stop session ${sessionId} in the PTY host`));\n}\n\n/**\n * Stop a session's Claude in the PTY host before its worktree is deleted —\n * from any caller, including the CLI (`work remove` / prune / sync), which\n * doesn't run a pool. Never starts a host; waits for the process to exit\n * (the host's kill does) so Windows can then delete the directory.\n * Best-effort: no host, or a host that can't be reached, is a no-op.\n */\nexport async function stopSessionPty(target: string, branch: string): Promise<void> {\n const id = sessionIdFor({ target, branch } as WorktreeSession);\n live.delete(id);\n // Under the host START lock: a host that's starting holds it until it has\n // restored, so we either see it running (and kill the session) or know\n // none is — and then drop the session from the saved list so a later\n // start doesn't restore Claude into a worktree that's being deleted.\n const lock = hostStartLockPath();\n ensureFile(lock, '');\n await withFileLock(lock, async () => {\n let info;\n try {\n info = await findHostPatient();\n } catch (err) {\n // A host from another build can't be talked to; one still busy after\n // waiting is running and owns the session — leave both alone (and\n // never drop the saved entry: the host is what it belongs to).\n logSwallowed(`stop session ${id}: PTY host`, err);\n return;\n }\n if (info) await new PtyHostClient(info).kill(id).catch(swallow(`stop session ${id} in the PTY host`));\n else await forgetPersistedSession(id).catch(swallow(`forget saved session ${id}`));\n }).catch(swallow(`stop session ${id}: host start lock`));\n}\n\n/** `work web` shutdown. Deliberately does NOT kill anything: the PTYs belong\n * to the host and outlive the dashboard. Just stops polling. */\nexport function detachPtyPool(): void {\n if (refreshTimer) clearInterval(refreshTimer);\n refreshTimer = null;\n client = null;\n live = new Set();\n livePids = new Set();\n}\n","import { createFsWatcher, type FsWatcher } from '../platform/fs-watcher.js';\nimport { findSessionById, type WorktreeSession } from './history.js';\n\nexport { sessionIdFor } from './session-id.js';\n\n/** A session by id — a primary-key lookup (every /api/sessions/:id/*\n * request does one; it used to load and hash every row). */\nexport function findSession(sessionId: string): WorktreeSession | null {\n return findSessionById(sessionId);\n}\n\ninterface WatcherEntry {\n watcher: FsWatcher;\n subscribers: Set<() => void>;\n}\n\nconst sessionWatchers = new Map<string, WatcherEntry>();\nconst DEBOUNCE_MS = 150;\n\n/**\n * Subscribe to filesystem changes for a session's worktree(s). The watch is\n * started on first subscriber and stopped when the last one leaves —\n * reference-counted so the cost stays proportional to what's actually being\n * viewed in the browser. It is the shared fs-watcher: dependency and build\n * folders (node_modules, bin/obj, dist, …) are left out, and on Windows and\n * macOS it is one recursive OS watch per root. A chokidar watch over the\n * whole worktree used to open one watch per folder, node_modules included.\n *\n * Returns an unsubscribe function. Safe to call multiple times.\n */\nexport function subscribeSession(sessionId: string, onChange: () => void): () => void {\n const session = findSession(sessionId);\n if (!session)\n return () => {\n /* unknown session */\n };\n\n let entry = sessionWatchers.get(sessionId);\n if (!entry) {\n const subscribers = new Set<() => void>();\n const newEntry: WatcherEntry = {\n subscribers,\n watcher: createFsWatcher({\n roots: session.paths,\n debounceMs: DEBOUNCE_MS,\n onChange: () => {\n for (const cb of subscribers) {\n try {\n cb();\n } catch {\n /* swallow */\n }\n }\n },\n }),\n };\n sessionWatchers.set(sessionId, newEntry);\n entry = newEntry;\n }\n\n entry.subscribers.add(onChange);\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n entry!.subscribers.delete(onChange);\n if (entry!.subscribers.size === 0) {\n entry!.watcher.stop();\n if (sessionWatchers.get(sessionId) === entry) {\n sessionWatchers.delete(sessionId);\n }\n }\n };\n}\n\n/**\n * Force-stop one session's watcher regardless of subscribers. Used before\n * removing a worktree: on Windows an open directory watch keeps a handle\n * on the tree and makes `git worktree remove` fail. Late unsubscribes from\n * the orphaned entry are harmless (see the identity check above).\n */\nexport async function disposeSessionWatcher(sessionId: string): Promise<void> {\n const entry = sessionWatchers.get(sessionId);\n if (!entry) return;\n sessionWatchers.delete(sessionId);\n entry.subscribers.clear();\n entry.watcher.stop();\n}\n\n/** Stop every active session watcher. Called on server shutdown. */\nexport function dis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,IAAI,cAAc,IAAI;AAAA,EAC5B;AACA,QAAM,EAAE,KAAK,SAAS,EAAE,MAAM,QAAQ,gBAAgB,SAAS,kBAAkB,CAAC;AACpF;AASA,eAAsB,eAAe,QAAgB,QAA+B;AAClF,QAAM,KAAK,aAAa,EAAE,QAAQ,OAAO,CAAoB;AAC7D,OAAK,OAAO,EAAE;AAKd,QAAM,OAAO,kBAAkB;AAC/B,aAAW,MAAM,EAAE;AACnB,QAAM,aAAa,MAAM,YAAY;AACnC,QAAI;AACJ,QAAI;AACF,aAAO,MAAM,gBAAgB;AAAA,IAC/B,SAAS,KAAK;AAIZ,mBAAa,gBAAgB,EAAE,cAAc,GAAG;AAChD;AAAA,IACF;AACA,QAAI,KAAM,OAAM,IAAI,cAAc,IAAI,EAAE,KAAK,EAAE,EAAE,MAAM,QAAQ,gBAAgB,EAAE,kBAAkB,CAAC;AAAA,QAC/F,OAAM,uBAAuB,EAAE,EAAE,MAAM,QAAQ,wBAAwB,EAAE,EAAE,CAAC;AAAA,EACnF,CAAC,EAAE,MAAM,QAAQ,gBAAgB,EAAE,mBAAmB,CAAC;AACzD;AAIO,SAAS,gBAAsB;AACpC,MAAI,aAAc,eAAc,YAAY;AAC5C,iBAAe;AACf,WAAS;AACT,SAAO,oBAAI,IAAI;AACf,aAAW,oBAAI,IAAI;AACrB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/pty-host.ts","../src/core/pty/pty-host.ts","../src/core/pty/pty-registry.ts","../src/core/pty/pty-session.ts","../src/core/pty/spawn-helper.ts"],"sourcesContent":["import fs from 'node:fs';\nimport chalk from 'chalk';\nimport type { CommandModule } from 'yargs';\nimport { startPtyHost } from '../core/pty/pty-host.js';\nimport {\n ensureHost,\n findHost,\n probeHostDetailed,\n PtyHostBusyError,\n PtyHostClient,\n PtyHostVersionError,\n} from '../core/pty/pty-host-client.js';\nimport { ensureFile, withFileLock } from '../core/platform/fs-safe.js';\nimport { killTree } from '../core/platform/process.js';\nimport { hostInfoPath, hostStartLockPath, readHostInfo } from '../core/pty/pty-host-protocol.js';\nimport { loadHistory } from '../core/sessions/history.js';\nimport { sessionIdFor } from '../core/sessions/session-id.js';\nimport { resolveWorkBinPath } from '../core/platform/work-bin.js';\n\nfunction info(message: string): void {\n process.stderr.write(message + '\\n');\n}\n\nexport type StopOutcome = 'stopped' | 'not-running' | 'stale-file' | 'unresponsive' | 'failed';\n\n/**\n * Kill the running host and its PTYs. The persisted session list stays, so\n * the next host start restores them with --continue.\n *\n * Only a PID that proves it's our host gets killed: it must answer /health\n * with the discovery file's token and report that same PID. The file\n * survives crashes and reboots (TerminateProcess skips cleanup), and\n * Windows reuses PIDs — force-killing the recorded PID and its tree blind\n * could take down an unrelated process. A stale file is just removed.\n */\nexport async function stopHost(kill: (pid: number) => boolean = killTree, probeTimeoutMs = 5000): Promise<StopOutcome> {\n const hostInfo = readHostInfo();\n if (!hostInfo) return 'not-running';\n // A busy host (restoring many sessions) can miss a short probe; give it\n // longer before concluding anything.\n const probe = await probeHostDetailed(hostInfo, probeTimeoutMs);\n if (probe.kind === 'timeout') {\n // Alive-but-slow must NOT be treated as stale: deleting the file would\n // orphan a live host, and --restart would then start a second one that\n // restores every session again. Keep the file, kill nothing.\n return 'unresponsive';\n }\n if (probe.kind !== 'host' || probe.pid !== hostInfo.pid) {\n // Nothing listening, or someone else on that port: the file is stale\n // (reboot, crash, PID/port reused). Remove it; kill nothing.\n try {\n fs.unlinkSync(hostInfoPath());\n } catch {\n /* */\n }\n return 'stale-file';\n }\n const ok = kill(hostInfo.pid);\n // TerminateProcess means the host never runs its own cleanup.\n try {\n fs.unlinkSync(hostInfoPath());\n } catch {\n /* */\n }\n return ok ? 'stopped' : 'failed';\n}\n\nasync function printStatus(): Promise<void> {\n let host;\n try {\n host = await findHost();\n } catch (err) {\n if (err instanceof PtyHostVersionError || err instanceof PtyHostBusyError) {\n info(chalk.yellow(err.message));\n return;\n }\n throw err;\n }\n if (!host) {\n info(chalk.gray('No PTY host running.'));\n return;\n }\n const ptys = await new PtyHostClient(host).list();\n const names = new Map(loadHistory().map((s) => [sessionIdFor(s), `${s.target} · ${s.branch}`]));\n info(chalk.gray(`PTY host PID ${host.pid}, port ${host.port} — ${ptys.length} session(s)`));\n for (const p of ptys) {\n const state = p.exited ? chalk.red('exited') : chalk.green('live');\n const tag = p.restored ? chalk.gray(' (restored)') : '';\n info(` ${state} ${names.get(p.id) ?? p.id}${tag} ${chalk.gray(p.cwd)}`);\n }\n}\n\nexport const ptyHostCommand: CommandModule = {\n command: 'pty-host',\n describe: false, // internal — started on demand by `work web` / `work attach`\n builder: (yargs) =>\n yargs\n .option('stop', { type: 'boolean', default: false, describe: 'Stop the PTY host (sessions restore on next start).' })\n .option('restart', { type: 'boolean', default: false, describe: 'Restart the PTY host, e.g. after upgrading work.' })\n .option('status', { type: 'boolean', default: false, describe: 'List the sessions the PTY host owns.' }),\n handler: async (argv) => {\n if (argv.status) {\n await printStatus();\n return;\n }\n if (argv.stop || argv.restart) {\n const outcome = await stopHost();\n info(\n chalk.gray(\n {\n stopped: 'Stopped the PTY host.',\n 'not-running': 'No PTY host running.',\n 'stale-file': 'No PTY host running (removed a stale discovery file; nothing was killed).',\n unresponsive: 'The PTY host is not responding (busy?). Nothing was stopped — try again in a moment.',\n failed: 'Could not stop the PTY host.',\n }[outcome],\n ),\n );\n if (outcome === 'failed' || outcome === 'unresponsive') {\n process.exitCode = 1;\n return; // never --restart on top of a host we couldn't stop\n }\n if (argv.stop) return;\n await new Promise((r) => setTimeout(r, 500));\n const host = await ensureHost(resolveWorkBinPath(process.argv[1]));\n info(chalk.gray(`PTY host restarted (PID ${host.pid}); sessions are being restored.`));\n return;\n }\n\n // Singleton: a second host would restore every saved session a second\n // time (two Claudes per conversation). Check-and-start under a lock; a\n // version-mismatched or busy (not answering in time) host still counts\n // as running.\n const lock = hostStartLockPath();\n ensureFile(lock, '');\n const handle = await withFileLock(lock, async () => {\n const running = await findHost().catch((err) =>\n err instanceof PtyHostVersionError || err instanceof PtyHostBusyError ? true : null,\n );\n if (running) return null;\n // Restore INSIDE the lock, as part of starting: startPtyHost writes\n // the discovery file and reads the saved list in the same tick,\n // before any request is served — so a client spawning a session\n // can't overwrite the list first (which lost every other saved\n // session), and a racing `work remove` waits for the restore.\n return startPtyHost();\n });\n if (!handle) {\n info(chalk.gray('PTY host already running.'));\n return;\n }\n info(chalk.gray(`PTY host listening on 127.0.0.1:${handle.info.port} (PID ${process.pid})`));\n const shutdown = () => {\n void handle.stop().finally(() => process.exit(0));\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n await new Promise(() => {});\n },\n};\n","import http from 'node:http';\nimport crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport { WebSocketServer } from 'ws';\nimport { atomicWriteFile } from '../platform/fs-safe.js';\nimport { PtyRegistry } from './pty-registry.js';\nimport { adoptLegacyRestoreList } from './pty-sessions-file.js';\nimport { bestEffort } from '../platform/best-effort.js';\nimport { PROTOCOL_VERSION, hostInfoPath, type ClientFrame, type HostInfo, type SpawnSpec } from './pty-host-protocol.js';\nimport { report } from '../platform/report.js';\n\nconst ATTACH_PATH = /^\\/ptys\\/([^/?]+)\\/attach(?:\\?|$)/;\nconst PTY_PATH = /^\\/ptys\\/([^/?]+)(\\/write|\\/screen)?$/;\nconst MAX_BODY = 1024 * 1024;\n\nexport interface PtyHostHandle {\n info: HostInfo;\n registry: PtyRegistry;\n /** Kill every PTY (state file kept for the next restore) and stop. */\n stop(): Promise<void>;\n}\n\nfunction readBody(req: http.IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n let size = 0;\n const chunks: Buffer[] = [];\n req.on('data', (c: Buffer) => {\n size += c.length;\n if (size > MAX_BODY) {\n reject(new Error('body too large'));\n req.destroy();\n return;\n }\n chunks.push(c);\n });\n req.on('end', () => {\n try {\n const text = Buffer.concat(chunks).toString('utf-8');\n resolve(text ? JSON.parse(text) : {});\n } catch (err) {\n reject(err);\n }\n });\n req.on('error', reject);\n });\n}\n\nfunction send(res: http.ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify(body));\n}\n\nfunction isSpawnSpec(v: unknown): v is SpawnSpec {\n if (!v || typeof v !== 'object') return false;\n const s = v as Partial<SpawnSpec>;\n return typeof s.cwd === 'string' && s.cwd.length > 0 && !!s.tool && typeof s.tool.cmd === 'string' && Array.isArray(s.tool.baseArgs);\n}\n\n/**\n * The PTY host: a small localhost-only server that owns every Claude PTY\n * so they survive `work web` restarts and rebuilds, and so any number of\n * clients (browser terminal via `work web`, a real terminal via\n * `work attach`) can attach to the same session.\n *\n * Auth: a random token written to `~/.work/pty-host.json` (user-only\n * readable location) must accompany every request — `x-work-token` header\n * for HTTP, `?token=` for the WebSocket upgrade. Plus a Host-header check\n * against DNS rebinding, same as the other local servers (§1.3).\n */\nexport async function startPtyHost(opts: { registry?: PtyRegistry; restore?: boolean; writeInfo?: boolean } = {}): Promise<PtyHostHandle> {\n const registry = opts.registry ?? new PtyRegistry();\n const token = crypto.randomBytes(24).toString('hex');\n let allowedHosts = new Set<string>();\n\n const authorized = (req: http.IncomingMessage, url: URL): boolean => {\n if (!req.headers.host || !allowedHosts.has(req.headers.host)) return false;\n const given = (req.headers['x-work-token'] as string | undefined) ?? url.searchParams.get('token') ?? '';\n const a = Buffer.from(given);\n const b = Buffer.from(token);\n return a.length === b.length && crypto.timingSafeEqual(a, b);\n };\n\n const server = http.createServer(async (req, res) => {\n const url = new URL(req.url ?? '/', 'http://localhost');\n if (!authorized(req, url)) return send(res, 403, { error: 'forbidden' });\n\n try {\n if (req.method === 'GET' && url.pathname === '/health') {\n return send(res, 200, { version: PROTOCOL_VERSION, pid: process.pid });\n }\n if (req.method === 'GET' && url.pathname === '/ptys') {\n return send(res, 200, registry.list());\n }\n const m = url.pathname.match(PTY_PATH);\n if (m) {\n const id = decodeURIComponent(m[1]);\n if (m[2] === '/screen' && req.method === 'GET') {\n const text = registry.screen(id);\n return text === null ? send(res, 404, { error: 'not found' }) : send(res, 200, { text });\n }\n if (m[2] === '/write' && req.method === 'POST') {\n const body = (await readBody(req)) as { data?: unknown };\n if (typeof body.data !== 'string') return send(res, 400, { error: 'data required' });\n return send(res, registry.write(id, body.data) ? 200 : 404, {});\n }\n if (!m[2] && req.method === 'POST') {\n const spec = await readBody(req);\n if (!isSpawnSpec(spec)) return send(res, 400, { error: 'invalid spawn spec' });\n if (!fs.existsSync(spec.cwd)) return send(res, 400, { error: 'cwd does not exist' });\n return send(res, 200, registry.spawn(id, spec));\n }\n if (!m[2] && req.method === 'GET') {\n const info = registry.get(id);\n return info ? send(res, 200, info) : send(res, 404, { error: 'not found' });\n }\n if (!m[2] && req.method === 'DELETE') {\n await registry.kill(id);\n return send(res, 200, {});\n }\n }\n return send(res, 404, { error: 'not found' });\n } catch (err) {\n return send(res, 500, { error: (err as Error).message });\n }\n });\n\n const wss = new WebSocketServer({ noServer: true });\n server.on('upgrade', (req, socket, head) => {\n const url = new URL(req.url ?? '/', 'http://localhost');\n const m = (req.url ?? '').match(ATTACH_PATH);\n if (!m || !authorized(req, url)) {\n socket.destroy();\n return;\n }\n const id = decodeURIComponent(m[1]);\n wss.handleUpgrade(req, socket, head, (ws) => {\n const attached = registry.attach(\n id,\n (data) => {\n try {\n ws.send(Buffer.from(data, 'utf-8'), { binary: true });\n } catch {\n /* */\n }\n },\n (code) => {\n try {\n ws.send(JSON.stringify({ type: 'exit', code }));\n ws.close(1000);\n } catch {\n /* */\n }\n },\n );\n if (!attached) {\n try {\n ws.send(JSON.stringify({ type: 'error', message: 'no such pty' }));\n ws.close(1011);\n } catch {\n /* */\n }\n return;\n }\n // Always first, even when empty: clients hold input and their own\n // resize until they've drawn it (see HostControlFrame 'replay'). The\n // screen as of the attach, then what came since (registry.attach).\n void attached.ready.then((replay) => {\n try {\n ws.send(JSON.stringify({ type: 'replay', ...replay }));\n } catch {\n /* */\n }\n if (attached.exitedWith !== null) {\n try {\n ws.send(JSON.stringify({ type: 'exit', code: attached.exitedWith }));\n ws.close(1000);\n } catch {\n /* */\n }\n return;\n }\n attached.start();\n });\n if (attached.exitedWith !== null) return;\n ws.on('message', (raw, isBinary) => {\n if (isBinary) return;\n let msg: ClientFrame;\n try {\n msg = JSON.parse(raw.toString('utf-8')) as ClientFrame;\n } catch {\n return;\n }\n if (msg.type === 'input' && typeof msg.data === 'string') {\n registry.write(id, msg.data);\n } else if (msg.type === 'resize' && Number.isInteger(msg.cols) && Number.isInteger(msg.rows)) {\n registry.resize(id, msg.cols, msg.rows);\n }\n });\n ws.on('close', () => attached.detach());\n ws.on('error', () => attached.detach());\n });\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(0, '127.0.0.1', () => resolve());\n });\n const port = (server.address() as { port: number }).port;\n allowedHosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);\n\n const info: HostInfo = { pid: process.pid, port, token, version: PROTOCOL_VERSION };\n if (opts.writeInfo !== false) {\n atomicWriteFile(hostInfoPath(), JSON.stringify(info));\n }\n if (opts.restore !== false) {\n // An older host that outlived the upgrade kept its list in the old\n // file: take it over before restoring (see adoptLegacyRestoreList).\n if (!opts.registry) {\n const adopted = bestEffort('adopt the old pty-sessions.json', () => adoptLegacyRestoreList(), null);\n if (adopted !== null && adopted !== undefined)\n report('info', `[pty-host] adopted ${adopted} session(s) from an older host's pty-sessions.json`);\n }\n await registry.restore();\n }\n\n return {\n info,\n registry,\n async stop() {\n registry.disposeAllKeepingState();\n wss.close();\n await new Promise<void>((r) => server.close(() => r()));\n if (opts.writeInfo !== false) {\n try {\n const cur = JSON.parse(fs.readFileSync(hostInfoPath(), 'utf-8')) as HostInfo;\n if (cur.pid === process.pid) fs.unlinkSync(hostInfoPath());\n } catch {\n /* */\n }\n }\n },\n };\n}\n","import fs from 'node:fs';\nimport { agentById } from '../agents/index.js';\nimport { loadConfig } from '../platform/config.js';\nimport { PtySession } from './pty-session.js';\nimport { atomicWriteFile, ensureFile, withFileLockSync } from '../platform/fs-safe.js';\nimport { dbPtySessions, type PtySessionsStore } from './pty-sessions-file.js';\nimport { isPersistedPty, keepEnv, type PersistedPty, type PersistedPtys, type PtyInfo, type SpawnSpec } from './pty-host-protocol.js';\nimport { logSwallowed, swallow } from '../platform/best-effort.js';\n\nconst REPLAY_MAX = 256 * 1024;\n\n/** How long an exited PTY lingers before it's dropped from the persisted\n * list. During a Windows shutdown/logoff the child Claudes are often killed\n * a moment BEFORE the host; dropping them immediately would erase exactly\n * the list we need to restore after the reboot. A host that's itself about\n * to die never reaches the timer. */\nconst FORGET_EXITED_MS = 5_000;\n\n/** Minimal PTY surface the registry needs — `PtySession` in production, a\n * fake in tests. */\nexport interface PtyLike {\n readonly pty: { pid: number };\n readonly exited: boolean;\n onExit?: (code: number) => void;\n setOutputHandler(h?: (data: string) => void): void;\n write(data: string): void;\n resize(cols: number, rows: number): void;\n dispose(): void;\n /** Serialized screen state (see PtySession.serialize). Optional so test\n * fakes can fall back to the raw replay buffer. */\n serialize?(): string;\n /** The serialized screen once everything written so far is parsed (see\n * PtySession.serializeSettled). Optional: a fake's screen is its raw buffer. */\n serializeSettled?(): Promise<string>;\n /** Visible screen as plain text (PtySession.screenText). */\n screenText?(): string;\n}\n\n/** What a newly attached client is sent first: the screen as it stands,\n * plus the grid it was drawn for. */\nexport interface ReplaySnapshot {\n data: string;\n cols: number;\n rows: number;\n}\n\nexport type PtySpawner = (spec: SpawnSpec & { resume: boolean }) => PtyLike;\n\nexport const defaultSpawner: PtySpawner = (spec) =>\n new PtySession(spec.cwd, spec.cols ?? 120, spec.rows ?? 32, undefined, {\n tool: spec.tool,\n resume: spec.resume,\n port: spec.port,\n unsafe: spec.unsafe,\n initialPrompt: spec.initialPrompt,\n env: spec.env,\n });\n\ninterface Entry {\n id: string;\n spec: Omit<PersistedPty, 'startedAt'>;\n pty: PtyLike;\n cols: number;\n rows: number;\n startedAt: string;\n restored: boolean;\n replay: string;\n subscribers: Set<(data: string) => void>;\n exitSubscribers: Set<(code: number) => void>;\n /** Set once the process exited (the entry lingers FORGET_EXITED_MS). */\n exitCode: number | null;\n /** When it last printed anything (ms): an idle Claude at its prompt prints nothing. */\n lastOutputAt: number;\n}\n\nexport interface RegistryDeps {\n /** The env variable names to keep for a restore (default: config `hostEnv`). */\n keepEnvNames?: () => string[];\n spawner?: PtySpawner;\n /** Its agent can resume a conversation in this folder (default: the agent's own check, agents/). */\n hasConversation?: (cwd: string, tool: string) => boolean;\n /** Where the restore list lives. Default: state.db. */\n sessions?: PtySessionsStore;\n /** Keep the restore list in this JSON file instead (tests, which must\n * never touch the user's state.db). */\n sessionsPath?: string;\n cwdExists?: (cwd: string) => boolean;\n}\n\n/** A restore list in a plain JSON file, written under the file lock. */\nexport function fileSessionsStore(file: string): PtySessionsStore {\n return {\n read() {\n const out: PersistedPtys = {};\n try {\n const raw = JSON.parse(fs.readFileSync(file, 'utf-8')) as unknown;\n if (raw && typeof raw === 'object') {\n for (const [id, entry] of Object.entries(raw)) if (isPersistedPty(entry)) out[id] = entry;\n }\n } catch {\n /* missing or unreadable: nothing to restore */\n }\n return out;\n },\n write(all) {\n ensureFile(file, '{}');\n withFileLockSync(file, () => atomicWriteFile(file, JSON.stringify(all, null, 2)));\n },\n };\n}\n\n/**\n * Owns every live PTY in the host process and mirrors the set to the\n * restore list (state.db `pty_sessions`, see pty-sessions-file.ts) so a\n * host restart (crash, `--restart`, reboot) can respawn them with\n * `--continue`. Writes replace the list in one transaction, so two hosts\n * racing at startup can't interleave.\n */\nexport class PtyRegistry {\n private readonly entries = new Map<string, Entry>();\n private readonly spawner: PtySpawner;\n private readonly hasConversation: (cwd: string, tool: string) => boolean;\n private readonly store: PtySessionsStore;\n private readonly cwdExists: (cwd: string) => boolean;\n private readonly keepEnvNames: () => string[];\n /** Serializes persistence writes inside this process. */\n private writeChain: Promise<void> = Promise.resolve();\n\n constructor(deps: RegistryDeps = {}) {\n this.spawner = deps.spawner ?? defaultSpawner;\n this.hasConversation = deps.hasConversation ?? ((cwd, tool) => agentById(tool).launch.canResume(cwd));\n this.store = deps.sessions ?? (deps.sessionsPath ? fileSessionsStore(deps.sessionsPath) : dbPtySessions);\n this.cwdExists = deps.cwdExists ?? ((p) => fs.existsSync(p));\n this.keepEnvNames = deps.keepEnvNames ?? (() => loadConfig()?.hostEnv ?? []);\n }\n\n list(): PtyInfo[] {\n return [...this.entries.values()].map((e) => this.info(e));\n }\n\n get(id: string): PtyInfo | null {\n const e = this.entries.get(id);\n return e ? this.info(e) : null;\n }\n\n /** Spawn unless a live PTY already exists for `id` (idempotent). */\n spawn(id: string, spec: SpawnSpec & { keptEnv?: Record<string, string> }, restored = false): PtyInfo {\n const existing = this.entries.get(id);\n if (existing && !existing.pty.exited) return this.info(existing);\n\n // A spawn from a shell keeps the variables config `hostEnv` names; a\n // restore — or a respawn without a shell (the Terminal tab) — runs with\n // the host's environment plus what its session kept.\n const kept = spec.env ? keepEnv(spec.env, this.keepEnvNames()) : (spec.keptEnv ?? existing?.spec.keptEnv);\n if (!spec.env && kept) spec = { ...spec, env: { ...(process.env as Record<string, string>), ...kept } };\n\n const cols = spec.cols ?? 120;\n const rows = spec.rows ?? 32;\n const pty = this.spawner({\n ...spec,\n cols,\n rows,\n // `--continue` hard-errors in a directory Claude never ran in;\n // `--fresh` opts out even when one exists.\n resume: !spec.fresh && this.hasConversation(spec.cwd, spec.tool.cmd),\n });\n const entry: Entry = {\n id,\n // Only what a restore may reuse: env/prompt/fresh are one-shot (and\n // env can hold secrets), so they never reach pty-sessions.json — but\n // the variables config `hostEnv` names do (keepEnv), so a restore after\n // a reboot gets the JAVA_HOME / PATH it was started with.\n spec: { cwd: spec.cwd, tool: spec.tool, port: spec.port, unsafe: spec.unsafe, ...(kept ? { keptEnv: kept } : {}) },\n pty,\n cols,\n rows,\n startedAt: new Date().toISOString(),\n restored,\n replay: '',\n subscribers: new Set(),\n exitSubscribers: new Set(),\n exitCode: null,\n lastOutputAt: Date.now(),\n };\n // Raw history is only a fallback for PTYs that can't serialize their\n // screen (test fakes) — real sessions replay PtySession.serialize().\n const keepRaw = !pty.serialize;\n pty.setOutputHandler((data) => {\n entry.lastOutputAt = Date.now();\n if (keepRaw) {\n entry.replay += data;\n if (entry.replay.length > REPLAY_MAX) {\n entry.replay = entry.replay.slice(entry.replay.length - REPLAY_MAX);\n }\n }\n for (const cb of entry.subscribers) {\n try {\n cb(data);\n } catch {\n /* subscriber gone */\n }\n }\n });\n pty.onExit = (code) => {\n entry.exitCode = code;\n for (const cb of entry.exitSubscribers) {\n try {\n cb(code);\n } catch {\n /* */\n }\n }\n setTimeout(() => {\n // Only forget it if nothing respawned under the same id meanwhile.\n if (this.entries.get(id) === entry) {\n this.entries.delete(id);\n void this.persist();\n }\n }, FORGET_EXITED_MS).unref?.();\n };\n this.entries.set(id, entry);\n void this.persist();\n return this.info(entry);\n }\n\n /** The live PTY's visible screen as text; null when there is none (or\n * it can't render one — test fakes). */\n screen(id: string): string | null {\n const e = this.entries.get(id);\n if (!e || e.pty.exited || !e.pty.screenText) return null;\n return e.pty.screenText();\n }\n\n write(id: string, data: string): boolean {\n const e = this.entries.get(id);\n if (!e || e.pty.exited) return false;\n e.pty.write(data);\n return true;\n }\n\n /** Last writer wins — with several clients attached (browser + a real\n * terminal) the one that most recently resized sets the grid, like\n * tmux's `window-size latest`. */\n resize(id: string, cols: number, rows: number): void {\n const e = this.entries.get(id);\n if (!e || e.pty.exited) return;\n if (cols < 2 || rows < 2 || (cols === e.cols && rows === e.rows)) return;\n e.cols = cols;\n e.rows = rows;\n e.pty.resize(cols, rows);\n }\n\n /**\n * Attach a client: the screen snapshot, a disposer, and — for a real\n * session — `ready`, the snapshot once the screen has parsed everything\n * that arrived before this attach, then `start()` once it was sent.\n *\n * Output reaches clients the moment it arrives, but the screen parses it a\n * moment later (xterm's write is queued). A client attaching in between got\n * a snapshot without that output and subscribed too late to be sent it: it\n * was lost (a Linux PTY answers fast enough to land there). So output\n * arriving from the attach on is held for this client until `start()`, and\n * `ready` is the screen exactly as of the attach — nothing lost, nothing\n * twice. `replay` (taken at once) is for screens with no parsing step.\n */\n attach(\n id: string,\n onData: (data: string) => void,\n onExit: (code: number) => void,\n ): {\n replay: ReplaySnapshot;\n ready: Promise<ReplaySnapshot>;\n start: () => void;\n detach: () => void;\n exitedWith: number | null;\n } | null {\n const e = this.entries.get(id);\n if (!e) return null;\n // Attaching to one that already exited (inside the linger window): its\n // exit subscribers have fired, so tell this client now — otherwise it\n // would sit on a dead screen, its input silently dropped.\n const exitedWith = e.pty.exited ? (e.exitCode ?? 0) : null;\n const settled = e.pty.serializeSettled;\n // Held output while the settled snapshot is taken; null = passed straight on.\n let held: string[] | null = settled ? [] : null;\n const sub = (d: string) => (held ? held.push(d) : onData(d));\n if (exitedWith === null) {\n e.subscribers.add(sub);\n e.exitSubscribers.add(onExit);\n }\n const snapshot = (data: string): ReplaySnapshot => ({ data, cols: e.cols, rows: e.rows });\n const replay = snapshot(e.pty.serialize?.() || e.replay);\n return {\n exitedWith,\n replay,\n ready: settled ? settled.call(e.pty).then((d) => snapshot(d || e.replay)) : Promise.resolve(replay),\n start: () => {\n const q = held;\n held = null;\n for (const d of q ?? []) onData(d);\n },\n detach: () => {\n e.subscribers.delete(sub);\n e.exitSubscribers.delete(onExit);\n },\n };\n }\n\n /**\n * Explicit kill (worktree removal, user closed the session). Removed\n * from the persisted list so it is NOT restored.\n *\n * Resolves once the process has actually exited (or after `timeoutMs`):\n * on Windows a just-killed process still holds its cwd for a moment, and\n * the caller's next step is usually deleting that very directory.\n */\n async kill(id: string, timeoutMs = 3000): Promise<void> {\n const e = this.entries.get(id);\n if (!e) return;\n this.entries.delete(id);\n // The terminals attached to it are told it ended (and so offer Enter to start it again):\n // dropped silently, a dashboard tab kept a connection to nothing and took no input.\n const attached = [...e.exitSubscribers];\n e.subscribers.clear();\n e.exitSubscribers.clear();\n const exited = e.pty.exited\n ? Promise.resolve(e.exitCode ?? 0)\n : new Promise<number>((resolve) => {\n const timer = setTimeout(() => resolve(0), timeoutMs);\n e.pty.onExit = (code) => {\n clearTimeout(timer);\n resolve(code);\n };\n });\n e.pty.dispose();\n const [code] = await Promise.all([exited, this.persist()]);\n for (const cb of attached) {\n try {\n cb(code);\n } catch {\n /* that client is gone */\n }\n }\n }\n\n /**\n * Respawn everything in the persisted list. Called once at host startup.\n * Worktrees that no longer exist are dropped.\n */\n async restore(): Promise<string[]> {\n const saved = this.readPersisted();\n const restored: string[] = [];\n for (const [id, entry] of Object.entries(saved)) {\n if (!this.cwdExists(entry.cwd)) continue;\n try {\n this.spawn(id, entry, true);\n restored.push(id);\n } catch (err) {\n // One bad entry (tool missing, cwd unreadable) mustn't block the rest.\n logSwallowed(`restore session ${id} in ${entry.cwd}`, err);\n }\n }\n await this.persist();\n return restored;\n }\n\n /** Host shutdown: kill every PTY but KEEP the persisted list, so the next\n * host start restores them. */\n disposeAllKeepingState(): void {\n for (const e of this.entries.values()) {\n e.pty.onExit = undefined;\n e.subscribers.clear();\n e.exitSubscribers.clear();\n e.pty.dispose();\n }\n this.entries.clear();\n }\n\n /** Resolves once every queued persistence write has landed. */\n flush(): Promise<void> {\n return this.writeChain;\n }\n\n private info(e: Entry): PtyInfo {\n return {\n id: e.id,\n cwd: e.spec.cwd,\n pid: e.pty.pty.pid,\n exited: e.pty.exited,\n cols: e.cols,\n rows: e.rows,\n startedAt: e.startedAt,\n restored: e.restored,\n clients: e.subscribers.size,\n lastOutputAt: new Date(e.lastOutputAt).toISOString(),\n tool: e.spec.tool.cmd,\n };\n }\n\n private readPersisted(): PersistedPtys {\n try {\n return this.store.read();\n } catch (err) {\n logSwallowed('read the PTY restore list', err);\n return {};\n }\n }\n\n private persist(): Promise<void> {\n const snapshot: PersistedPtys = {};\n // Exited entries still lingering (see FORGET_EXITED_MS) are kept on\n // purpose — dropping them on an unrelated write would defeat the delay.\n for (const e of this.entries.values()) {\n snapshot[e.id] = { ...e.spec, startedAt: e.startedAt };\n }\n this.writeChain = this.writeChain\n .then(() => this.store.write(snapshot))\n .catch(swallow('persist the PTY restore list (next change retries)'));\n return this.writeChain;\n }\n}\n","import pty, { type IPty } from 'node-pty';\nimport { agentById } from '../agents/index.js';\nimport crossSpawn from 'cross-spawn';\nimport xtermHeadless from '@xterm/headless';\nimport xtermSerialize from '@xterm/addon-serialize';\nimport { debug } from '../platform/logger.js';\nimport { buildAiLaunchArgs, type AiToolSpec } from '../platform/ai-launcher.js';\nimport childProcess from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { makeSpawnHelperExecutable } from './spawn-helper.js';\nimport { report } from '../platform/report.js';\n\ntype Fork = typeof childProcess.fork;\nconst HIDDEN = Symbol.for('work.forkHidesConsole');\n\n/**\n * Make `fork()` hide the child's console window unless the caller says\n * otherwise. node-pty kills a Windows PTY by forking a helper\n * (conpty_console_list_agent) without `windowsHide`; from the PTY host —\n * detached, so it has no console of its own — Windows gave every such helper\n * a new, visible console: a window flashed on each Archive or stop.\n */\nexport function hideForkConsoles(cp: { fork: Fork }): void {\n if ((cp.fork as { [HIDDEN]?: true })[HIDDEN]) return;\n // windowsHide isn't in @types/node's ForkOptions, but fork passes its\n // options on to spawn, which honours it.\n const orig = cp.fork as unknown as (modulePath: string | URL, args: readonly string[], options: object) => ReturnType<Fork>;\n const wrapped = function (modulePath: string | URL, a?: unknown, b?: unknown) {\n const args = Array.isArray(a) ? (a as readonly string[]) : [];\n const options = (Array.isArray(a) || a == null ? b : a) ?? {};\n return orig.call(cp, modulePath, args, { windowsHide: true, ...(options as object) });\n } as unknown as Fork & { [HIDDEN]?: true };\n wrapped[HIDDEN] = true;\n cp.fork = wrapped;\n}\nif (process.platform === 'win32') hideForkConsoles(childProcess);\n\nlet spawnHelperChecked = false;\n/**\n * Once per process, before the first terminal: node-pty's spawn-helper must\n * be executable on macOS and Linux, or every terminal fails with\n * \"posix_spawnp failed\" (spawn-helper.ts). Fixes an install that has it\n * wrong; says so when it can't.\n */\nfunction ensureSpawnHelper(): void {\n if (spawnHelperChecked) return;\n spawnHelperChecked = true;\n try {\n const dir = path.dirname(createRequire(import.meta.url).resolve('node-pty/package.json'));\n const { fixed, failed } = makeSpawnHelperExecutable(dir);\n for (const file of fixed) debug('made node-pty spawn-helper executable', file);\n for (const { file, error } of failed)\n report(\n 'warn',\n `node-pty's spawn-helper isn't executable and couldn't be made so (${error}): terminals can't start. Run: chmod +x \"${file}\"`,\n );\n } catch (err) {\n debug('spawn-helper check failed', (err as Error).message);\n }\n}\n\nconst { Terminal } = xtermHeadless;\nconst { SerializeAddon } = xtermSerialize;\n\nexport interface PtyAiOptions {\n /** Resolved AI tool spec (from `getAiTool(config)`). */\n tool: AiToolSpec;\n unsafe?: boolean;\n resume?: boolean;\n promptFile?: string;\n /** Initial prompt passed on the command line (escaped — see\n * resolvePtyCommand). */\n initialPrompt?: string;\n /** Dev-server port exposed to the launched process as $PORT. */\n port?: number;\n /** Environment for the process instead of this process's own — the PTY\n * host passes the launching shell's env so PATH, AWS_PROFILE, venvs,\n * WT_SESSION etc. match where the user ran `work tree`. */\n env?: Record<string, string>;\n}\n\ntype CrossSpawnParse = (\n command: string,\n args: string[],\n options: { env?: NodeJS.ProcessEnv; cwd?: string },\n) => { command: string; args: string[]; file?: string; options: { windowsVerbatimArguments?: boolean } };\n\n/**\n * Turn `cmd args` into what node-pty should spawn, safely.\n *\n * Windows: resolved the way cross-spawn (used by `work tree`'s direct\n * launch) resolves it — a real .exe is spawned directly with normal argv\n * quoting; a .cmd/.bat shim goes through `cmd.exe /d /s /c \"…\"` with\n * cmd-metacharacters caret-escaped, handed to node-pty as a verbatim\n * command line. Never a bare `cmd.exe /c cmd args`: that lets `&`, `|`, `%`\n * in an argument (a prompt, a path) run as commands (§1.1).\n */\nexport function resolvePtyCommand(\n cmd: string,\n args: string[],\n opts: { env?: NodeJS.ProcessEnv; cwd?: string } = {},\n): { file: string; args: string[] | string } {\n if (process.platform !== 'win32') return { file: cmd, args };\n const parse = (crossSpawn as unknown as { _parse: CrossSpawnParse })._parse;\n const parsed = parse(cmd, args, opts);\n if (parsed.options.windowsVerbatimArguments) {\n return { file: parsed.command, args: parsed.args.join(' ') };\n }\n return { file: parsed.file ?? parsed.command, args: parsed.args };\n}\n\nexport class PtySession {\n readonly pty: IPty;\n readonly terminal: InstanceType<typeof Terminal>;\n private readonly serializer = new SerializeAddon();\n readonly cwd: string;\n private outputHandler?: (data: string) => void;\n private _exited = false;\n private _outputBuffer = '';\n private _loggedOutput = false;\n onExit?: (code: number) => void;\n\n constructor(cwd: string, cols: number, rows: number, command?: { cmd: string; args: string[] }, aiOptions?: PtyAiOptions) {\n this.cwd = cwd;\n this.terminal = new Terminal({\n cols,\n rows,\n scrollback: 200,\n allowProposedApi: true,\n });\n this.terminal.loadAddon(this.serializer);\n\n let rawCmd: string;\n let rawArgs: string[];\n\n if (command) {\n // Custom command (e.g. work tree)\n rawCmd = command.cmd;\n rawArgs = command.args;\n } else if (aiOptions) {\n // Launch configured AI tool (default: claude)\n ({ cmd: rawCmd, args: rawArgs } = buildAiLaunchArgs(aiOptions.tool, {\n unsafe: aiOptions.unsafe,\n resume: aiOptions.resume,\n promptFile: aiOptions.promptFile,\n initialPrompt: aiOptions.initialPrompt,\n }));\n } else {\n throw new Error('PtySession requires either a custom command or aiOptions');\n }\n\n // A session of its own: never another agent's child (its adapter knows what a parent sets).\n const env: Record<string, string> = Object.fromEntries(\n Object.entries(agentById(aiOptions?.tool.cmd ?? 'claude').launch.cleanEnv(aiOptions?.env ?? process.env)).filter(\n (e): e is [string, string] => e[1] != null,\n ),\n );\n if (aiOptions?.port !== undefined) {\n env.PORT = String(aiOptions.port);\n }\n const { file: spawnCmd, args: spawnArgs } = resolvePtyCommand(rawCmd, rawArgs, { env, cwd });\n\n debug('PtySession spawn', { spawnCmd, spawnArgs, cwd, cols, rows });\n ensureSpawnHelper();\n this.pty = pty.spawn(spawnCmd, spawnArgs, {\n name: 'xterm-256color',\n cwd,\n cols,\n rows,\n env,\n });\n debug('PtySession spawned pid=', this.pty.pid);\n\n this.pty.onData((data) => {\n this.terminal.write(data);\n this.outputHandler?.(data);\n // Log first 500 chars of PTY output for debugging early exits\n if (!this._loggedOutput) {\n this._outputBuffer = (this._outputBuffer || '') + data;\n if (this._outputBuffer.length > 500) {\n debug('PtySession first output', { cwd, output: this._outputBuffer.slice(0, 500) });\n this._loggedOutput = true;\n this._outputBuffer = '';\n }\n }\n });\n\n this.pty.onExit(({ exitCode }) => {\n if (!this._loggedOutput && this._outputBuffer) {\n debug('PtySession output before exit', { cwd, output: this._outputBuffer.slice(0, 500) });\n }\n this._outputBuffer = '';\n debug('PtySession exited', { cwd, exitCode });\n this._exited = true;\n this.onExit?.(exitCode);\n });\n }\n\n get exited() {\n return this._exited;\n }\n\n write(data: string) {\n if (!this._exited) {\n try {\n this.pty.write(data);\n } catch {\n /* PTY already exited */\n }\n }\n }\n\n resize(cols: number, rows: number) {\n if (!this._exited) {\n try {\n this.pty.resize(cols, rows);\n } catch {\n // PTY already exited natively before our flag was set — ignore\n }\n this.terminal.resize(cols, rows);\n }\n }\n\n /**\n * The current screen + scrollback as escape sequences that redraw it\n * exactly (colors, cursor, modes, alt screen). What a late attacher is\n * sent instead of raw output history — raw bytes can start mid-sequence\n * and were drawn for another client's grid (VS Code does the same).\n */\n serialize(): string {\n try {\n return this.serializer.serialize();\n } catch {\n return '';\n }\n }\n\n /**\n * serialize(), once the screen has parsed everything written to it so far:\n * xterm queues writes, and a write's callback runs right after that write\n * is parsed — before any written later. What a new client is sent first.\n */\n serializeSettled(): Promise<string> {\n return new Promise((resolve) => {\n try {\n this.terminal.write('', () => resolve(this.serialize()));\n } catch {\n resolve(this.serialize());\n }\n });\n }\n\n /** The visible screen as plain text, one line per row (no colors).\n * What the dashboard checks before answering a prompt by keystroke. */\n screenText(): string {\n try {\n const buf = this.terminal.buffer.active;\n const lines: string[] = [];\n for (let y = buf.viewportY; y < buf.viewportY + this.terminal.rows; y++) {\n lines.push(buf.getLine(y)?.translateToString(true) ?? '');\n }\n return lines.join('\\n');\n } catch {\n return '';\n }\n }\n\n setOutputHandler(handler?: (data: string) => void) {\n this.outputHandler = handler;\n }\n\n dispose() {\n this.setOutputHandler(undefined);\n if (!this._exited) {\n try {\n this.pty.kill();\n } catch {\n /* PTY already exited */\n }\n }\n this.terminal.dispose();\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\n/** The file system calls this needs (tests pass a fake one). */\nexport interface ModeFs {\n statSync(p: string): { mode: number };\n chmodSync(p: string, mode: number): void;\n}\n\nexport interface SpawnHelperCheck {\n /** Made executable. */\n fixed: string[];\n /** Not executable, and chmod failed (a root-owned global install): terminals can't start. */\n failed: Array<{ file: string; error: string }>;\n}\n\n/**\n * node-pty starts every terminal on macOS and Linux through its\n * `spawn-helper`. Its npm package ships the prebuilt one without the\n * executable bit, and its install script — which would fix that — doesn't\n * always run (npm skipping dependency install scripts; the desktop app's\n * 2.0.2 shipped it 0644): every terminal then fails with \"posix_spawnp\n * failed\". Make it executable where it lies: the prebuild for this\n * platform, and a locally built one. Nothing on Windows.\n */\nexport function makeSpawnHelperExecutable(\n ptyDir: string,\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n f: ModeFs = fs,\n): SpawnHelperCheck {\n const out: SpawnHelperCheck = { fixed: [], failed: [] };\n if (platform === 'win32') return out;\n for (const file of [\n path.join(ptyDir, 'prebuilds', `${platform}-${arch}`, 'spawn-helper'),\n path.join(ptyDir, 'build', 'Release', 'spawn-helper'),\n ]) {\n let mode: number;\n try {\n mode = f.statSync(file).mode;\n } catch {\n continue; // not there: the other one is used\n }\n if ((mode & 0o111) === 0o111) continue;\n try {\n f.chmodSync(file, (mode & 0o777) | 0o755);\n out.fixed.push(file);\n } catch (err) {\n out.failed.push({ file, error: (err as Error).message });\n }\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,SAAQ;AACf,OAAO,WA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