@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,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import {
3
- listReplies
4
- } from "./chunk-26IZBYVL.js";
5
2
  import {
6
3
  examineWorktree,
7
4
  normPath
8
5
  } from "./chunk-AKMPF72Y.js";
6
+ import {
7
+ listReplies
8
+ } from "./chunk-26IZBYVL.js";
9
9
  import {
10
10
  saveIgnored,
11
11
  teardownWorktree,
@@ -16,7 +16,7 @@ import {
16
16
  } from "./chunk-L6RUHCKB.js";
17
17
  import {
18
18
  disposePty
19
- } from "./chunk-UAAH334K.js";
19
+ } from "./chunk-7JPCVEOY.js";
20
20
  import {
21
21
  shownState
22
22
  } from "./chunk-427RB7E4.js";
@@ -26,7 +26,7 @@ import {
26
26
  import {
27
27
  checkedOutBranch,
28
28
  readPendingForSession
29
- } from "./chunk-RG63ACAK.js";
29
+ } from "./chunk-PVN5IGDZ.js";
30
30
  import {
31
31
  buildFoldersOf,
32
32
  clearBuildFolders
@@ -272,4 +272,4 @@ export {
272
272
  archiveMergedSession,
273
273
  defaultArchiveDeps
274
274
  };
275
- //# sourceMappingURL=chunk-RMICESXA.js.map
275
+ //# sourceMappingURL=chunk-KUWFGPGW.js.map
@@ -203,6 +203,23 @@ var PtyHostClient = class {
203
203
  return false;
204
204
  }
205
205
  }
206
+ /**
207
+ * Its agent restarted in place, the attached terminals kept (registry.restart).
208
+ * `unsupported`: a host from before the call (404) — stop and start it instead.
209
+ */
210
+ async restart(id) {
211
+ const res = await fetch(`http://127.0.0.1:${this.info.port}/ptys/${encodeURIComponent(id)}/restart`, {
212
+ method: "POST",
213
+ headers: { "x-work-token": this.info.token },
214
+ // Waits for the old process to exit (up to 3 s) before the new one starts.
215
+ signal: AbortSignal.timeout(15e3)
216
+ });
217
+ if (res.ok) return "restarted";
218
+ if (res.status === 409) return "not-running";
219
+ if (res.status === 404) return "unsupported";
220
+ const json = await res.json().catch(() => ({}));
221
+ throw new Error(json.error ?? `PTY host restart ${id}: ${res.status}`);
222
+ }
206
223
  async kill(id) {
207
224
  await this.call("DELETE", `/ptys/${encodeURIComponent(id)}`);
208
225
  }
@@ -227,4 +244,4 @@ export {
227
244
  ensureHost,
228
245
  PtyHostClient
229
246
  };
