@moberg_hr/work-tree 2.0.11 → 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 (113) hide show
  1. package/dist/{answer-6UVHVEGQ.js → answer-IL5AQHRO.js} +4 -4
  2. package/dist/{attach-6Q6HGPCM.js → attach-MFU4KN47.js} +7 -7
  3. package/dist/bin.js +2 -2
  4. package/dist/{block-46DPS75I.js → block-OXGEQ2PZ.js} +4 -4
  5. package/dist/{broadcast-OGOEQX4Z.js → broadcast-UJURJNEK.js} +2 -2
  6. package/dist/{catchup-TTAC3GMX.js → catchup-HN4VL5XK.js} +4 -4
  7. package/dist/chunk-4KNBN2OF.js +9 -0
  8. package/dist/{chunk-4PP27RI7.js → chunk-7GQCPGKQ.js} +4 -4
  9. package/dist/{chunk-UAAH334K.js → chunk-7JPCVEOY.js} +35 -4
  10. package/dist/chunk-7JPCVEOY.js.map +1 -0
  11. package/dist/{chunk-Y6VPABC3.js → chunk-BSFL3WDR.js} +32 -31
  12. package/dist/chunk-BSFL3WDR.js.map +1 -0
  13. package/dist/{chunk-7HGABVGR.js → chunk-E3Y4ZACK.js} +18 -1
  14. package/dist/chunk-E3Y4ZACK.js.map +1 -0
  15. package/dist/{chunk-WG3BMHKU.js → chunk-EU3BS5A6.js} +2 -2
  16. package/dist/{chunk-AFV5S6UV.js → chunk-F375JY4M.js} +3 -3
  17. package/dist/{chunk-D4FUDMMX.js → chunk-FX4IA5U4.js} +3 -3
  18. package/dist/{chunk-HBXDIRM4.js → chunk-KSIXTTO6.js} +3 -3
  19. package/dist/{chunk-RMICESXA.js → chunk-KUWFGPGW.js} +6 -6
  20. package/dist/{chunk-ACXPSQJR.js → chunk-MI3PS2SH.js} +18 -1
  21. package/dist/{chunk-ACXPSQJR.js.map → chunk-MI3PS2SH.js.map} +1 -1
  22. package/dist/{chunk-AVRDRZ4D.js → chunk-OZIR2255.js} +62 -8
  23. package/dist/chunk-OZIR2255.js.map +1 -0
  24. package/dist/{chunk-RG63ACAK.js → chunk-PVN5IGDZ.js} +11 -10
  25. package/dist/chunk-PVN5IGDZ.js.map +1 -0
  26. package/dist/chunk-TNJF7T33.js +17 -0
  27. package/dist/chunk-TNJF7T33.js.map +1 -0
  28. package/dist/{chunk-SRIYY5HL.js → chunk-U4UB4LG6.js} +2 -2
  29. package/dist/{cleanup-OO3DCPGC.js → cleanup-LRT6J36R.js} +10 -10
  30. package/dist/{cli-I6N4U4GN.js → cli-VGUJI5WG.js} +3 -3
  31. package/dist/{fork-WTNAUILU.js → fork-RJ3ZPPWT.js} +8 -8
  32. package/dist/{hook-OTPVWY52.js → hook-CA5X3VKU.js} +3 -3
  33. package/dist/{move-CE5NIZKL.js → move-OLXCDNA3.js} +2 -2
  34. package/dist/{note-2JHWK6CV.js → note-JOR53JP4.js} +4 -4
  35. package/dist/{pin-UOW5VW42.js → pin-DAWKCVB2.js} +4 -4
  36. package/dist/{pr-74X5MOPX.js → pr-RKOVRSHC.js} +3 -3
  37. package/dist/{prune-L3VXZUIE.js → prune-UYCQOEUF.js} +9 -9
  38. package/dist/{pty-host-5Z3GYXTW.js → pty-host-X3QK2LSK.js} +115 -14
  39. package/dist/pty-host-X3QK2LSK.js.map +1 -0
  40. package/dist/{read-G7CVQRH6.js → read-IKDSIDJD.js} +4 -4
  41. package/dist/{remove-NVQ2JNMA.js → remove-6XACPXUU.js} +8 -8
  42. package/dist/restart-6ZAFDRBO.js +70 -0
  43. package/dist/restart-6ZAFDRBO.js.map +1 -0
  44. package/dist/{screen-XSBZHJNW.js → screen-KUXSDDLB.js} +4 -4
  45. package/dist/{section-BWZW3E2I.js → section-QLUIAYAV.js} +4 -4
  46. package/dist/{send-4E7CD6PL.js → send-V6LL6YR6.js} +4 -4
  47. package/dist/{sessions-4LFKWTBZ.js → sessions-MKXREA2M.js} +7 -7
  48. package/dist/{snooze-SSSA656T.js → snooze-JXI7VZJ4.js} +4 -4
  49. package/dist/{start-5LODG4WG.js → start-5XFUYT6I.js} +4 -4
  50. package/dist/{stop-OFQFHRXD.js → stop-PFI7J2CS.js} +4 -4
  51. package/dist/{sync-FDXM5EFD.js → sync-MSU7QJWN.js} +9 -9
  52. package/dist/{time-IIAXBSE7.js → time-VDRCEIYQ.js} +4 -4
  53. package/dist/{tree-7S4DUZRZ.js → tree-MOIO4GQL.js} +5 -5
  54. package/dist/{update-7ZE4CG7T.js → update-DXIY6BEX.js} +4 -4
  55. package/dist/{wait-TGQLNTE7.js → wait-KPH5BQUD.js} +4 -4
  56. package/dist/wd-bin.js +2 -2
  57. package/dist/web/assets/{PtyView-CAaXDb9_.js → PtyView-D1TEpjVE.js} +2 -2
  58. package/dist/web/assets/{PtyView-CAaXDb9_.js.map → PtyView-D1TEpjVE.js.map} +1 -1
  59. package/dist/web/assets/index-BVeughC2.css +1 -0
  60. package/dist/web/assets/index-DoMf82kx.js +118 -0
  61. package/dist/web/assets/index-DoMf82kx.js.map +1 -0
  62. package/dist/web/index.html +2 -2
  63. package/dist/{web-NFKTIH4M.js → web-6AOR3MIE.js} +490 -144
  64. package/dist/web-6AOR3MIE.js.map +1 -0
  65. package/npm-shrinkwrap.json +2 -2
  66. package/package.json +1 -1
  67. package/dist/chunk-7HGABVGR.js.map +0 -1
  68. package/dist/chunk-AVRDRZ4D.js.map +0 -1
  69. package/dist/chunk-RG63ACAK.js.map +0 -1
  70. package/dist/chunk-UAAH334K.js.map +0 -1
  71. package/dist/chunk-W5B4NLBI.js +0 -9
  72. package/dist/chunk-Y6VPABC3.js.map +0 -1
  73. package/dist/pty-host-5Z3GYXTW.js.map +0 -1
  74. package/dist/web/assets/index-3r-glBYq.js +0 -118
  75. package/dist/web/assets/index-3r-glBYq.js.map +0 -1
  76. package/dist/web/assets/index-Dk0Q1Qib.css +0 -1
  77. package/dist/web-NFKTIH4M.js.map +0 -1
  78. /package/dist/{answer-6UVHVEGQ.js.map → answer-IL5AQHRO.js.map} +0 -0
  79. /package/dist/{attach-6Q6HGPCM.js.map → attach-MFU4KN47.js.map} +0 -0
  80. /package/dist/{block-46DPS75I.js.map → block-OXGEQ2PZ.js.map} +0 -0
  81. /package/dist/{broadcast-OGOEQX4Z.js.map → broadcast-UJURJNEK.js.map} +0 -0
  82. /package/dist/{catchup-TTAC3GMX.js.map → catchup-HN4VL5XK.js.map} +0 -0
  83. /package/dist/{chunk-W5B4NLBI.js.map → chunk-4KNBN2OF.js.map} +0 -0
  84. /package/dist/{chunk-4PP27RI7.js.map → chunk-7GQCPGKQ.js.map} +0 -0
  85. /package/dist/{chunk-WG3BMHKU.js.map → chunk-EU3BS5A6.js.map} +0 -0
  86. /package/dist/{chunk-AFV5S6UV.js.map → chunk-F375JY4M.js.map} +0 -0
  87. /package/dist/{chunk-D4FUDMMX.js.map → chunk-FX4IA5U4.js.map} +0 -0
  88. /package/dist/{chunk-HBXDIRM4.js.map → chunk-KSIXTTO6.js.map} +0 -0
  89. /package/dist/{chunk-RMICESXA.js.map → chunk-KUWFGPGW.js.map} +0 -0
  90. /package/dist/{chunk-SRIYY5HL.js.map → chunk-U4UB4LG6.js.map} +0 -0
  91. /package/dist/{cleanup-OO3DCPGC.js.map → cleanup-LRT6J36R.js.map} +0 -0
  92. /package/dist/{cli-I6N4U4GN.js.map → cli-VGUJI5WG.js.map} +0 -0
  93. /package/dist/{fork-WTNAUILU.js.map → fork-RJ3ZPPWT.js.map} +0 -0
  94. /package/dist/{hook-OTPVWY52.js.map → hook-CA5X3VKU.js.map} +0 -0
  95. /package/dist/{move-CE5NIZKL.js.map → move-OLXCDNA3.js.map} +0 -0
  96. /package/dist/{note-2JHWK6CV.js.map → note-JOR53JP4.js.map} +0 -0
  97. /package/dist/{pin-UOW5VW42.js.map → pin-DAWKCVB2.js.map} +0 -0
  98. /package/dist/{pr-74X5MOPX.js.map → pr-RKOVRSHC.js.map} +0 -0
  99. /package/dist/{prune-L3VXZUIE.js.map → prune-UYCQOEUF.js.map} +0 -0
  100. /package/dist/{read-G7CVQRH6.js.map → read-IKDSIDJD.js.map} +0 -0
  101. /package/dist/{remove-NVQ2JNMA.js.map → remove-6XACPXUU.js.map} +0 -0
  102. /package/dist/{screen-XSBZHJNW.js.map → screen-KUXSDDLB.js.map} +0 -0
  103. /package/dist/{section-BWZW3E2I.js.map → section-QLUIAYAV.js.map} +0 -0
  104. /package/dist/{send-4E7CD6PL.js.map → send-V6LL6YR6.js.map} +0 -0
  105. /package/dist/{sessions-4LFKWTBZ.js.map → sessions-MKXREA2M.js.map} +0 -0
  106. /package/dist/{snooze-SSSA656T.js.map → snooze-JXI7VZJ4.js.map} +0 -0
  107. /package/dist/{start-5LODG4WG.js.map → start-5XFUYT6I.js.map} +0 -0
  108. /package/dist/{stop-OFQFHRXD.js.map → stop-PFI7J2CS.js.map} +0 -0
  109. /package/dist/{sync-FDXM5EFD.js.map → sync-MSU7QJWN.js.map} +0 -0
  110. /package/dist/{time-IIAXBSE7.js.map → time-VDRCEIYQ.js.map} +0 -0
  111. /package/dist/{tree-7S4DUZRZ.js.map → tree-MOIO4GQL.js.map} +0 -0
  112. /package/dist/{update-7ZE4CG7T.js.map → update-DXIY6BEX.js.map} +0 -0
  113. /package/dist/{wait-TGQLNTE7.js.map → wait-KPH5BQUD.js.map} +0 -0
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@moberg_hr/work-tree",
3
- "version": "2.0.11",
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.11",
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.11",
3
+ "version": "2.0.13",
4
4
  "description": "Cross-platform Git worktree manager for multiple repositories",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/comments/comment-file-store.ts"],"sourcesContent":["import { createCommentStore, type CommentInput, type CommentStore } from './comment-store.js';\nimport { json, tx, withDb, type Db } from '../platform/db.js';\nimport type { Comment } from './comment-types.js';\n\n/**\n * Persistent comment store: the pure in-memory model (comment-store.ts)\n * over state.db's `comments` table, one \"store\" per session id (or\n * `scope-<hash>` for a `wd` review). Every mutation runs in a write\n * transaction that first reloads the store from the database, so\n * concurrent writers in other processes (`work broadcast`, the hook, a\n * second work web tab) are never lost.\n *\n * (The name is historical: this used to be one JSON file per store.)\n */\nexport interface CommentFileStore extends CommentStore {\n /** Drop the cached in-memory store and reload from disk. */\n reload(): void;\n /** Remove every comment (memory + disk). Returns how many were removed.\n * Used when a finished scope review is re-registered — the new run\n * starts from a clean slate instead of replaying the old comments. */\n clearAll(): number;\n}\n\nfunction isComment(x: unknown): x is Comment {\n const c = x as Comment | null;\n return !!c && typeof c === 'object' && typeof c.id === 'string' && typeof c.body === 'string';\n}\n\nfunction readRows(d: Db, store: string): Comment[] {\n return (d.prepare('SELECT data FROM comments WHERE store = ? ORDER BY rowid').all(store) as Array<{ data: string }>)\n .map((r) => json.parse(r.data))\n .filter(isComment);\n}\n\n/** Replace a store's rows with `comments` (in their order). */\nfunction writeRows(d: Db, store: string, comments: Comment[]): void {\n d.prepare('DELETE FROM comments WHERE store = ?').run(store);\n const ins = d.prepare('INSERT OR REPLACE INTO comments (store, id, data) VALUES (?, ?, ?)');\n for (const c of comments) ins.run(store, c.id, JSON.stringify(c));\n}\n\n/** A store's comments straight from the database: current even when\n * another process wrote since this process cached the store. */\nexport function readStoreComments(store: string): Comment[] {\n return withDb((d) => readRows(d, store));\n}\n\nconst cache = new Map<string, CommentFileStore>();\n\nexport function getCommentFileStore(sessionId: string): CommentFileStore {\n const existing = cache.get(sessionId);\n if (existing) return existing;\n\n const inner = createCommentStore();\n\n /** Replace the in-memory contents with the current on-disk contents.\n * Used to reconcile before a mutation so concurrent writers (e.g. a\n * `work broadcast` process appending under the same lock) aren't lost. */\n function reloadFrom(rows: Comment[]): void {\n const list = inner.list() as Comment[];\n list.length = 0;\n for (const c of rows) list.push(c);\n }\n function reloadInner(): void {\n reloadFrom(withDb((d) => readRows(d, sessionId)));\n }\n\n // Seed from the database.\n reloadInner();\n\n /**\n * A read-modify-write of this store in one write transaction: reload the\n * in-memory model from the database (so it reflects other processes'\n * writes), apply `mutate`, persist. `persisted` reports whether anything\n * changed, so a no-op (e.g. removing a missing id) skips the write.\n */\n function lockedMutate<T>(mutate: () => { value: T; persisted: boolean }): T {\n return tx((d) => {\n reloadFrom(readRows(d, sessionId));\n const { value, persisted } = mutate();\n if (persisted) writeRows(d, sessionId, inner.snapshot());\n return value;\n });\n }\n\n const store: CommentFileStore = {\n // Reads reload first (one indexed query): `work broadcast` and the\n // hooks write to the same store from other processes, and a list\n // served from this process's memory didn't show them until something\n // here mutated. The in-memory model is for mutations, not a cache.\n list: () => {\n reloadInner();\n return inner.list();\n },\n snapshot: () => {\n reloadInner();\n return inner.snapshot();\n },\n post(input: CommentInput) {\n return lockedMutate(() => {\n const c = inner.post(input);\n return { value: c, persisted: true };\n });\n },\n remove(id: string) {\n return lockedMutate(() => {\n const r = inner.remove(id);\n return { value: r, persisted: r };\n });\n },\n setResolved(id: string, resolved: boolean) {\n return lockedMutate(() => {\n const c = inner.setResolved(id, resolved);\n return { value: c, persisted: c !== null };\n });\n },\n submit(summary: string | undefined) {\n return lockedMutate(() => {\n const result = inner.submit(summary);\n return { value: result, persisted: true };\n });\n },\n discardDrafts() {\n return lockedMutate(() => {\n const n = inner.discardDrafts();\n return { value: n, persisted: n > 0 };\n });\n },\n reload() {\n reloadInner();\n },\n clearAll() {\n return lockedMutate(() => {\n const list = inner.list() as Comment[];\n const n = list.length;\n list.length = 0;\n return { value: n, persisted: n > 0 };\n });\n },\n };\n cache.set(sessionId, store);\n return store;\n}\n\n/** Clear the in-memory cache. Test/server-shutdown hook. */\nexport function clearCommentStoreCache(): void {\n cache.clear();\n}\n"],"m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AI,WAAW,KAAK;AAC1B,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/sessions/session-wire.ts","../src/core/sessions/session-meta.ts","../src/core/conversations/context-usage.ts","../src/core/conversations/session-title.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { agentOf, agentWire } from '../agents/index.js';\nimport { readStatus } from '../status/session-status.js';\nimport { snoozeActive, type Snooze } from '../rail/snooze.js';\nimport { withLiveClaude } from '../status/session-status.js';\nimport path from 'node:path';\nimport { readSessionMeta } from './session-meta.js';\nimport { checkedOutBranch } from '../git/git-head.js';\nimport { sessionIdFor } from './web-state.js';\nimport { readContextUsage } from '../conversations/context-usage.js';\nimport { bestEffort } from '../platform/best-effort.js';\nimport type { WorktreeSession } from './history.js';\nimport type {\n DiffStat,\n SessionArchiveInfo,\n SessionAttention,\n SessionClaudes,\n SessionWire,\n BlockerWire,\n PrStageWire,\n} from '../api-types.js';\nimport { archiveDirFor, keptList, readArchive } from '../archive/session-archive.js';\nimport { sessionTitle } from '../conversations/session-title.js';\nimport { prStageOf, STAGE_WANTS_YOU, type StagePr } from '../pr/pr-stage.js';\nimport { isLeftover } from '../worktree/leftover.js';\n\n/**\n * One session as every client sees it — the dashboard's /api/sessions rows\n * and `work sessions --json` alike: identity, status, activity, comments,\n * context, archive state. Built in one place so the two can't drift.\n */\nexport interface SessionWireOptions {\n /** The session's `+N −M`, when the caller has one (the web cache). */\n diffStatFor?: (id: string, s: WorktreeSession, hasStatus: boolean) => DiffStat | null;\n /** Whether its Claude runs in the PTY host (the CLI asks the host; the\n * web server's pool knows it already). */\n ptyLive?: (id: string) => boolean;\n /** Its running Claudes, wherever they were started (live-claudes.ts). */\n claudesFor?: (id: string) => SessionClaudes | null;\n /** It shares its folder with another session that owns it\n * (shared-folders.ts): the folder's activity isn't this one's. */\n shadowed?: (id: string) => boolean;\n /** Unresolved review threads on its open PRs (the PR watch's last check). */\n reviewThreadsFor?: (id: string) => number;\n /** Reply drafts its Claude wrote for you to post (pr-replies.ts). */\n replyDraftsFor?: (id: string) => number;\n /** Where its PR stands (pr-stage.ts over the PR watch's last check), and whether you've seen it there. */\n prStageFor?: (id: string) => PrStageWire | null;\n /** You have notes on it (session-notes.ts). */\n hasNote?: (id: string) => boolean;\n /** What it waits on that isn't done yet (session-blocks.ts). */\n blockedByFor?: (id: string) => BlockerWire[];\n /** The running Claudes were read against a real process list, so \"none\" means none. */\n liveKnown?: boolean;\n /** A Claude of ours runs for it (PTY host), whether or not Claude Code's file shows it yet. */\n hostedLive?: (id: string) => boolean;\n /** A status read from its terminal output, for a tool with no hooks (output-status.ts). */\n outputStatusFor?: (id: string) => SessionAttention | null;\n /** Its snooze, if any (snooze-store.ts); shown only while it holds. */\n snoozeFor?: (id: string) => Snooze | null;\n /** How far behind main — or the session it is stacked on — it is (behind-main.ts's cache). */\n behindFor?: (id: string, s: WorktreeSession) => { base: string; commits: number; conflicts: boolean; stacked?: true } | null;\n /** Where it sits in a stack (stack-sessions.ts). */\n stackFor?: (id: string) => {\n parent: { id: string; branch: string; title?: string } | null;\n children: number;\n merged?: { id: string; branch: string } | null;\n };\n}\n\nexport function sessionWire(s: WorktreeSession, opts: SessionWireOptions = {}): SessionWire {\n const id = sessionIdFor(s);\n const meta = readSessionMeta(id, s);\n const shadowed = opts.shadowed?.(id) ?? false;\n const claudes = shadowed ? null : (opts.claudesFor?.(id) ?? null);\n const reviewThreads = s.archivedAt ? 0 : (opts.reviewThreadsFor?.(id) ?? 0);\n const replyDrafts = s.archivedAt ? 0 : (opts.replyDraftsFor?.(id) ?? 0);\n const prStage = s.archivedAt ? null : (opts.prStageFor?.(id) ?? null);\n const wire: SessionWire = {\n id,\n target: s.target,\n branch: s.branch,\n isGroup: s.isGroup,\n paths: s.paths,\n baseBranch: s.baseBranch,\n jiraKey: s.jiraKey,\n createdAt: s.createdAt,\n lastAccessedAt: s.lastAccessedAt,\n draftCount: meta.draftCount,\n commentCount: meta.commentCount,\n claudeCount: meta.claudeCount,\n ptyStatus: opts.ptyLive ? (opts.ptyLive(id) ? 'running' : 'idle') : meta.ptyStatus,\n lastActivity: shadowed ? null : meta.lastActivity,\n // A running Claude is open even when it writes nothing (idle at its prompt).\n activityState: shadowed\n ? 'stale'\n : claudes\n ? claudes.busy\n ? 'active'\n : meta.activityState === 'active'\n ? 'active'\n : 'open'\n : meta.activityState,\n ...(claudes ? { agents: claudes, claudes } : {}),\n agent: agentWire(agentOf(s)),\n ...(s.archivedAt ? archiveInfo(id) : {}),\n title: bestEffort(\n `title of ${s.target}:${s.branch}`,\n () => sessionTitle(s, s.archivedAt ? readArchive(id)?.summary.prompts[0]?.text : null),\n null,\n ),\n ...(s.title ? { titleIsYours: true } : {}),\n pendingForClaudeCount: meta.pendingForClaudeCount,\n // Claude Code's own state file over what the hooks recorded, when newer.\n attention:\n meta.attention && !shadowed && opts.claudesFor\n ? withLiveClaude(meta.attention, claudes, { known: opts.liveKnown === true, hosted: opts.hostedLive?.(id) ?? true })\n : (meta.attention ?? (shadowed || s.archivedAt ? null : (opts.outputStatusFor?.(id) ?? null))),\n diffStat: opts.diffStatFor ? opts.diffStatFor(id, s, meta.attention !== null) : null,\n archivedAt: s.archivedAt ?? null,\n port: s.port ?? null,\n context: s.archivedAt ? null : bestEffort(`context usage for ${s.target}:${s.branch}`, () => readContextUsage(s), null),\n ...(reviewThreads > 0 ? { openReviewThreads: reviewThreads } : {}),\n ...(replyDrafts > 0 ? { replyDrafts } : {}),\n ...(prStage ? { prStage } : {}),\n ...otherBranches(s),\n };\n // Snoozed: only while it holds (a time not yet reached, or the status it\n // was snoozed in). \"Its status\" is what the hooks recorded — the same the\n // snooze was taken against — not the shown one, which a live Claude's state\n // file can override (that would end a snooze the moment it was set).\n const snooze = s.archivedAt ? null : (opts.snoozeFor?.(id) ?? null);\n if (snooze && snoozeActive(snooze, { attention: readStatus(id), openReviewThreads: wire.openReviewThreads, prStage: wire.prStage }))\n wire.snoozed = { until: snooze.until };\n const behind = s.archivedAt ? null : (opts.behindFor?.(id, s) ?? null);\n if (behind && behind.commits > 0) wire.behind = behind;\n const stack = s.archivedAt ? null : (opts.stackFor?.(id) ?? null);\n if (stack?.parent) wire.stackedOn = stack.parent;\n if (stack?.children) wire.stackedChildren = stack.children;\n if (stack?.merged) wire.stackParentMerged = stack.merged;\n if (opts.hasNote?.(id)) wire.hasNote = true;\n const blockers = s.archivedAt ? [] : (opts.blockedByFor?.(id) ?? []);\n if (blockers.length) wire.blockedBy = blockers;\n return wire;\n}\n\n/**\n * Repos of the session checked out on another branch than the session's\n * (read from HEAD files, no git). Ship and the PR watch follow the real\n * branch already; this is so the dashboard says so.\n */\nexport function otherBranches(s: Pick<WorktreeSession, 'branch' | 'paths' | 'target' | 'isGroup' | 'archivedAt'>): {\n onOtherBranch?: Array<{ repo: string; branch: string | null; noGit?: true }>;\n} {\n if (s.archivedAt || !s.branch) return {};\n const out: Array<{ repo: string; branch: string | null; noGit?: true }> = [];\n for (const p of s.paths) {\n if (!fs.existsSync(p)) continue;\n // A folder with no git left in it (a removal that stopped halfway) is on no branch at all.\n if (isLeftover(p)) {\n out.push({ repo: s.isGroup ? path.basename(p) : s.target, branch: null, noGit: true });\n continue;\n }\n const branch = checkedOutBranch(p);\n if (branch !== s.branch) out.push({ repo: s.isGroup ? path.basename(p) : s.target, branch });\n }\n return out.length ? { onOtherBranch: out } : {};\n}\n\n/** A session's unresolved review threads, from the PR watch's per-repo counts (open PRs only). */\nexport function reviewThreadsOf(ci: { repos: Array<{ pr: { state: string } | null; openThreads?: number }> } | null | undefined): number {\n return (ci?.repos ?? []).reduce((n, r) => n + (r.pr?.state === 'OPEN' ? (r.openThreads ?? 0) : 0), 0);\n}\n\n/** The `pr_watch_seen` key that says you saw a session at a PR stage. */\nexport const stageSeenKey = (stageKey: string) => `stage:${stageKey}`;\n\n/**\n * A session's PR stage from the PR watch's last check, with `seen` read only\n * for a stage that would bring it back to the Inbox (one lookup, not one per row).\n */\nexport function prStageWire(\n ci: { repos: Array<{ name: string; pr: StagePr | null }> } | null | undefined,\n seen: (key: string) => boolean,\n): PrStageWire | null {\n const stage = prStageOf(ci?.repos ?? []);\n if (!stage) return null;\n return STAGE_WANTS_YOU.has(stage.kind) && seen(stageSeenKey(stage.key)) ? { ...stage, seen: true } : stage;\n}\n\n/** Saved uncommitted files a Restore hasn't put back yet. */\nfunction savedFiles(saved: Record<string, { files: number; restoredAt?: string; restoreError?: string }> | undefined): {\n savedUncommitted?: number;\n} {\n const n = Object.values(saved ?? {})\n .filter((u) => !u.restoredAt && !u.restoreError)\n .reduce((sum, u) => sum + u.files, 0);\n return n ? { savedUncommitted: n } : {};\n}\n\nfunction archiveInfo(id: string): { archive?: SessionArchiveInfo } {\n const rec = readArchive(id);\n if (!rec) return {};\n return {\n archive: {\n worktreeRemoved: rec.worktreeRemoved,\n keptBecause: rec.keptBecause,\n promptCount: rec.summary.promptCount,\n prompts: rec.summary.prompts.map((p) => p.text),\n lastSummary: rec.summary.lastSummary,\n ...(rec.summary.written ? { written: rec.summary.written } : {}),\n ...(rec.buildFolders ? { buildFolders: rec.buildFolders } : {}),\n ...savedFiles(rec.uncommitted),\n ...(keptList(rec.kept) ? { kept: keptList(rec.kept) } : {}),\n },\n };\n}\n\n/** Newest sign of life (ms): the hook update, Claude's last write, the\n * `work tree` entry — the same rule as the dashboard's \"Last active\". */\nexport function lastActiveMs(w: Pick<SessionWire, 'lastAccessedAt' | 'lastActivity' | 'attention'>): number {\n return Math.max(Date.parse(w.lastAccessedAt) || 0, w.lastActivity ?? 0, w.attention ? Date.parse(w.attention.updatedAt) || 0 : 0);\n}\n\n/**\n * Archived sessions' rows, kept between builds of the list: an archived\n * session doesn't change — its Claude is stopped, its worktree mostly gone —\n * and building its row reads its archive (2/3 of /api/sessions' time with\n * fifty of them). A row is built again when its archive file was written\n * (the summary lands after archiving, a Restore records what came back), it\n * was renamed or entered, or your note on it came or went.\n */\nexport function createArchivedRows(\n archiveFile: (id: string) => string = (id) => path.join(archiveDirFor(id), 'archive.json'),\n): (s: WorktreeSession, extra: { hasNote: boolean }, build: () => SessionWire) => SessionWire {\n const rows = new Map<string, { key: string; row: SessionWire }>();\n return (s, extra, build) => {\n if (!s.archivedAt) return build();\n const id = sessionIdFor(s);\n let mtime = 0;\n try {\n mtime = fs.statSync(archiveFile(id)).mtimeMs;\n } catch {\n /* none yet */\n }\n const key = `${s.archivedAt}|${mtime}|${s.title ?? ''}|${s.lastAccessedAt}|${extra.hasNote}`;\n const hit = rows.get(id);\n if (hit?.key === key) return hit.row;\n const row = build();\n rows.set(id, { key, row });\n return row;\n };\n}\n","import { peekPty } from '../pty/pty-pool.js';\nimport { sessionStatusView } from '../status/turn-activity.js';\nimport type { ActivityState } from '../api-types.js';\nimport { readSessionActivity } from './session-activity.js';\nimport { getCommentFileStore } from '../comments/comment-file-store.js';\nimport { readPendingForSession } from '../comments/pending-delivery.js';\nimport type { WorktreeSession } from './history.js';\nimport { readStatus, type EffectiveStatus } from '../status/session-status.js';\n\nexport type { PtyStatus } from '../api-types.js';\nimport type { PtyStatus } from '../api-types.js';\n\nexport interface SessionMeta {\n draftCount: number;\n /** Open comment threads (top-level, not resolved): the Diff tab's badge. */\n commentCount: number;\n /** Comments authored by claude — used by the client to compute unread. */\n claudeCount: number;\n /** Set when *our* PTY pool has a live Claude for this session. Doesn't\n * catch external terminals — `activityState` does. */\n ptyStatus: PtyStatus;\n /** ms since epoch of Claude's last write across this worktree, or null. */\n lastActivity: number | null;\n /** Derived from `lastActivity`: 'active' (≤30 s), 'open' (≤5 min), 'stale'. */\n activityState: ActivityState;\n /** Published user comments not yet surfaced to Claude via the\n * UserPromptSubmit hook. Drops to zero after Claude takes its next turn. */\n pendingForClaudeCount: number;\n /** Hook-driven agent status for the attention inbox; null until the\n * session's Claude has fired a hook under a full `work web`. */\n attention: EffectiveStatus | null;\n}\n\n/**\n * Cheap per-session metadata. Goes through the file-store cache so badge\n * counts reflect in-flight writes that haven't yet hit disk — reading the\n * raw JSON behind the cache's back produced stale counts under load.\n *\n * `session` is required because we need the worktree paths to look up\n * Claude's transcript directory (the sessionId hash alone isn't enough).\n */\nexport function readSessionMeta(sessionId: string, session: WorktreeSession): SessionMeta {\n const comments = getCommentFileStore(sessionId).snapshot();\n let drafts = 0;\n let claude = 0;\n let open = 0;\n for (const c of comments) {\n if (c.status === 'draft') drafts++;\n if (c.author === 'claude') claude++;\n // The Diff tab's badge: threads still open. One Claude worked through is resolved (resolveAddressed).\n if (!c.parentId && !c.resolved) open++;\n }\n const activity = readSessionActivity(session);\n const pending = readPendingForSession(sessionId).length;\n const status = readStatus(sessionId);\n return {\n draftCount: drafts,\n commentCount: open,\n claudeCount: claude,\n ptyStatus: peekPty(sessionId) ? 'running' : 'idle',\n lastActivity: activity.lastActivity,\n activityState: activity.state,\n pendingForClaudeCount: pending,\n attention: status ? sessionStatusView(status, session, activity.lastActivity ?? 0) : null,\n };\n}\n","import { readJsonlTail } from './jsonl.js';\nimport { agentOf } from '../agents/index.js';\nimport type { ConversationEntry } from '../agents/types.js';\nimport type { ContextUsage } from '../api-types.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\n\nexport type { ContextUsage } from '../api-types.js';\n\n/**\n * How full a session's conversation is. Every assistant message in the\n * transcript carries the token usage of the request that produced it, so\n * the newest one says how big the context is now: its prompt (input +\n * cache reads + cache writes) plus its reply, which the next turn carries.\n * Near the window Claude Code compacts the conversation, and answers get\n * worse before that — the dashboard shows when to start fresh.\n */\n\n/** From conversation entries (oldest first): the newest main-thread usage, in the agent's window (`window`). */\nexport function contextUsageFrom(\n entries: readonly ConversationEntry[],\n window: (model: string | undefined, used: number) => number,\n): ContextUsage | null {\n for (let i = entries.length - 1; i >= 0; i--) {\n const e = entries[i];\n // Subagent (Task) turns run in their own context.\n if (e.role !== 'agent' || e.sidechain || !e.usage) continue;\n const used = e.usage.prompt + e.usage.reply;\n if (used === 0) continue;\n return { used, window: window(e.model, used), ...(e.model ? { model: e.model } : {}) };\n }\n return null;\n}\n\n// Claude Code's transcript files, for the callers that still read Claude's own records (turn activity): agents/claude-files.ts.\nexport type { ConversationFile as TranscriptFile } from '../agents/types.js';\n\n/** Only the tail is read — a usage line is always near the end. */\nconst USAGE_TAIL_BYTES = 64 * 1024;\nconst cache = new Map<string, { key: string; usage: ContextUsage | null }>();\n\n/** The session's context usage now, through its agent; re-reads a conversation only after it changed. Null when work can't read its agent's conversations. */\nexport function readContextUsage(session: WorktreeSession): ContextUsage | null {\n const conv = agentOf(session).conversation;\n if (!conv) return null;\n let t: { file: string; size: number; mtimeMs: number } | null = null;\n for (const f of conv.files(session)) if (!t || f.mtimeMs > t.mtimeMs) t = f;\n if (!t) return null;\n const key = `${t.file}:${t.size}:${t.mtimeMs}`;\n const id = session.paths.join('|');\n const hit = cache.get(id);\n if (hit?.key === key) return hit.usage;\n const usage = contextUsageFrom(conv.entries(readJsonlTail(t.file, USAGE_TAIL_BYTES)), conv.contextWindow);\n cache.set(id, { key, usage });\n return usage;\n}\n","import fs from 'node:fs';\nimport { promptsSince } from './digest.js';\nimport { agentOf } from '../agents/index.js';\nimport type { ConversationEntry } from '../agents/types.js';\nimport type { WorktreeSession } from '../sessions/session-types.js';\n\n/**\n * A human name for a session, beside its branch: the name you gave it, or\n * else what you first asked its Claude (\"Rotate the terminal encryption\n * keys\"), or else its Jira key. Worked out when read — the first prompt is\n * read from the start of its oldest transcript, cached per file — so a GET\n * writes nothing; only a rename is stored.\n */\n\nconst TITLE_CHARS = 80;\nconst HEAD_BYTES = 256 * 1024;\nconst cache = new Map<string, { size: number; title: string | null }>();\n\n/** The first prompt in a conversation file (read from its start), its lines read by `toEntries` (the agent's). */\nexport function firstPromptOf(file: string, toEntries: (lines: readonly unknown[]) => ConversationEntry[]): string | null {\n let size: number;\n try {\n size = fs.statSync(file).size;\n } catch {\n return null;\n }\n const hit = cache.get(file);\n // The start of a file doesn't change as it grows, unless it was replaced\n // (smaller). \"No prompt in it\" holds as long as the file is the same, or\n // its whole head was read already: re-reading 256 KB of every such\n // transcript on every session-list build cost the most of all.\n if (hit && size >= hit.size && (hit.title !== null || size === hit.size || hit.size >= HEAD_BYTES)) return hit.title;\n let text: string;\n try {\n const fd = fs.openSync(file, 'r');\n try {\n const buf = Buffer.alloc(Math.min(size, HEAD_BYTES));\n fs.readSync(fd, buf, 0, buf.length, 0);\n text = buf.toString('utf8');\n } finally {\n fs.closeSync(fd);\n }\n } catch {\n return null;\n }\n const lines: unknown[] = [];\n for (const line of text.split('\\n')) {\n try {\n lines.push(JSON.parse(line));\n } catch {\n /* the last, cut-off line */\n }\n }\n const first = promptsSince([toEntries(lines)], 0)[0]?.text ?? null;\n const readable = first ? titleText(first) : null;\n const title = readable ? clip(readable) : null;\n cache.set(file, { size, title });\n return title;\n}\n\nconst clip = (s: string) => (s.length > TITLE_CHARS ? s.slice(0, TITLE_CHARS - 1).trimEnd() + '…' : s);\n\n/**\n * A prompt as a name: what you wrote, without markup. A pasted block\n * (`<pasted_content …>…</pasted_content>`, a log or code you pasted) is left\n * out when you also wrote something; a prompt that is only a paste keeps its\n * text. Other tags are dropped, their text kept. Null when nothing is left.\n */\nexport function titleText(prompt: string): string | null {\n const flat = (s: string) =>\n s\n .replace(/<\\/?[A-Za-z][\\w-]*(?:\\s[^>]*)?>/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n const outside = flat(prompt.replace(/<pasted_content\\b[^>]*>[\\s\\S]*?<\\/pasted_content>/g, ' '));\n const text = outside || flat(prompt);\n return text ? text : null;\n}\n\n/** The session's name: yours, else its first prompt, else its Jira key. */\nexport function sessionTitle(s: WorktreeSession, fallbackPrompt?: string | null): string | null {\n if (s.title?.trim()) return s.title.trim();\n const conv = agentOf(s).conversation;\n const oldestFirst = (conv?.files(s) ?? []).sort((a, b) => a.mtimeMs - b.mtimeMs);\n for (const t of oldestFirst) {\n const p = firstPromptOf(t.file, conv!.entries);\n if (p) return p;\n }\n const fallback = fallbackPrompt ? titleText(fallbackPrompt) : null;\n if (fallback) return clip(fallback);\n return s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AAO,UAAU;AAC1B,QAAI,CAAC,EAAE,WAAY,QAAO,MAAM;AAChC,UAAM,KAAK,aAAa,CAAC;AACzB,QAAI,QAAQ;AACZ,QAAI;AACF,cAAQA,IAAG,SAAS,YAAY,EAAE,CAAC,EAAE;AAAA,IACvC,QAAQ;AAAA,IAER;AACA,UAAM,MAAM,GAAG,EAAE,UAAU,IAAI,KAAK,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,cAAc,IAAI,MAAM,OAAO;AAC1F,UAAM,MAAM,KAAK,IAAI,EAAE;AACvB,QAAI,KAAK,QAAQ,IAAK,QAAO,IAAI;AACjC,UAAM,MAAM,MAAM;AAClB,SAAK,IAAI,IAAI,EAAE,KAAK,IAAI,CAAC;AACzB,WAAO;AAAA,EACT;AACF;","names":["fs","cache","fs"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/git/git-head.ts","../src/core/comments/pending-delivery.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\n/**\n * The branch checked out in a checkout, read from its HEAD file — no `git`\n * process, so the session list can ask for every session on every request.\n * A worktree's `.git` is a file (`gitdir: <repo>/.git/worktrees/<name>`)\n * whose HEAD names the branch; a base checkout's `.git` is the folder.\n *\n * null: detached HEAD, not a checkout, or unreadable.\n */\nexport function checkedOutBranch(checkout: string): string | null {\n try {\n const dotGit = path.join(checkout, '.git');\n let gitDir = dotGit;\n if (fs.statSync(dotGit).isFile()) {\n const m = /^gitdir:\\s*(.+?)\\s*$/m.exec(fs.readFileSync(dotGit, 'utf8'));\n if (!m) return null;\n gitDir = path.resolve(checkout, m[1]);\n }\n return branchFromHead(fs.readFileSync(path.join(gitDir, 'HEAD'), 'utf8'));\n } catch {\n return null;\n }\n}\n\n/** `ref: refs/heads/fix/x` → `fix/x`; a commit sha (detached) → null. */\nexport function branchFromHead(head: string): string | null {\n const m = /^ref:\\s*refs\\/heads\\/(.+?)\\s*$/m.exec(head);\n return m ? m[1] : null;\n}\n","/**\n * Bridge between `work web` review comments and any live Claude session\n * running in the same worktree. Storage (state.db, see db.ts):\n *\n * comments the comment stores (comment-file-store.ts)\n * comment_deliveries (session, comment id) pairs surfaced to Claude\n *\n * \"Pending\" = published, user-authored, not in the delivered list. Replies\n * authored by Claude (author === 'claude') are excluded — Claude wrote\n * them; we don't need to echo them back.\n *\n * Delivery is lazy: when a Claude in the matching worktree submits a\n * prompt, the hook reads pending comments via this module, prints them as\n * a system-reminder block to stdout (which Claude Code injects into the\n * conversation), and marks them delivered.\n */\n\nimport { checkedOutBranch } from '../git/git-head.js';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { loadHistory, type WorktreeSession } from '../sessions/history.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport { getCommentFileStore, readStoreComments } from './comment-file-store.js';\nimport { scopeHashFor } from '../diff/repo-spec.js';\nimport { tx, withDb, type Db } from '../platform/db.js';\nimport type { Comment } from './comment-types.js';\n\nfunction deliveredIds(d: Db, sessionId: string): Set<string> {\n return new Set(\n (d.prepare('SELECT comment_id FROM comment_deliveries WHERE session_id = ?').all(sessionId) as Array<{ comment_id: string }>).map(\n (r) => r.comment_id,\n ),\n );\n}\n\n/** Norm-path comparison that mirrors what we do server-side. */\nfunction normalize(p: string): string {\n return path.resolve(p).replace(/\\\\/g, '/').toLowerCase();\n}\n\n/** Map a Claude cwd back to a session. Tries direct-match against any\n * session's path first, then ancestor match (so cwd inside a subdir of a\n * worktree still resolves to the worktree's session). */\n/**\n * Two sessions on one folder (an old entry and a newer one, a typo'd target\n * re-added): which of them a Claude there is. Not an archived one when the\n * other isn't; then the one whose branch is checked out there; then the one\n * entered last. The oldest used to win, so status and comments went to an\n * entry nobody looks at.\n */\nfunction owns(candidate: WorktreeSession, current: WorktreeSession, root: string): boolean {\n if (!!candidate.archivedAt !== !!current.archivedAt) return !candidate.archivedAt;\n const onBranch = checkedOutBranch(root);\n const a = candidate.branch === onBranch;\n const b = current.branch === onBranch;\n if (a !== b) return a;\n return (Date.parse(candidate.lastAccessedAt) || 0) > (Date.parse(current.lastAccessedAt) || 0);\n}\n\nexport function findSessionForCwd(cwd: string, sessions: WorktreeSession[] = loadHistory()): WorktreeSession | null {\n const here = normalize(cwd);\n // Deepest root containing cwd wins, so nested worktrees disambiguate. A\n // group's roots include the group root (the sub-repos' parent) — that's\n // where `work tree` launches Claude for a group, so hooks fire from there.\n let best: { session: WorktreeSession; root: string; len: number } | null = null;\n for (const s of sessions) {\n const roots = s.isGroup && s.paths[0] ? [...s.paths, path.dirname(s.paths[0])] : s.paths;\n for (const root of roots) {\n const r = normalize(root);\n if (!(here === r || here.startsWith(r + '/'))) continue;\n if (!best || r.length > best.len || (r.length === best.len && owns(s, best.session, root))) {\n best = { session: s, root, len: r.length };\n }\n }\n }\n if (!best) return null;\n // A separate checkout nested INSIDE the session's tree (a git worktree at\n // <repo>/.claude/worktrees/x, a vendored repo) is not this session: its\n // Claude must not report status, take checkpoints or receive comments as\n // if it were the parent. Any `.git` between cwd and the matched root —\n // other than the session's own repos — marks a different checkout.\n // (Plain fs checks: this runs on every hook.)\n const own = new Set(best.session.paths.map(normalize));\n const top = normalize(best.root);\n for (let dir = path.resolve(cwd); normalize(dir) !== top && normalize(dir).startsWith(top + '/'); dir = path.dirname(dir)) {\n if (!own.has(normalize(dir)) && fs.existsSync(path.join(dir, '.git'))) return null;\n if (path.dirname(dir) === dir) break;\n }\n return best.session;\n}\n\nfunction isPendingFor(delivered: Set<string>) {\n return (c: Comment) => c.status === 'published' && c.author === 'user' && !delivered.has(c.id);\n}\n\n/** Returns published user comments that haven't been delivered yet.\n * Reads through the file-store cache so we see in-flight writes\n * (`session-meta.ts` and other readers couldn't, when they re-read the\n * disk directly). */\n/**\n * The line typed into an idle Claude (or given as the first prompt of one\n * work starts) so its UserPromptSubmit hook attaches the pending comments.\n * Short on purpose: a long typed note got mangled by Claude Code's paste\n * handling. It says where the content is, so it reads right in the\n * transcript.\n */\nexport const NOTE_NUDGE =\n 'work has new notes for you (review feedback, CI results or comments); they are attached to this message. Work through them now.';\n\nexport function readPendingForSession(sessionId: string): Comment[] {\n const delivered = withDb((d) => deliveredIds(d, sessionId));\n return readStoreComments(sessionId).filter(isPendingFor(delivered));\n}\n\n/** Comment-store ids for every `wd` scope that could cover this worktree.\n * A scope is keyed by `sha1` of its sorted repo roots (see\n * `repo-spec.scopeHashFor`), so from a session's paths we can rebuild the\n * exact ids without consulting `work web`'s in-memory scope registry:\n * - the whole-set hash → a group `wd` opened at the group root, or the\n * single-repo `wd` (one path);\n * - each individual path's hash → a `wd` opened inside one sub-repo of a\n * group worktree.\n * `registerScope` hashes `path.resolve()`d roots, so we resolve here too or\n * the hashes won't line up. Mirrors `scope-manager.commentStoreIdForScope`\n * (`scope-<hash>`). */\nfunction scopeStoreIdsForPaths(paths: string[]): string[] {\n const resolved = paths.map((p) => path.resolve(p));\n const ids = new Set<string>();\n ids.add(`scope-${scopeHashFor(resolved)}`);\n for (const p of resolved) ids.add(`scope-${scopeHashFor([p])}`);\n return [...ids];\n}\n\n/**\n * Pending comments for a whole worktree: the session's own comment store\n * PLUS any `wd` / `wd -c` scope review store covering the same paths.\n *\n * `wd` registers its review under a scope-hash comment store, not the\n * session store the hook reads — without this merge, comments left in the\n * `wd` review UI would never reach the Claude running in that worktree.\n * Delivered-tracking stays per-session (one `<sessionId>.delivered.json`),\n * so a comment surfaced here won't be re-delivered regardless of which\n * store it came from.\n */\nexport function readPendingForWorktree(session: WorktreeSession): Comment[] {\n const sessionId = sessionIdFor(session);\n const delivered = withDb((d) => deliveredIds(d, sessionId));\n const pending = isPendingFor(delivered);\n const seen = new Set<string>();\n const out: Comment[] = [];\n const collect = (storeId: string) => {\n for (const c of readStoreComments(storeId)) {\n if (seen.has(c.id) || !pending(c)) continue;\n seen.add(c.id);\n out.push(c);\n }\n };\n collect(sessionId);\n for (const storeId of scopeStoreIdsForPaths(session.paths)) collect(storeId);\n return out;\n}\n\n/**\n * What was handed to Claude is done once its turn really ends: your review\n * comments and work's notes to it (PR feedback, CI, a prompt you sent) —\n * every top-level comment of yours it was given, in the session's store and\n * any `wd` scope store over its paths — are marked resolved. Left open, they\n * piled up on the Diff tab's badge (three PR-watch notes read as \"3\"), to\n * resolve or delete by hand. Resolved threads stay listed (dimmed) and can\n * be reopened. Claude's own replies are left as they are. Returns the ids\n * resolved.\n */\nexport function resolveAddressed(session: WorktreeSession): string[] {\n const sessionId = sessionIdFor(session);\n const delivered = withDb((d) => deliveredIds(d, sessionId));\n if (delivered.size === 0) return [];\n const done: string[] = [];\n for (const storeId of [sessionId, ...scopeStoreIdsForPaths(session.paths)]) {\n const open = readStoreComments(storeId).filter(\n (c) => delivered.has(c.id) && c.author === 'user' && c.status === 'published' && !c.parentId && !c.resolved,\n );\n if (open.length === 0) continue;\n const store = getCommentFileStore(storeId);\n for (const c of open) if (store.setResolved(c.id, true)) done.push(c.id);\n }\n return done;\n}\n\n/** Persist a delivery batch, so these ids are never surfaced again. */\nexport function markDelivered(sessionId: string, ids: string[]): void {\n if (ids.length === 0) return;\n tx((d) => {\n const ins = d.prepare('INSERT OR IGNORE INTO comment_deliveries (session_id, comment_id) VALUES (?, ?)');\n for (const id of ids) ins.run(sessionId, id);\n });\n}\n\n/**\n * Claim comments for delivery: of `ids`, return the ones nobody has\n * delivered yet, and mark them delivered — atomically. Two deliverers\n * racing (a Stop hook and the PTY push for the same comment) then can't\n * both send it: only the one that claimed it does. A deliverer whose send\n * fails gives the ids back with `releaseClaim`.\n */\nexport function claimForDelivery(sessionId: string, ids: string[]): string[] {\n if (ids.length === 0) return [];\n // INSERT OR IGNORE in one write transaction: a row inserted here is our\n // claim; one that already existed was someone else's.\n return tx((d) => {\n const ins = d.prepare('INSERT OR IGNORE INTO comment_deliveries (session_id, comment_id) VALUES (?, ?)');\n return ids.filter((id) => ins.run(sessionId, id).changes > 0);\n });\n}\n\n/** Undo a claim whose delivery failed, so the next hook picks them up. */\nexport function releaseClaim(sessionId: string, ids: string[]): void {\n if (ids.length === 0) return;\n tx((d) => {\n const del = d.prepare('DELETE FROM comment_deliveries WHERE session_id = ? AND comment_id = ?');\n for (const id of ids) del.run(sessionId, id);\n });\n}\n\n/** Cap the size of one comment body we surface to Claude. A pathologically\n * long comment shouldn't blow out Claude's context — we truncate, then\n * hint at the rest via \"(truncated)\". 4 KB is generous for a code-review\n * note while leaving headroom for batches. */\nconst MAX_BODY_BYTES = 4 * 1024;\n/** A general note: a prompt, or work's own note (a PR review round quotes\n * every thread, then a bot's overview). 4 KB once cut such a note before\n * the line telling Claude how to draft its replies. */\nconst MAX_NOTE_BYTES = 16 * 1024;\n/** Overall cap on the whole system-reminder payload. Multiple long\n * comments at once still get bounded — but room for four whole notes, since\n * the cut falls on the newest one's end: its instructions. */\nconst MAX_TOTAL_BYTES = 4 * MAX_NOTE_BYTES;\n\n/**\n * Format pending comments as a system-reminder block suitable for stdout.\n * Returns empty string when there's nothing pending — the caller (the\n * `work hook` CLI) just exits silently in that case.\n *\n * Truncates pathologically long bodies and caps the overall payload so\n * one runaway comment can't displace the rest of Claude's context.\n */\nexport function formatPendingForPrompt(pending: Comment[]): string {\n if (pending.length === 0) return '';\n\n const sorted = [...pending].sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n\n const general = sorted.filter((c) => c.side === 'general' && !c.parentId);\n const inline = sorted.filter((c) => c.side !== 'general' && !c.parentId);\n const replies = sorted.filter((c) => c.parentId);\n\n const lines: string[] = [];\n lines.push('<system-reminder>');\n lines.push(`New review comments from \\`work web\\` (${pending.length} item${pending.length === 1 ? '' : 's'}):`);\n lines.push('');\n\n if (general.length > 0) {\n lines.push('## General notes');\n for (const c of general) {\n // General notes (this is where `work broadcast` lands) may be multi-line\n // prompts — deliver the whole body, not just line 1. Only the byte cap\n // applies. Inline/reply comments still use the one-line `formatBody`.\n lines.push(formatFullBody('-', c));\n }\n lines.push('');\n }\n\n if (inline.length > 0) {\n lines.push('## Inline comments');\n for (const c of inline) {\n const where = `${c.repo}/${c.file}:${c.line} (${c.side})`;\n lines.push(formatBody(`- ${where}`, c));\n }\n lines.push('');\n }\n\n if (replies.length > 0) {\n lines.push('## Replies');\n for (const c of replies) {\n lines.push(formatBody(`- (reply to ${c.parentId})`, c));\n }\n lines.push('');\n }\n\n lines.push(\n 'Address them as part of your next response. You can reply via the same review UI by posting back to the latest review URL at `~/.work/web.url` + `/api/sessions/<id>/comments` with `author: \"claude\"`.',\n );\n lines.push('</system-reminder>');\n const out = lines.join('\\n');\n if (out.length <= MAX_TOTAL_BYTES) return out;\n const trimmed = out.slice(0, MAX_TOTAL_BYTES - 200);\n return (\n trimmed +\n '\\n\\n(…review payload truncated for context-window safety; ' +\n `${pending.length} comment(s) total — open work web for the full list.)\\n` +\n '</system-reminder>'\n );\n}\n\nfunction formatBody(prefix: string, c: Comment): string {\n const lead = c.body.split('\\n')[0].trim();\n const capped = lead.length > MAX_BODY_BYTES ? `${lead.slice(0, MAX_BODY_BYTES)}…` : lead;\n return `${prefix}: ${capped}${c.body.includes('\\n') ? ' …' : ''}`;\n}\n\n/** Like `formatBody` but preserves the full multi-line body (only the note\n * cap applies). Multi-line bodies are emitted under the bullet, indented, so\n * a broadcast prompt arrives intact rather than truncated to its first line. */\nfunction formatFullBody(prefix: string, c: Comment): string {\n const body = c.body.trim();\n const capped = body.length > MAX_NOTE_BYTES ? `${body.slice(0, MAX_NOTE_BYTES)}…` : body;\n const bodyLines = capped.split('\\n');\n if (bodyLines.length === 1) return `${prefix}: ${bodyLines[0]}`;\n const [first, ...rest] = bodyLines;\n return [`${prefix}: ${first}`, ...rest.map((l) => ` ${l}`)].join('\\n');\n}\n\n/** Re-export so consumers don't have to know which module owns it. */\nexport { sessionIdFor };\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAUV,SAAS,iBAAiB,UAAiC;AAChE,MAAI;AACF,UAAM,SAAS,KAAK,KAAK,UAAU,MAAM;AACzC,QAAI,SAAS;AACb,QAAI,GAAG,SAAS,MAAM,EAAE,OA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KAAK,IAAI,GAAG,KAAK,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC,EAAE,KAAK,IAAI;AACxE;","names":["fs","path","path","fs"]}
@@ -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 disposeAllWat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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,9 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/version.ts
4
- var VERSION = true ? "2.0.11" : "dev";
5
-
6
- export {
7
- VERSION
8
- };
9
- //# sourceMappingURL=chunk-W5B4NLBI.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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AI,qCAAqC;AACjD,UAAQ,IAAI,uCAAuC;AACnD,UAAQ,IAAI,EAAE;AAChB;AAEA,eAAsB,IAAI,MAA+B;AAEvD,MAAI,KAAK,WAAW,GAAG;AACrB,aAAS;AACT;AAAA,EACF;AAEA,MAAI,MAAM,MAAM,IAAI,EAAE,WAAW,MAAM,EAAE,MAAM,wBAAwB;AACvE,aAAW,KAAK,MAAM,YAAY,IAAI,EAAG,OAAM,IAAI,QAAQ,CAAC;AAC5D,QAAM,IAEH,WAAW,iBAAiB,OAAO,iBAAiB,EACpD,cAAc,GAAG,2DAA2D,EAC5E,OAAO,EACP,KAAK,CAAC,KAAK,KAAKA,WAAU;AACzB,QAAI,KAAK,SAAS,mBAAmB;AACnC,cAAQ,IAAI,cAAc;AAC1B,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,QAAI,KAAK;AACP,MAAAA,OAAM,SAAS;AACf,cAAQ,MAAM,OAAO,GAAG;AAAA,IAC1B;AACA,QAAI,IAAK,SAAQ,MAAM,GAAG;AAC1B,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC,EACA,KAAK,EACL,MAAM,KAAK,MAAM,EACjB,QAAQ,OAAO,EACf,MAAM,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/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,OAA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