230
- //# sourceMappingURL=chunk-ACXPSQJR.js.map
247
+ //# sourceMappingURL=chunk-MI3PS2SH.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/pty/pty-host-protocol.ts","../src/core/pty/pty-host-client.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { getConfigDir } from '../platform/config.js';\nimport type { AiToolSpec } from '../platform/ai-launcher.js';\n\n/**\n * Wire contract between the PTY host (`work pty-host`, the long-lived\n * process that owns every Claude PTY) and its clients (`work web`,\n * `work attach`). Bump PROTOCOL_VERSION on any incompatible change: a\n * client that finds an older host running tells the user to restart it\n * (`work pty-host --restart`) instead of silently misbehaving — the host\n * outlives rebuilds by design.\n *\n * 2: the restore list moved from pty-sessions.json into state.db. A v1 host\n * still writes the file, which a v2 host adopts on start\n * (adoptLegacyRestoreList).\n */\nexport const PROTOCOL_VERSION = 2;\n\n/** Discovery file: where the running host listens and its auth token. */\nexport interface HostInfo {\n pid: number;\n port: number;\n token: string;\n version: number;\n}\n\n/** What a client asks the host to spawn. The host decides `--continue`\n * itself (see `hasClaudeConversation`) so restores after a reboot make\n * the same call a fresh spawn would. */\nexport interface SpawnSpec {\n cwd: string;\n tool: AiToolSpec;\n port?: number;\n cols?: number;\n rows?: number;\n /** `--unsafe`: the tool's skip-permissions flag. Persisted, so a restore\n * comes back with the same permission mode. */\n unsafe?: boolean;\n /** `--fresh`: start a new conversation even if one exists. First spawn\n * only — a restore always continues. */\n fresh?: boolean;\n /** `--prompt` / `--prompt-file` contents. First spawn only. */\n initialPrompt?: string;\n /** The launching shell's environment. First spawn only and never\n * persisted — it can hold secrets; a restore after reboot uses the\n * host's own environment. */\n env?: Record<string, string>;\n}\n\n/** One entry of the host's restore list: how to respawn a session. The\n * spec as launched, minus `env` (never persisted: it can hold secrets) —\n * except the variables config `hostEnv` names (`keptEnv`), which a restore\n * after a reboot puts back over the host's own environment. */\nexport interface PersistedPty extends SpawnSpec {\n startedAt: string;\n keptEnv?: Record<string, string>;\n}\n\n/** Names that look like secrets (or carry them, as a connection string does): never kept on disk, whatever `hostEnv` says. */\nconst SECRET_NAME =\n /TOKEN|SECRET|PASS|PWD|CREDENTIAL|PRIVATE|KEY|AUTH|BEARER|COOKIE|SESSION|CERT|SIGN|SALT|(^|_)PAT($|_)|DSN|CONN|DATABASE_URL|_URI$|_URL$/i;\n/** Values that carry a password whatever their name: `scheme://user:pass@host`. */\nconst SECRET_VALUE = /:\\/\\/[^/\\s:@]+:[^/\\s@]+@/;\n\n/** The variables of `env` to keep for a restore: the ones named, that exist, and look like neither a secret nor a URL with a password in it. Pure. */\nexport function keepEnv(env: Record<string, string> | undefined, names: readonly string[]): Record<string, string> | undefined {\n if (!env) return undefined;\n const kept = Object.fromEntries(\n names.filter((n) => !SECRET_NAME.test(n) && typeof env[n] === 'string' && !SECRET_VALUE.test(env[n])).map((n) => [n, env[n]]),\n );\n return Object.keys(kept).length ? kept : undefined;\n}\nexport type PersistedPtys = Record<string, PersistedPty>;\n\n/** Shape check for a restore-list entry read back from storage. */\nexport function isPersistedPty(x: unknown): x is PersistedPty {\n const e = x as PersistedPty | null;\n return (\n !!e &&\n typeof e === 'object' &&\n typeof e.cwd === 'string' &&\n !!e.tool &&\n typeof e.tool === 'object' &&\n (e.keptEnv === undefined ||\n (!!e.keptEnv && typeof e.keptEnv === 'object' && Object.values(e.keptEnv).every((v) => typeof v === 'string')))\n );\n}\n\nexport interface PtyInfo {\n id: string;\n cwd: string;\n pid: number;\n exited: boolean;\n cols: number;\n rows: number;\n startedAt: string;\n /** Respawned by the host on startup from the persisted session list\n * (after a crash, `--restart` or reboot), not by a client. */\n restored: boolean;\n /** Clients attached right now (dashboard Terminal tabs, `work attach`).\n * Additive: a host from before it sends none. */\n clients?: number;\n /** When the PTY last printed anything (ISO). Additive, like clients. */\n lastOutputAt?: string;\n /** The tool's binary (`claude`, `opencode`…). Additive, like clients. */\n tool?: string;\n}\n\n/** Client → host frames on the attach WebSocket (text, JSON). Host →\n * client PTY output is sent as binary frames; control frames as text. */\nexport type ClientFrame = { type: 'input'; data: string } | { type: 'resize'; cols: number; rows: number };\n\nexport type HostControlFrame =\n /** Sent once, first, on attach: the serialized screen and the grid it was\n * drawn for. Clients draw it at exactly cols×rows, then resize to their\n * own size (which makes Claude redraw), and only then send input. */\n { type: 'replay'; data: string; cols: number; rows: number } | { type: 'exit'; code: number } | { type: 'error'; message: string };\n\nexport function hostInfoPath(): string {\n return path.join(getConfigDir(), 'pty-host.json');\n}\n\n/** Held by a starting host from \"is one running?\" through writing its\n * discovery file AND restoring the saved sessions — so two hosts can't\n * both start, and a `work remove` racing a start waits for the restore\n * instead of slipping between it (see stopSessionPty). */\nexport function hostStartLockPath(): string {\n return path.join(getConfigDir(), 'pty-host.start.lock');\n}\n\n/** The pre-SQLite restore list. Only the one-time import reads it now. */\nexport function ptySessionsPath(): string {\n return path.join(getConfigDir(), 'pty-sessions.json');\n}\n\nexport function readHostInfo(): HostInfo | null {\n try {\n const raw = JSON.parse(fs.readFileSync(hostInfoPath(), 'utf-8')) as HostInfo;\n if (typeof raw.port === 'number' && typeof raw.token === 'string' && typeof raw.pid === 'number') {\n return raw;\n }\n return null;\n } catch {\n return null;\n }\n}\n","import path from 'node:path';\nimport { spawnDetachedWork } from '../platform/process.js';\nimport { getConfigDir } from '../platform/config.js';\nimport { isPidAlive } from '../platform/process.js';\nimport { ensureFile, withFileLock } from '../platform/fs-safe.js';\nimport { PROTOCOL_VERSION, readHostInfo, type HostInfo, type PtyInfo, type SpawnSpec } from './pty-host-protocol.js';\n\nexport class PtyHostVersionError extends Error {\n constructor(readonly hostVersion: number) {\n super(\n `A PTY host from an older build (protocol v${hostVersion}, need v${PROTOCOL_VERSION}) ` +\n 'is running. Restart it with `work pty-host --restart` — sessions come back via --continue.',\n );\n }\n}\n\n/**\n * Ask whoever listens on the discovery file's port whether it's our host:\n * it must answer /health with our token. Returns what it reports (its\n * protocol version and pid), or null if nothing answers / the token is\n * wrong — i.e. the discovery file is stale.\n */\nexport async function probeHost(info: HostInfo, timeoutMs = 800): Promise<{ version: number; pid: number } | null> {\n const r = await probeHostDetailed(info, timeoutMs);\n return r.kind === 'host' ? { version: r.version, pid: r.pid } : null;\n}\n\nexport type ProbeResult =\n | { kind: 'host'; version: number; pid: number }\n /** Nothing listens on the port (connection refused): definitely gone. */\n | { kind: 'refused' }\n /** Something answered, but not as our host (wrong token, bad body). */\n | { kind: 'not-ours' }\n /** No answer in time — could be a BUSY host (e.g. restoring many\n * sessions). Never treat this as proof the host is gone. */\n | { kind: 'timeout' };\n\nexport async function probeHostDetailed(info: HostInfo, timeoutMs = 800): Promise<ProbeResult> {\n try {\n const res = await fetch(`http://127.0.0.1:${info.port}/health`, {\n headers: { 'x-work-token': info.token },\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!res.ok) return { kind: 'not-ours' };\n const body = (await res.json()) as { version?: number; pid?: number };\n if (typeof body.version !== 'number' || typeof body.pid !== 'number') return { kind: 'not-ours' };\n return { kind: 'host', version: body.version, pid: body.pid };\n } catch (err) {\n const e = err as { name?: string; cause?: { code?: string } };\n if (e.cause?.code === 'ECONNREFUSED') return { kind: 'refused' };\n if (e.name === 'TimeoutError' || e.name === 'AbortError') return { kind: 'timeout' };\n return { kind: 'refused' };\n }\n}\n\n/** A host is there but didn't answer in time (event loop busy: a ConPTY\n * spawn, restoring many sessions). It is RUNNING — never start another. */\nexport class PtyHostBusyError extends Error {\n constructor() {\n super('The PTY host is running but not answering (busy?). Try again in a moment.');\n this.name = 'PtyHostBusyError';\n }\n}\n\n/**\n * The running host, or null when there is none. Throws PtyHostVersionError\n * on a mismatch, and PtyHostBusyError when a host holds the port but\n * doesn't answer even a patient second probe — treating that as \"no host\"\n * would start a second one, which restores every session again (two\n * Claudes per conversation).\n */\nexport async function findHost(timeoutsMs: number[] = [800, 5000]): Promise<HostInfo | null> {\n const info = readHostInfo();\n if (!info) return null;\n let probe: ProbeResult = { kind: 'timeout' };\n for (const t of timeoutsMs) {\n probe = await probeHostDetailed(info, t);\n if (probe.kind !== 'timeout') break;\n }\n if (probe.kind === 'timeout') {\n // No answer: a host whose process is alive is busy — but a dead one\n // (crashed, killed) left a stale file, and whatever now holds that port\n // is not our host. Calling THAT busy would make the host unstartable.\n if (!isPidAlive(info.pid)) return null;\n throw new PtyHostBusyError();\n }\n if (probe.kind !== 'host' || probe.pid !== info.pid) return null;\n if (probe.version !== PROTOCOL_VERSION) throw new PtyHostVersionError(probe.version);\n return info;\n}\n\n/**\n * findHost that waits out a busy host: retries until it answers or\n * `timeoutMs` passes, then throws PtyHostBusyError. For callers that must\n * reach the host (stopping a session before its worktree is deleted).\n */\nexport async function findHostPatient(timeoutMs = 20_000): Promise<HostInfo | null> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n try {\n return await findHost();\n } catch (err) {\n if (!(err instanceof PtyHostBusyError) || Date.now() >= deadline) throw err;\n await new Promise((r) => setTimeout(r, 250));\n }\n }\n}\n\n/** findHost for \"should I start one?\": a busy host counts as running. */\nasync function findHostOrBusy(): Promise<HostInfo | 'busy' | null> {\n try {\n return await findHost();\n } catch (err) {\n if (err instanceof PtyHostBusyError) return 'busy';\n throw err;\n }\n}\n\n/** Serializes host spawning across `work` processes (see ensureHost). */\nexport function hostSpawnLockPath(): string {\n return path.join(getConfigDir(), 'pty-host.spawn.lock');\n}\n\nlet inFlight: Promise<HostInfo> | null = null;\n\n/**\n * Return the running host, spawning a detached one if none is. `workBin` is\n * the path to the `work` binary (dist/bin.js) — passed in rather than\n * derived because core can't reach the commands layer's resolver (§2.1).\n *\n * Exactly one host may start: two hosts would each restore every saved\n * session — two Claudes on one conversation. So spawning is single-flight\n * within this process (concurrent callers share one attempt) and serialized\n * across processes by a file lock held from \"is one running?\" until the new\n * host answers; a caller that waited on the lock re-checks and finds it.\n */\n// A cold host start loads the whole `work` bundle; on a busy machine (right\n// after login with autostart, or a loaded test run) that can pass 8 s.\nexport function ensureHost(workBin: string, timeoutMs = 20_000): Promise<HostInfo> {\n if (!inFlight) {\n inFlight = ensureHostLocked(workBin, timeoutMs).finally(() => {\n inFlight = null;\n });\n }\n return inFlight;\n}\n\nasync function ensureHostLocked(workBin: string, timeoutMs: number): Promise<HostInfo> {\n const existing = await findHostOrBusy();\n if (existing === 'busy') return waitForHost(timeoutMs); // it's there; wait for it to answer\n if (existing) return existing;\n const lock = hostSpawnLockPath();\n ensureFile(lock, '');\n try {\n return await withFileLock(lock, async () => {\n // Another process may have started it while we waited for the lock.\n const started = await findHostOrBusy();\n if (started === 'busy') return waitForHost(timeoutMs);\n if (started) return started;\n spawnHost(workBin);\n return waitForHost(timeoutMs);\n });\n } catch (err) {\n // Couldn't get the lock in time (another process is mid-spawn and slow):\n // don't spawn a second one — wait for theirs.\n if ((err as { code?: string }).code === 'ELOCKED') return waitForHost(timeoutMs);\n throw err;\n }\n}\n\nfunction spawnHost(workBin: string): void {\n spawnDetachedWork(workBin, ['pty-host'], path.join(getConfigDir(), 'pty-host.log'));\n}\n\nasync function waitForHost(timeoutMs: number): Promise<HostInfo> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const found = await findHost().catch(() => null);\n if (found) return found;\n await new Promise((r) => setTimeout(r, 100));\n }\n throw new Error('PTY host did not start (see ~/.work/pty-host.log)');\n}\n\nexport class PtyHostClient {\n constructor(readonly info: HostInfo) {}\n\n private async call<T>(method: string, p: string, body?: unknown): Promise<T> {\n const res = await fetch(`http://127.0.0.1:${this.info.port}${p}`, {\n method,\n headers: {\n 'x-work-token': this.info.token,\n ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal: AbortSignal.timeout(5000),\n });\n const json = (await res.json().catch(() => ({}))) as T & { error?: string };\n if (!res.ok) throw new Error(json.error ?? `PTY host ${method} ${p}: ${res.status}`);\n return json;\n }\n\n list(): Promise<PtyInfo[]> {\n return this.call('GET', '/ptys');\n }\n\n get(id: string): Promise<PtyInfo | null> {\n return this.call<PtyInfo>('GET', `/ptys/${encodeURIComponent(id)}`).catch(() => null);\n }\n\n spawn(id: string, spec: SpawnSpec): Promise<PtyInfo> {\n return this.call('POST', `/ptys/${encodeURIComponent(id)}`, spec);\n }\n\n /** The session's visible screen as text; null when it has none — or the\n * host predates this call (404 either way: nothing to answer by key). */\n async screen(id: string): Promise<string | null> {\n try {\n const r = await this.call<{ text?: unknown }>('GET', `/ptys/${encodeURIComponent(id)}/screen`);\n return typeof r.text === 'string' ? r.text : null;\n } catch {\n return null;\n }\n }\n\n async write(id: string, data: string): Promise<boolean> {\n try {\n await this.call('POST', `/ptys/${encodeURIComponent(id)}/write`, { data });\n return true;\n } catch {\n return false;\n }\n }\n\n async kill(id: string): Promise<void> {\n await this.call('DELETE', `/ptys/${encodeURIComponent(id)}`);\n }\n\n attachUrl(id: string): string {\n return `ws://127.0.0.1:${this.info.port}/ptys/${encodeURIComponent(id)}/attach?token=${this.info.token}`;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAgBV,IAAM,mBAAmB;AA2ChC,IAAM,cACJ;AAEF,IAAM,eAAe;AAGd,SAAS,QAAQ,KAAyC,OAA8D;AAC7H,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,OAAO,OAAO;AAAA,IAClB,MAAM,OAAO,CAAC,MAAM,CAAC,YAAY,KAAK,CAAC,KAAK,OAAO,IAAI,CAAC,MAAM,YAAY,CAAC,aAAa,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;AAAA,EAC9H;AACA,SAAO,OAAO,KAAK,IAAI,EAAE,SAAS,OAAO;AAC3C;AAIO,SAAS,eAAe,GAA+B;AAC5D,QAAM,IAAI;AACV,SACE,CAAC,CAAC,KACF,OAAO,MAAM,YACb,OAAO,EAAE,QAAQ,YACjB,CAAC,CAAC,EAAE,QACJ,OAAO,EAAE,SAAS,aACjB,EAAE,YAAY,UACZ,CAAC,CAAC,EAAE,WAAW,OAAO,EAAE,YAAY,YAAY,OAAO,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,OAAO,MAAM,QAAQ;AAElH;AAgCO,SAAS,eAAuB;AACrC,SAAO,KAAK,KAAK,aAAa,GAAG,eAAe;AAClD;AAMO,SAAS,oBAA4B;AAC1C,SAAO,KAAK,KAAK,aAAa,GAAG,qBAAqB;AACxD;AAGO,SAAS,kBAA0B;AACxC,SAAO,KAAK,KAAK,aAAa,GAAG,mBAAmB;AACtD;AAEO,S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;AACF;","names":["path","path"]}
1
+ {"version":3,"sources":["../src/core/pty/pty-host-protocol.ts","../src/core/pty/pty-host-client.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { getConfigDir } from '../platform/config.js';\nimport type { AiToolSpec } from '../platform/ai-launcher.js';\n\n/**\n * Wire contract between the PTY host (`work pty-host`, the long-lived\n * process that owns every Claude PTY) and its clients (`work web`,\n * `work attach`). Bump PROTOCOL_VERSION on any incompatible change: a\n * client that finds an older host running tells the user to restart it\n * (`work pty-host --restart`) instead of silently misbehaving — the host\n * outlives rebuilds by design.\n *\n * 2: the restore list moved from pty-sessions.json into state.db. A v1 host\n * still writes the file, which a v2 host adopts on start\n * (adoptLegacyRestoreList).\n */\nexport const PROTOCOL_VERSION = 2;\n\n/** Discovery file: where the running host listens and its auth token. */\nexport interface HostInfo {\n pid: number;\n port: number;\n token: string;\n version: number;\n}\n\n/** What a client asks the host to spawn. The host decides `--continue`\n * itself (see `hasClaudeConversation`) so restores after a reboot make\n * the same call a fresh spawn would. */\nexport interface SpawnSpec {\n cwd: string;\n tool: AiToolSpec;\n port?: number;\n cols?: number;\n rows?: number;\n /** `--unsafe`: the tool's skip-permissions flag. Persisted, so a restore\n * comes back with the same permission mode. */\n unsafe?: boolean;\n /** `--fresh`: start a new conversation even if one exists. First spawn\n * only — a restore always continues. */\n fresh?: boolean;\n /** `--prompt` / `--prompt-file` contents. First spawn only. */\n initialPrompt?: string;\n /** The launching shell's environment. First spawn only and never\n * persisted — it can hold secrets; a restore after reboot uses the\n * host's own environment. */\n env?: Record<string, string>;\n}\n\n/** One entry of the host's restore list: how to respawn a session. The\n * spec as launched, minus `env` (never persisted: it can hold secrets) —\n * except the variables config `hostEnv` names (`keptEnv`), which a restore\n * after a reboot puts back over the host's own environment. */\nexport interface PersistedPty extends SpawnSpec {\n startedAt: string;\n keptEnv?: Record<string, string>;\n}\n\n/** Names that look like secrets (or carry them, as a connection string does): never kept on disk, whatever `hostEnv` says. */\nconst SECRET_NAME =\n /TOKEN|SECRET|PASS|PWD|CREDENTIAL|PRIVATE|KEY|AUTH|BEARER|COOKIE|SESSION|CERT|SIGN|SALT|(^|_)PAT($|_)|DSN|CONN|DATABASE_URL|_URI$|_URL$/i;\n/** Values that carry a password whatever their name: `scheme://user:pass@host`. */\nconst SECRET_VALUE = /:\\/\\/[^/\\s:@]+:[^/\\s@]+@/;\n\n/** The variables of `env` to keep for a restore: the ones named, that exist, and look like neither a secret nor a URL with a password in it. Pure. */\nexport function keepEnv(env: Record<string, string> | undefined, names: readonly string[]): Record<string, string> | undefined {\n if (!env) return undefined;\n const kept = Object.fromEntries(\n names.filter((n) => !SECRET_NAME.test(n) && typeof env[n] === 'string' && !SECRET_VALUE.test(env[n])).map((n) => [n, env[n]]),\n );\n return Object.keys(kept).length ? kept : undefined;\n}\nexport type PersistedPtys = Record<string, PersistedPty>;\n\n/** Shape check for a restore-list entry read back from storage. */\nexport function isPersistedPty(x: unknown): x is PersistedPty {\n const e = x as PersistedPty | null;\n return (\n !!e &&\n typeof e === 'object' &&\n typeof e.cwd === 'string' &&\n !!e.tool &&\n typeof e.tool === 'object' &&\n (e.keptEnv === undefined ||\n (!!e.keptEnv && typeof e.keptEnv === 'object' && Object.values(e.keptEnv).every((v) => typeof v === 'string')))\n );\n}\n\nexport interface PtyInfo {\n id: string;\n cwd: string;\n pid: number;\n exited: boolean;\n cols: number;\n rows: number;\n startedAt: string;\n /** Respawned by the host on startup from the persisted session list\n * (after a crash, `--restart` or reboot), not by a client. */\n restored: boolean;\n /** Clients attached right now (dashboard Terminal tabs, `work attach`).\n * Additive: a host from before it sends none. */\n clients?: number;\n /** When the PTY last printed anything (ISO). Additive, like clients. */\n lastOutputAt?: string;\n /** The tool's binary (`claude`, `opencode`…). Additive, like clients. */\n tool?: string;\n}\n\n/** Client → host frames on the attach WebSocket (text, JSON). Host →\n * client PTY output is sent as binary frames; control frames as text. */\nexport type ClientFrame = { type: 'input'; data: string } | { type: 'resize'; cols: number; rows: number };\n\nexport type HostControlFrame =\n /** Sent once, first, on attach: the serialized screen and the grid it was\n * drawn for. Clients draw it at exactly cols×rows, then resize to their\n * own size (which makes Claude redraw), and only then send input. */\n { type: 'replay'; data: string; cols: number; rows: number } | { type: 'exit'; code: number } | { type: 'error'; message: string };\n\nexport function hostInfoPath(): string {\n return path.join(getConfigDir(), 'pty-host.json');\n}\n\n/** Held by a starting host from \"is one running?\" through writing its\n * discovery file AND restoring the saved sessions — so two hosts can't\n * both start, and a `work remove` racing a start waits for the restore\n * instead of slipping between it (see stopSessionPty). */\nexport function hostStartLockPath(): string {\n return path.join(getConfigDir(), 'pty-host.start.lock');\n}\n\n/** The pre-SQLite restore list. Only the one-time import reads it now. */\nexport function ptySessionsPath(): string {\n return path.join(getConfigDir(), 'pty-sessions.json');\n}\n\nexport function readHostInfo(): HostInfo | null {\n try {\n const raw = JSON.parse(fs.readFileSync(hostInfoPath(), 'utf-8')) as HostInfo;\n if (typeof raw.port === 'number' && typeof raw.token === 'string' && typeof raw.pid === 'number') {\n return raw;\n }\n return null;\n } catch {\n return null;\n }\n}\n","import path from 'node:path';\nimport { spawnDetachedWork } from '../platform/process.js';\nimport { getConfigDir } from '../platform/config.js';\nimport { isPidAlive } from '../platform/process.js';\nimport { ensureFile, withFileLock } from '../platform/fs-safe.js';\nimport { PROTOCOL_VERSION, readHostInfo, type HostInfo, type PtyInfo, type SpawnSpec } from './pty-host-protocol.js';\n\nexport class PtyHostVersionError extends Error {\n constructor(readonly hostVersion: number) {\n super(\n `A PTY host from an older build (protocol v${hostVersion}, need v${PROTOCOL_VERSION}) ` +\n 'is running. Restart it with `work pty-host --restart` — sessions come back via --continue.',\n );\n }\n}\n\n/**\n * Ask whoever listens on the discovery file's port whether it's our host:\n * it must answer /health with our token. Returns what it reports (its\n * protocol version and pid), or null if nothing answers / the token is\n * wrong — i.e. the discovery file is stale.\n */\nexport async function probeHost(info: HostInfo, timeoutMs = 800): Promise<{ version: number; pid: number } | null> {\n const r = await probeHostDetailed(info, timeoutMs);\n return r.kind === 'host' ? { version: r.version, pid: r.pid } : null;\n}\n\nexport type ProbeResult =\n | { kind: 'host'; version: number; pid: number }\n /** Nothing listens on the port (connection refused): definitely gone. */\n | { kind: 'refused' }\n /** Something answered, but not as our host (wrong token, bad body). */\n | { kind: 'not-ours' }\n /** No answer in time — could be a BUSY host (e.g. restoring many\n * sessions). Never treat this as proof the host is gone. */\n | { kind: 'timeout' };\n\nexport async function probeHostDetailed(info: HostInfo, timeoutMs = 800): Promise<ProbeResult> {\n try {\n const res = await fetch(`http://127.0.0.1:${info.port}/health`, {\n headers: { 'x-work-token': info.token },\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!res.ok) return { kind: 'not-ours' };\n const body = (await res.json()) as { version?: number; pid?: number };\n if (typeof body.version !== 'number' || typeof body.pid !== 'number') return { kind: 'not-ours' };\n return { kind: 'host', version: body.version, pid: body.pid };\n } catch (err) {\n const e = err as { name?: string; cause?: { code?: string } };\n if (e.cause?.code === 'ECONNREFUSED') return { kind: 'refused' };\n if (e.name === 'TimeoutError' || e.name === 'AbortError') return { kind: 'timeout' };\n return { kind: 'refused' };\n }\n}\n\n/** A host is there but didn't answer in time (event loop busy: a ConPTY\n * spawn, restoring many sessions). It is RUNNING — never start another. */\nexport class PtyHostBusyError extends Error {\n constructor() {\n super('The PTY host is running but not answering (busy?). Try again in a moment.');\n this.name = 'PtyHostBusyError';\n }\n}\n\n/**\n * The running host, or null when there is none. Throws PtyHostVersionError\n * on a mismatch, and PtyHostBusyError when a host holds the port but\n * doesn't answer even a patient second probe — treating that as \"no host\"\n * would start a second one, which restores every session again (two\n * Claudes per conversation).\n */\nexport async function findHost(timeoutsMs: number[] = [800, 5000]): Promise<HostInfo | null> {\n const info = readHostInfo();\n if (!info) return null;\n let probe: ProbeResult = { kind: 'timeout' };\n for (const t of timeoutsMs) {\n probe = await probeHostDetailed(info, t);\n if (probe.kind !== 'timeout') break;\n }\n if (probe.kind === 'timeout') {\n // No answer: a host whose process is alive is busy — but a dead one\n // (crashed, killed) left a stale file, and whatever now holds that port\n // is not our host. Calling THAT busy would make the host unstartable.\n if (!isPidAlive(info.pid)) return null;\n throw new PtyHostBusyError();\n }\n if (probe.kind !== 'host' || probe.pid !== info.pid) return null;\n if (probe.version !== PROTOCOL_VERSION) throw new PtyHostVersionError(probe.version);\n return info;\n}\n\n/**\n * findHost that waits out a busy host: retries until it answers or\n * `timeoutMs` passes, then throws PtyHostBusyError. For callers that must\n * reach the host (stopping a session before its worktree is deleted).\n */\nexport async function findHostPatient(timeoutMs = 20_000): Promise<HostInfo | null> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n try {\n return await findHost();\n } catch (err) {\n if (!(err instanceof PtyHostBusyError) || Date.now() >= deadline) throw err;\n await new Promise((r) => setTimeout(r, 250));\n }\n }\n}\n\n/** findHost for \"should I start one?\": a busy host counts as running. */\nasync function findHostOrBusy(): Promise<HostInfo | 'busy' | null> {\n try {\n return await findHost();\n } catch (err) {\n if (err instanceof PtyHostBusyError) return 'busy';\n throw err;\n }\n}\n\n/** Serializes host spawning across `work` processes (see ensureHost). */\nexport function hostSpawnLockPath(): string {\n return path.join(getConfigDir(), 'pty-host.spawn.lock');\n}\n\nlet inFlight: Promise<HostInfo> | null = null;\n\n/**\n * Return the running host, spawning a detached one if none is. `workBin` is\n * the path to the `work` binary (dist/bin.js) — passed in rather than\n * derived because core can't reach the commands layer's resolver (§2.1).\n *\n * Exactly one host may start: two hosts would each restore every saved\n * session — two Claudes on one conversation. So spawning is single-flight\n * within this process (concurrent callers share one attempt) and serialized\n * across processes by a file lock held from \"is one running?\" until the new\n * host answers; a caller that waited on the lock re-checks and finds it.\n */\n// A cold host start loads the whole `work` bundle; on a busy machine (right\n// after login with autostart, or a loaded test run) that can pass 8 s.\nexport function ensureHost(workBin: string, timeoutMs = 20_000): Promise<HostInfo> {\n if (!inFlight) {\n inFlight = ensureHostLocked(workBin, timeoutMs).finally(() => {\n inFlight = null;\n });\n }\n return inFlight;\n}\n\nasync function ensureHostLocked(workBin: string, timeoutMs: number): Promise<HostInfo> {\n const existing = await findHostOrBusy();\n if (existing === 'busy') return waitForHost(timeoutMs); // it's there; wait for it to answer\n if (existing) return existing;\n const lock = hostSpawnLockPath();\n ensureFile(lock, '');\n try {\n return await withFileLock(lock, async () => {\n // Another process may have started it while we waited for the lock.\n const started = await findHostOrBusy();\n if (started === 'busy') return waitForHost(timeoutMs);\n if (started) return started;\n spawnHost(workBin);\n return waitForHost(timeoutMs);\n });\n } catch (err) {\n // Couldn't get the lock in time (another process is mid-spawn and slow):\n // don't spawn a second one — wait for theirs.\n if ((err as { code?: string }).code === 'ELOCKED') return waitForHost(timeoutMs);\n throw err;\n }\n}\n\nfunction spawnHost(workBin: string): void {\n spawnDetachedWork(workBin, ['pty-host'], path.join(getConfigDir(), 'pty-host.log'));\n}\n\nasync function waitForHost(timeoutMs: number): Promise<HostInfo> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const found = await findHost().catch(() => null);\n if (found) return found;\n await new Promise((r) => setTimeout(r, 100));\n }\n throw new Error('PTY host did not start (see ~/.work/pty-host.log)');\n}\n\nexport class PtyHostClient {\n constructor(readonly info: HostInfo) {}\n\n private async call<T>(method: string, p: string, body?: unknown): Promise<T> {\n const res = await fetch(`http://127.0.0.1:${this.info.port}${p}`, {\n method,\n headers: {\n 'x-work-token': this.info.token,\n ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n },\n body: body !== undefined ? JSON.stringify(body) : undefined,\n signal: AbortSignal.timeout(5000),\n });\n const json = (await res.json().catch(() => ({}))) as T & { error?: string };\n if (!res.ok) throw new Error(json.error ?? `PTY host ${method} ${p}: ${res.status}`);\n return json;\n }\n\n list(): Promise<PtyInfo[]> {\n return this.call('GET', '/ptys');\n }\n\n get(id: string): Promise<PtyInfo | null> {\n return this.call<PtyInfo>('GET', `/ptys/${encodeURIComponent(id)}`).catch(() => null);\n }\n\n spawn(id: string, spec: SpawnSpec): Promise<PtyInfo> {\n return this.call('POST', `/ptys/${encodeURIComponent(id)}`, spec);\n }\n\n /** The session's visible screen as text; null when it has none — or the\n * host predates this call (404 either way: nothing to answer by key). */\n async screen(id: string): Promise<string | null> {\n try {\n const r = await this.call<{ text?: unknown }>('GET', `/ptys/${encodeURIComponent(id)}/screen`);\n return typeof r.text === 'string' ? r.text : null;\n } catch {\n return null;\n }\n }\n\n async write(id: string, data: string): Promise<boolean> {\n try {\n await this.call('POST', `/ptys/${encodeURIComponent(id)}/write`, { data });\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * Its agent restarted in place, the attached terminals kept (registry.restart).\n * `unsupported`: a host from before the call (404) — stop and start it instead.\n */\n async restart(id: string): Promise<'restarted' | 'not-running' | 'unsupported'> {\n const res = await fetch(`http://127.0.0.1:${this.info.port}/ptys/${encodeURIComponent(id)}/restart`, {\n method: 'POST',\n headers: { 'x-work-token': this.info.token },\n // Waits for the old process to exit (up to 3 s) before the new one starts.\n signal: AbortSignal.timeout(15_000),\n });\n if (res.ok) return 'restarted';\n if (res.status === 409) return 'not-running';\n if (res.status === 404) return 'unsupported';\n const json = (await res.json().catch(() => ({}))) as { error?: string };\n throw new Error(json.error ?? `PTY host restart ${id}: ${res.status}`);\n }\n\n async kill(id: string): Promise<void> {\n await this.call('DELETE', `/ptys/${encodeURIComponent(id)}`);\n }\n\n attachUrl(id: string): string {\n return `ws://127.0.0.1:${this.info.port}/ptys/${encodeURIComponent(id)}/attach?token=${this.info.token}`;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AAgBV,IAAM,mBAAmB;AA2ChC,IAAM,cACJ;AAEF,IAAM,eAAe;AAGd,SAAS,QAAQ,KAAyC,OAA8D;AAC7H,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,OAAO,OAAO;AAAA,IAClB,MAAM,OAAO,CAAC,MAAM,CAAC,YAAY,KAAK,CAAC,KAAK,OAAO,IAAI,C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;AAAA,EACxG;AACF;","names":["path","path"]}
@@ -4,17 +4,18 @@ import {
4
4
  } from "./chunk-L6RUHCKB.js";
5
5
  import {
6
6
  peekPty
7
- } from "./chunk-UAAH334K.js";
7
+ } from "./chunk-7JPCVEOY.js";
8
8
  import {
9
9
  sessionStatusView
10
10
  } from "./chunk-427RB7E4.js";
11
11
  import {
12
12
  checkedOutBranch,
13
- readPendingForSession
14
- } from "./chunk-RG63ACAK.js";
13
+ readPendingForWorktree,
14
+ scopeStoreIdsForPaths
15
+ } from "./chunk-PVN5IGDZ.js";
15
16
  import {
16
- getCommentFileStore
17
- } from "./chunk-7HGABVGR.js";
17
+ readStoresComments
18
+ } from "./chunk-E3Y4ZACK.js";
18
19
  import {
19
20
  STAGE_WANTS_YOU,
20
21
  archiveDirFor,
@@ -41,9 +42,56 @@ import {
41
42
  import fs2 from "fs";
42
43
  import path from "path";
43
44
 
45
+ // src/core/comments/linked-stores.ts
46
+ var linkedSession = (s) => ({ id: sessionIdFor(s), paths: s.paths });
47
+ function sessionLinkedStoreIds(session) {
48
+ return [session.id, ...scopeStoreIdsForPaths(session.paths)];
49
+ }
50
+ function scopeLinkedStoreIds(hash, sessions) {
51
+ const own = `scope-${hash}`;
52
+ return [own, ...new Set(sessions.filter((s) => scopeStoreIdsForPaths(s.paths).includes(own)).map((s) => s.id))];
53
+ }
54
+ function readerFor(storeIds) {
55
+ const rows = readStoresComments(storeIds);
56
+ return (id) => rows.get(id) ?? [];
57
+ }
58
+ function linkedComments(storeIds, read = readerFor(storeIds)) {
59
+ const seen = /* @__PURE__ */ new Set();
60
+ const out = [];
61
+ storeIds.forEach((id, i) => {
62
+ for (const c of read(id)) {
63
+ if (seen.has(c.id) || i > 0 && c.status === "draft") continue;
64
+ seen.add(c.id);
65
+ out.push(c);
66
+ }
67
+ });
68
+ return out.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
69
+ }
70
+ function storeHolding(storeIds, commentId, read = readerFor(storeIds)) {
71
+ return storeIds.find((id) => read(id).some((c) => c.id === commentId)) ?? null;
72
+ }
73
+ function viewersOf(storeId, sessions) {
74
+ if (storeId.startsWith("scope-")) {
75
+ return {
76
+ sessionIds: [...new Set(sessions.filter((s) => scopeStoreIdsForPaths(s.paths).includes(storeId)).map((s) => s.id))],
77
+ scopeHashes: [storeId.slice("scope-".length)]
78
+ };
79
+ }
80
+ const session = sessions.find((s) => s.id === storeId);
81
+ return {
82
+ sessionIds: [storeId],
83
+ scopeHashes: session ? scopeStoreIdsForPaths(session.paths).map((id) => id.slice("scope-".length)) : []
84
+ };
85
+ }
86
+ function announceChange(storeId, sessions, tell, data) {
87
+ const { sessionIds, scopeHashes } = viewersOf(storeId, sessions);
88
+ for (const sessionId of sessionIds) tell.session(sessionId, { ...data, sessionId });
89
+ for (const scopeHash of scopeHashes) tell.scope(scopeHash, { ...data, scopeHash });
90
+ }
91
+
44
92
  // src/core/sessions/session-meta.ts
45
93
  function readSessionMeta(sessionId, session) {
46
- const comments = getCommentFileStore(sessionId).snapshot();
94
+ const comments = linkedComments(sessionLinkedStoreIds({ id: sessionId, paths: session.paths }));
47
95
  let drafts = 0;
48
96
  let claude = 0;
49
97
  let open = 0;
@@ -53,7 +101,7 @@ function readSessionMeta(sessionId, session) {
53
101
  if (!c.parentId && !c.resolved) open++;
54
102
  }
55
103
  const activity = readSessionActivity(session);
56
- const pending = readPendingForSession(sessionId).length;
104
+ const pending = readPendingForWorktree(session, sessionId).length;
57
105
  const status = readStatus(sessionId);
58
106
  return {
59
107
  draftCount: drafts,
@@ -283,6 +331,12 @@ function createArchivedRows(archiveFile = (id) => path.join(archiveDirFor(id), "
283
331
  }
284
332
 
285
333
  export {
334
+ linkedSession,
335
+ sessionLinkedStoreIds,
336
+ scopeLinkedStoreIds,
337
+ linkedComments,
338
+ storeHolding,
339
+ announceChange,
286
340
  readContextUsage,
287
341
  sessionWire,
288
342
  reviewThreadsOf,
@@ -291,4 +345,4 @@ export {
291
345
  lastActiveMs,
292
346
  createArchivedRows
293
347
  };
294
- //# sourceMappingURL=chunk-AVRDRZ4D.js.map
348
+ //# sourceMappingURL=chunk-OZIR2255.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/sessions/session-wire.ts","../src/core/comments/linked-stores.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 type { WorktreeSession } from '../sessions/history.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport { readStoresComments } from './comment-file-store.js';\nimport { scopeStoreIdsForPaths } from './pending-delivery.js';\nimport type { Comment } from './comment-types.js';\n\n/**\n * One worktree's comments live in two kinds of store: the session's own (the\n * dashboard's Diff tab posts there) and a `wd` scope's (`scope-<hash>`: the\n * browser diff page, `/diff/<hash>`, posts there). Claude was handed both\n * (`readPendingForWorktree`), but each view showed only its own, so a comment\n * made on one wasn't there on the other. Each view now lists its own store\n * first and the linked ones after: the session's view its scope stores, a\n * scope's view the session(s) whose worktree it covers.\n *\n * The stores stay separate — a new `wd -c` run clears its scope's comments\n * (`ensureScope`), which must never clear the session's.\n */\n\n/** A session as these lookups need it: its id (its store's) and its worktree paths. */\nexport interface LinkedSession {\n id: string;\n paths: string[];\n}\n\nexport const linkedSession = (s: WorktreeSession): LinkedSession => ({ id: sessionIdFor(s), paths: s.paths });\n\n/** The session's store, then every scope store over its paths. */\nexport function sessionLinkedStoreIds(session: LinkedSession): string[] {\n return [session.id, ...scopeStoreIdsForPaths(session.paths)];\n}\n\n/** The scope's store, then each session whose paths that scope covers (the whole worktree, or one repo of a group). */\nexport function scopeLinkedStoreIds(hash: string, sessions: LinkedSession[]): string[] {\n const own = `scope-${hash}`;\n return [own, ...new Set(sessions.filter((s) => scopeStoreIdsForPaths(s.paths).includes(own)).map((s) => s.id))];\n}\n\nexport type Read = (storeId: string) => Comment[];\n\n/** These stores read in one query (they're mostly empty: a scope store has rows only once its page was commented on). */\nexport function readerFor(storeIds: string[]): Read {\n const rows = readStoresComments(storeIds);\n return (id) => rows.get(id) ?? [];\n}\n\n/**\n * Every comment the view shows: the first store's whole, the linked ones'\n * without their drafts (a draft is that view's unsent review; this view's\n * Submit wouldn't send it). Oldest first, each comment once.\n */\nexport function linkedComments(storeIds: string[], read: Read = readerFor(storeIds)): Comment[] {\n const seen = new Set<string>();\n const out: Comment[] = [];\n storeIds.forEach((id, i) => {\n for (const c of read(id)) {\n if (seen.has(c.id) || (i > 0 && c.status === 'draft')) continue;\n seen.add(c.id);\n out.push(c);\n }\n });\n return out.sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n}\n\n/** Which of these stores holds the comment (a delete, a resolve or a reply acts there), or null. */\nexport function storeHolding(storeIds: string[], commentId: string, read: Read = readerFor(storeIds)): string | null {\n return storeIds.find((id) => read(id).some((c) => c.id === commentId)) ?? null;\n}\n\n/** Who to tell a store changed: the sessions and scopes whose views list it. */\nexport function viewersOf(storeId: string, sessions: LinkedSession[]): { sessionIds: string[]; scopeHashes: string[] } {\n if (storeId.startsWith('scope-')) {\n return {\n sessionIds: [...new Set(sessions.filter((s) => scopeStoreIdsForPaths(s.paths).includes(storeId)).map((s) => s.id))],\n scopeHashes: [storeId.slice('scope-'.length)],\n };\n }\n const session = sessions.find((s) => s.id === storeId);\n return {\n sessionIds: [storeId],\n scopeHashes: session ? scopeStoreIdsForPaths(session.paths).map((id) => id.slice('scope-'.length)) : [],\n };\n}\n\n/** How a front-end tells a view its comments changed: a session's Diff tab by id, a scope page on its own stream. */\nexport interface Tell {\n session: (sessionId: string, data: Record<string, unknown>) => void;\n scope: (scopeHash: string, data: Record<string, unknown>) => void;\n}\n\n/** A store changed: every view listing it is told (both comment routes use this, so they can't drift apart). */\nexport function announceChange(storeId: string, sessions: LinkedSession[], tell: Tell, data: Record<string, unknown>): void {\n const { sessionIds, scopeHashes } = viewersOf(storeId, sessions);\n for (const sessionId of sessionIds) tell.session(sessionId, { ...data, sessionId });\n for (const scopeHash of scopeHashes) tell.scope(scopeHash, { ...data, scopeHash });\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 { linkedComments, sessionLinkedStoreIds } from '../comments/linked-stores.js';\nimport { readPendingForWorktree } 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 // As the Diff tab lists them: with those made on the browser diff page (linked-stores.ts).\n const comments = linkedComments(sessionLinkedStoreIds({ id: sessionId, paths: session.paths }));\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 // What the hooks will hand over: the session's and its scopes' (readPendingForWorktree), as the badges count.\n const pending = readPendingForWorktree(session, 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.jiraKey ?? null;\n}\n"],"mappings":";;;;;;;;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  } from "./chunk-ZSHWP2VS.js";
5
5
  import {
6
6
  getCommentFileStore,
7
- readStoreComments
8
- } from "./chunk-7HGABVGR.js";
7
+ readStoreComments,
8
+ readStoresComments
9
+ } from "./chunk-E3Y4ZACK.js";
9
10
  import {
10
11
  loadHistory
11
12
  } from "./chunk-OQAQMCHF.js";
@@ -95,21 +96,20 @@ function scopeStoreIdsForPaths(paths) {
95
96
  for (const p of resolved) ids.add(`scope-${scopeHashFor([p])}`);
96
97
  return [...ids];
97
98
  }
98
- function readPendingForWorktree(session) {
99
- const sessionId = sessionIdFor(session);
99
+ function readPendingForWorktree(session, sessionId = sessionIdFor(session)) {
100
100
  const delivered = withDb((d) => deliveredIds(d, sessionId));
101
101
  const pending = isPendingFor(delivered);
102
+ const storeIds = [sessionId, ...scopeStoreIdsForPaths(session.paths)];
103
+ const rows = readStoresComments(storeIds);
102
104
  const seen = /* @__PURE__ */ new Set();
103
105
  const out = [];
104
- const collect = (storeId) => {
105
- for (const c of readStoreComments(storeId)) {
106
+ for (const storeId of storeIds) {
107
+ for (const c of rows.get(storeId) ?? []) {
106
108
  if (seen.has(c.id) || !pending(c)) continue;
107
109
  seen.add(c.id);
108
110
  out.push(c);
109
111
  }
110
- };
111
- collect(sessionId);
112
- for (const storeId of scopeStoreIdsForPaths(session.paths)) collect(storeId);
112
+ }
113
113
  return out;
114
114
  }
115
115
  function resolveAddressed(session) {
@@ -200,9 +200,10 @@ export {
200
200
  findSessionForCwd,
201
201
  NOTE_NUDGE,
202
202
  readPendingForSession,
203
+ scopeStoreIdsForPaths,
203
204
  readPendingForWorktree,
204
205
  resolveAddressed,
205
206
  claimForDelivery,
206
207
  formatPendingForPrompt
207
208
  };
208
- //# sourceMappingURL=chunk-RG63ACAK.js.map
209
+ //# sourceMappingURL=chunk-PVN5IGDZ.js.map
@@ -0,0 +1 @@
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, readStoresComments } 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>`). */\nexport function 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, sessionId: string = sessionIdFor(session)): Comment[] {\n const delivered = withDb((d) => deliveredIds(d, sessionId));\n const pending = isPendingFor(delivered);\n const storeIds = [sessionId, ...scopeStoreIdsForPaths(session.paths)];\n const rows = readStoresComments(storeIds); // one query: this runs for every row of /api/sessions\n const seen = new Set<string>();\n const out: Comment[] = [];\n for (const storeId of storeIds) {\n for (const c of rows.get(storeId) ?? []) {\n if (seen.has(c.id) || !pending(c)) continue;\n seen.add(c.id);\n out.push(c);\n }\n }\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,OAAO,GAAG;AAChC,YAAM,IAAI,wBAAwB,KAAK,GAAG,aAAa,QAAQ,MAAM,CAAC;AACtE,UAAI,CAAC,EAAG,QAAO;AACf,eAAS,KAAK,QAAQ,UAAU,EAAE,CAAC,CAAC;AAAA,IACtC;AACA,WAAO,eAAe,GAAG,aAAa,KAAK,KAAK,QAAQ,MAAM,GAAG,MAAM,CAAC;AAAA,EAC1E,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,eAAe,MAA6B;AAC1D,QAAM,IAAI,kCAAkC,KAAK,IAAI;AACrD,SAAO,IAAI,EAAE,CAAC,IAAI;AACpB;;;ACZA,OAAOA,SAAQ;AACf,OAAOC,WAAU;AAQjB,SAAS,aAAa,GAAO,WAAgC;AAC3D,SAAO,IAAI;AAAA,IACR,EAAE,QAAQ,gEAAgE,EAAE,IAAI,SAAS,EAAoC;AAAA,MAC5H,CAAC,MAAM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,GAAG,kBAAkB,GAAG;AAClD,SACE,UACA;AAAA;AAAA,6DACG,QAAQ,MAAM;AAAA;AAGrB;AAEA,SAAS,WAAW,QAAgB,GAAoB;AACtD,QAAM,OAAO,EAAE,KAAK,MAAM,IAAI,EAAE,CAAC,EAAE,KAAK;AACxC,QAAM,SAAS,KAAK,SAAS,iBAAiB,GAAG,KAAK,MAAM,GAAG,cAAc,CAAC,WAAM;AACpF,SAAO,GAAG,MAAM,KAAK,MAAM,GAAG,EAAE,KAAK,SAAS,IAAI,IAAI,YAAO,EAAE;AACjE;AAKA,SAAS,eAAe,QAAgB,GAAoB;AAC1D,QAAM,OAAO,EAAE,KAAK,KAAK;AACzB,QAAM,SAAS,KAAK,SAAS,iBAAiB,GAAG,KAAK,MAAM,GAAG,cAAc,CAAC,WAAM;AACpF,QAAM,YAAY,OAAO,MAAM,IAAI;AACnC,MAAI,UAAU,WAAW,EAAG,QAAO,GAAG,MAAM,KAAK,UAAU,CAAC,CAAC;AAC7D,QAAM,CAAC,OAAO,GAAG,IAAI,IAAI;AACzB,SAAO,CAAC,GAAG,MAAM,KAAK,KAAK,IAAI,GAAG,KAAK,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC,EAAE,KAAK,IAAI;AACxE;","names":["fs","path","path","fs"]}
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/core/pty/restart-view.ts
4
+ var LATER_TEXT = "restarts when its turn ends";
5
+ function restartCountsText(c) {
6
+ const parts = [];
7
+ if (c.restarted) parts.push(`${c.restarted} session${c.restarted === 1 ? "" : "s"} restarted`);
8
+ if (c.later) parts.push(`${c.later} ${c.later === 1 ? LATER_TEXT : "restart when their turns end"}`);
9
+ if (c.failed) parts.push(`${c.failed} couldn't${c.firstError ? `: ${c.firstError}` : ""}`);
10
+ return parts.length ? `${parts.join(" \xB7 ")}.` : "Nothing to restart.";
11
+ }
12
+
13
+ export {
14
+ LATER_TEXT,
15
+ restartCountsText
16
+ };
17
+ //# sourceMappingURL=chunk-TNJF7T33.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/pty/restart-view.ts"],"sourcesContent":["/**\n * How a restart of agents is said (agent-restart.ts), the same in the dashboard,\n * the Activity panel and `work restart`. Pure: the SPA imports it.\n */\n\n/** What a session waiting for its turn is told it will do. */\nexport const LATER_TEXT = 'restarts when its turn ends';\n\n/** \"2 sessions restarted · 1 restarts when its turn ends · 1 couldn't: <why>.\" */\nexport function restartCountsText(c: { restarted: number; later: number; failed: number; firstError?: string }): string {\n const parts: string[] = [];\n if (c.restarted) parts.push(`${c.restarted} session${c.restarted === 1 ? '' : 's'} restarted`);\n if (c.later) parts.push(`${c.later} ${c.later === 1 ? LATER_TEXT : 'restart when their turns end'}`);\n if (c.failed) parts.push(`${c.failed} couldn't${c.firstError ? `: ${c.firstError}` : ''}`);\n return parts.length ? `${parts.join(' · ')}.` : 'Nothing to restart.';\n}\n"],"mappings":";;;AAMO,IAAM,aAAa;AAGnB,SAAS,kBAAkB,GAAsF;AACtH,QAAM,QAAkB,CAAC;AACzB,MAAI,EAAE,UAAW,OAAM,KAAK,GAAG,EAAE,SAAS,WAAW,EAAE,cAAc,IAAI,KAAK,GAAG,YAAY;AAC7F,MAAI,EAAE,MAAO,OAAM,KAAK,GAAG,EAAE,KAAK,IAAI,EAAE,UAAU,IAAI,aAAa,8BAA8B,EAAE;AACnG,MAAI,EAAE,OAAQ,OAAM,KAAK,GAAG,EAAE,MAAM,YAAY,EAAE,aAAa,KAAK,EAAE,UAAU,KAAK,EAAE,EAAE;AACzF,SAAO,MAAM,SAAS,GAAG,MAAM,KAAK,QAAK,CAAC,MAAM;AAClD;","names":[]}
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  isPersistedPty,
4
4
  ptySessionsPath
5
- } from "./chunk-ACXPSQJR.js";
5
+ } from "./chunk-MI3PS2SH.js";
6
6
  import {
7
7
  json,
8
8
  tx,
@@ -73,4 +73,4 @@ export {
73
73
  adoptLegacyRestoreList,
74
74
  forgetPersistedSession
75
75
  };
76
- //# sourceMappingURL=chunk-SRIYY5HL.js.map
76
+ //# sourceMappingURL=chunk-U4UB4LG6.js.map
@@ -6,32 +6,32 @@ import {
6
6
  deleteMergedBranches,
7
7
  findMergedBranches,
8
8
  scanBuildFolders
9
- } from "./chunk-D4FUDMMX.js";
9
+ } from "./chunk-FX4IA5U4.js";
10
10
  import {
11
11
  defaultCleanupDeps
12
- } from "./chunk-AFV5S6UV.js";
12
+ } from "./chunk-F375JY4M.js";
13
13
  import {
14
14
  timeAgo
15
15
  } from "./chunk-UQ35KLHH.js";
16
- import "./chunk-RMICESXA.js";
17
- import "./chunk-26IZBYVL.js";
16
+ import "./chunk-KUWFGPGW.js";
18
17
  import {
19
18
  applyCleanup,
20
19
  scanCleanup
21
20
  } from "./chunk-AKMPF72Y.js";
21
+ import "./chunk-26IZBYVL.js";
22
22
  import "./chunk-ZFPV46FA.js";
23
23
  import "./chunk-L6RUHCKB.js";
24
- import "./chunk-UAAH334K.js";
25
- import "./chunk-SRIYY5HL.js";
26
- import "./chunk-ACXPSQJR.js";
24
+ import "./chunk-7JPCVEOY.js";
25
+ import "./chunk-U4UB4LG6.js";
26
+ import "./chunk-MI3PS2SH.js";
27
27
  import "./chunk-427RB7E4.js";
28
28
  import "./chunk-R7B46WXN.js";
29
29
  import "./chunk-6O6765M7.js";
30
30
  import "./chunk-JTHILJFB.js";
31
31
  import "./chunk-3XY76XBD.js";
32
- import "./chunk-RG63ACAK.js";
32
+ import "./chunk-PVN5IGDZ.js";
33
33
  import "./chunk-ZSHWP2VS.js";
34
- import "./chunk-7HGABVGR.js";
34
+ import "./chunk-E3Y4ZACK.js";
35
35
  import "./chunk-HUXS3VAI.js";
36
36
  import "./chunk-5PAPD6VT.js";
37
37
  import "./chunk-4KZBZA5D.js";
@@ -191,4 +191,4 @@ var cleanupCommand = {
191
191
  export {
192
192
  cleanupCommand
193
193
  };
194
- //# sourceMappingURL=cleanup-OO3DCPGC.js.map
194
+ //# sourceMappingURL=cleanup-LRT6J36R.js.map
@@ -3,8 +3,8 @@ import {
3
3
  COMMANDS,
4
4
  commandsFor,
5
5
  run
6
- } from "./chunk-Y6VPABC3.js";
7
- import "./chunk-W5B4NLBI.js";
6
+ } from "./chunk-BSFL3WDR.js";
7
+ import "./chunk-4KNBN2OF.js";
8
8
  import "./chunk-JTHILJFB.js";
9
9
  import "./chunk-RKEY4573.js";
10
10
  import "./chunk-RCYI7SRA.js";
@@ -15,4 +15,4 @@ export {
15
15
  commandsFor,
16
16
  run
17
17
  };
18
- //# sourceMappingURL=cli-I6N4U4GN.js.map
18
+ //# sourceMappingURL=cli-VGUJI5WG.js.map
@@ -4,17 +4,17 @@ import {
4
4
  forkSession,
5
5
  startSessionWithPrompt,
6
6
  uncommittedFiles
7
- } from "./chunk-4PP27RI7.js";
7
+ } from "./chunk-7GQCPGKQ.js";
8
8
  import "./chunk-OW46TR4G.js";
9
9
  import {
10
10
  attachSession
11
- } from "./chunk-HBXDIRM4.js";
11
+ } from "./chunk-KSIXTTO6.js";
12
12
  import "./chunk-AH5TM3NB.js";
13
13
  import "./chunk-ZFPV46FA.js";
14
14
  import "./chunk-L6RUHCKB.js";
15
- import "./chunk-UAAH334K.js";
16
- import "./chunk-SRIYY5HL.js";
17
- import "./chunk-ACXPSQJR.js";
15
+ import "./chunk-7JPCVEOY.js";
16
+ import "./chunk-U4UB4LG6.js";
17
+ import "./chunk-MI3PS2SH.js";
18
18
  import {
19
19
  askCatchUp,
20
20
  catchUp,
@@ -26,9 +26,9 @@ import "./chunk-JTHILJFB.js";
26
26
  import "./chunk-3XY76XBD.js";
27
27
  import {
28
28
  findSessionForCwd
29
- } from "./chunk-RG63ACAK.js";
29
+ } from "./chunk-PVN5IGDZ.js";
30
30
  import "./chunk-ZSHWP2VS.js";
31
- import "./chunk-7HGABVGR.js";
31
+ import "./chunk-E3Y4ZACK.js";
32
32
  import "./chunk-HUXS3VAI.js";
33
33
  import "./chunk-5PAPD6VT.js";
34
34
  import "./chunk-4KZBZA5D.js";
@@ -120,4 +120,4 @@ var forkCommand = {
120
120
  export {
121
121
  forkCommand
122
122
  };
123
- //# sourceMappingURL=fork-WTNAUILU.js.map
123
+ //# sourceMappingURL=fork-RJ3ZPPWT.js.map