handmux 0.33.4 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/dist/build-meta.json +3 -3
  2. package/dist/package.json +13 -13
  3. package/dist/public/assets/{abnfDiagram-O67JEVCF-CTyexkYw.js → abnfDiagram-O67JEVCF-DslFDZId.js} +1 -1
  4. package/dist/public/assets/{arc-DdDiy07q.js → arc-VHB0ANPU.js} +1 -1
  5. package/dist/public/assets/{architectureDiagram-NJMV4G6O-Bot9hstQ.js → architectureDiagram-NJMV4G6O-CJcCA-5Z.js} +1 -1
  6. package/dist/public/assets/{blockDiagram-BEXU5L5S-W9XzhGdS.js → blockDiagram-BEXU5L5S-B01qZyZi.js} +1 -1
  7. package/dist/public/assets/{c4Diagram-YGBWAQC7-BAijt2HM.js → c4Diagram-YGBWAQC7-B3e2jVdt.js} +1 -1
  8. package/dist/public/assets/channel-YqF13omZ.js +1 -0
  9. package/dist/public/assets/{chunk-2Q5K7J3B-B2piJqsT.js → chunk-2Q5K7J3B-CES4ihJ2.js} +1 -1
  10. package/dist/public/assets/{chunk-3FUC2YCW-D3Sx9dKt.js → chunk-3FUC2YCW-Dma2vRtQ.js} +2 -2
  11. package/dist/public/assets/{chunk-5VM5RSS4-BUArEHwl.js → chunk-5VM5RSS4-BlpNsgH-.js} +1 -1
  12. package/dist/public/assets/{chunk-GTNCS2PH-CCbMJktB.js → chunk-GTNCS2PH-C2DhT6XM.js} +1 -1
  13. package/dist/public/assets/{chunk-GWA4HPMP-C6TuPRFq.js → chunk-GWA4HPMP-ye3iQ-a9.js} +1 -1
  14. package/dist/public/assets/{chunk-JWPE2WC7-aSSTyo6M.js → chunk-JWPE2WC7-Cpju1Ogm.js} +1 -1
  15. package/dist/public/assets/{chunk-NETBCI7D-CjU_M6rV.js → chunk-NETBCI7D-oNkGN9hx.js} +1 -1
  16. package/dist/public/assets/{chunk-WEXAMYUT-DoGrOfJC.js → chunk-WEXAMYUT-Bz2dLsEF.js} +1 -1
  17. package/dist/public/assets/{chunk-XXDRQBXY-DsVaYCaN.js → chunk-XXDRQBXY-CfnAOHJH.js} +1 -1
  18. package/dist/public/assets/{classDiagram-v2-NBCMYWYE-DY7FiJEP.js → classDiagram-v2-NBCMYWYE-CtEVnXTP.js} +1 -1
  19. package/dist/public/assets/{cose-bilkent-JH36ORCC-BXxbe0fb.js → cose-bilkent-JH36ORCC-CZI_xbWv.js} +1 -1
  20. package/dist/public/assets/{cynefin-OW5HDTMX-CCDWLi08.js → cynefin-OW5HDTMX-jKUkt7bh.js} +1 -1
  21. package/dist/public/assets/{cynefinDiagram-VND7K2PF-DZqqidYi.js → cynefinDiagram-VND7K2PF-DpOr06tv.js} +1 -1
  22. package/dist/public/assets/{dagre-6A5THRUB-mnFkYCPJ.js → dagre-6A5THRUB-Cp42nnjs.js} +1 -1
  23. package/dist/public/assets/{diagram-22UHCM2B-24J1jkjw.js → diagram-22UHCM2B-B4vh59kK.js} +1 -1
  24. package/dist/public/assets/{diagram-3UASUU5V-BjrIrnar.js → diagram-3UASUU5V-BrySHBW5.js} +1 -1
  25. package/dist/public/assets/{diagram-ATOU4E4O-Z1JX3sq5.js → diagram-ATOU4E4O-CRDLRjJK.js} +1 -1
  26. package/dist/public/assets/{diagram-CDSNMT55-C_prd06u.js → diagram-CDSNMT55-D_zXyS0J.js} +1 -1
  27. package/dist/public/assets/{diagram-MLGK6HIB-D9mjfvWc.js → diagram-MLGK6HIB-D9Q6Ol7F.js} +1 -1
  28. package/dist/public/assets/{diagram-MPIPVDR6-Dk23DnyI.js → diagram-MPIPVDR6-D_L7q2cj.js} +1 -1
  29. package/dist/public/assets/{ebnfDiagram-ZINNZB2B-BFAi_SN0.js → ebnfDiagram-ZINNZB2B-C9AymNC4.js} +1 -1
  30. package/dist/public/assets/{elk-276RUBZZ-85AZyxvX.js → elk-276RUBZZ-qj6gPVW5.js} +1 -1
  31. package/dist/public/assets/{erDiagram-OPXOYQCR-DGK2YMJn.js → erDiagram-OPXOYQCR-DXHbm2-3.js} +1 -1
  32. package/dist/public/assets/{flowDiagram-KWPJA3E3-AbELUL1s.js → flowDiagram-KWPJA3E3-CytiY7My.js} +1 -1
  33. package/dist/public/assets/{ganttDiagram-FUAMR5RP-D4EwkrB-.js → ganttDiagram-FUAMR5RP-XIXk3178.js} +1 -1
  34. package/dist/public/assets/{gitGraphDiagram-X574FWY7-SuIg9MNn.js → gitGraphDiagram-X574FWY7-2-Iaumi6.js} +1 -1
  35. package/dist/public/assets/index-B02FNbyq.css +32 -0
  36. package/dist/public/assets/index-BQp0V5lU.js +363 -0
  37. package/dist/public/assets/{infoDiagram-VRGFBTTK-USYiLU2N.js → infoDiagram-VRGFBTTK-rDrzVo_U.js} +1 -1
  38. package/dist/public/assets/{ishikawaDiagram-OU5B5YK6-DKl1cwGt.js → ishikawaDiagram-OU5B5YK6-D59KH_M6.js} +1 -1
  39. package/dist/public/assets/{journeyDiagram-ZHPQQLJL-DA6WJWzc.js → journeyDiagram-ZHPQQLJL-15Csh4-7.js} +1 -1
  40. package/dist/public/assets/{kanban-definition-PNTS6WVX-CHwoeiSV.js → kanban-definition-PNTS6WVX-DJt5zKPb.js} +1 -1
  41. package/dist/public/assets/{linear-CrX1doCP.js → linear-C_7B3tLp.js} +1 -1
  42. package/dist/public/assets/{mermaid.core-DycEQHIJ.js → mermaid.core-CUCURRF9.js} +4 -4
  43. package/dist/public/assets/{mindmap-definition-NLK3R4M7-CYZkgL2m.js → mindmap-definition-NLK3R4M7-DgHHfDE2.js} +1 -1
  44. package/dist/public/assets/{pegDiagram-GJSIUBJH-CLBKPdy7.js → pegDiagram-GJSIUBJH-Co8vXpQN.js} +1 -1
  45. package/dist/public/assets/{pieDiagram-5QR66LMP-fqgZKq3d.js → pieDiagram-5QR66LMP-D2-jPmQz.js} +1 -1
  46. package/dist/public/assets/{quadrantDiagram-O4NWA36T-Dpz9EdzN.js → quadrantDiagram-O4NWA36T-C01SNg0F.js} +1 -1
  47. package/dist/public/assets/{railroadDiagram-XR7U4H2S-CrjZ98Io.js → railroadDiagram-XR7U4H2S-CpOHUJjS.js} +1 -1
  48. package/dist/public/assets/{requirementDiagram-PLB6GJNP-3uFiTOPz.js → requirementDiagram-PLB6GJNP-MnTTEaJ8.js} +1 -1
  49. package/dist/public/assets/{sankeyDiagram-IPEJSGJF-BB4xiA5r.js → sankeyDiagram-IPEJSGJF-Drj8CpKl.js} +1 -1
  50. package/dist/public/assets/{sequenceDiagram-PO4LG4MO-CSV5btYj.js → sequenceDiagram-PO4LG4MO-BKIZBej_.js} +1 -1
  51. package/dist/public/assets/{sizeCapture-INFHLROL-CZM8lmXs.js → sizeCapture-INFHLROL-CA7QSTT6.js} +1 -1
  52. package/dist/public/assets/{stateDiagram-v2-GCMORJYK-CQMNaqRS.js → stateDiagram-v2-GCMORJYK-B5YaO32m.js} +1 -1
  53. package/dist/public/assets/{swimlanes-2SLR337P-D4XoDXeX.js → swimlanes-2SLR337P-Dp--9D-W.js} +1 -1
  54. package/dist/public/assets/swimlanesDiagram-TC7HE7FX-Du4bBHEh.js +8 -0
  55. package/dist/public/assets/{timeline-definition-EJHVYXUP-8vN31GK-.js → timeline-definition-EJHVYXUP-DxFkKZze.js} +1 -1
  56. package/dist/public/assets/{usecaseDiagram-POWQR4AR-DV8aZbyi.js → usecaseDiagram-POWQR4AR-wUt5OSw0.js} +1 -1
  57. package/dist/public/assets/{vennDiagram-UO4OBE2U-CzhdJPaP.js → vennDiagram-UO4OBE2U-DrXq2XMh.js} +1 -1
  58. package/dist/public/assets/{wardleyDiagram-VNRHLVJA-Br_J8zgL.js → wardleyDiagram-VNRHLVJA-DWqL4bqf.js} +1 -1
  59. package/dist/public/assets/{xychartDiagram-PMCCYNJV-DV4_m3f4.js → xychartDiagram-PMCCYNJV-BkZqHOc6.js} +1 -1
  60. package/dist/public/index.html +2 -2
  61. package/dist/src/agent-runtime/adapter.js +1 -1
  62. package/dist/src/agent-runtime/builtinRuntime.js +40 -2
  63. package/dist/src/agent-runtime/conversation.js +95 -7
  64. package/dist/src/agent-runtime/conversationRestart.js +201 -0
  65. package/dist/src/agent-runtime/inbox.js +37 -6
  66. package/dist/src/agent-runtime/runtime.js +35 -2
  67. package/dist/src/agent-runtime/tmuxRuntime.js +86 -4
  68. package/dist/src/agents/codex.js +1 -0
  69. package/dist/src/agents/codexConversation.js +66 -56
  70. package/dist/src/agents/codexConversationRestart.js +655 -0
  71. package/dist/src/agents/codexRestartReceipt.js +243 -0
  72. package/dist/src/agents/nativeInbox.js +29 -10
  73. package/dist/src/agents/nativeInboxSources.js +9 -3
  74. package/dist/src/apiAccountProviders.js +2 -2
  75. package/dist/src/cli/tunlite.js +14 -4
  76. package/dist/src/routes/agents.js +71 -0
  77. package/dist/src/routes/terminal.js +10 -3
  78. package/dist/src/server.js +12 -0
  79. package/dist/src/tmux/commands.js +16 -6
  80. package/dist/src/tmux/format.js +19 -3
  81. package/dist/src/workspace/tmuxAdapter.js +30 -0
  82. package/package.json +4 -4
  83. package/dist/public/assets/channel-CKSNhfVj.js +0 -1
  84. package/dist/public/assets/index-1-G2JyaA.js +0 -363
  85. package/dist/public/assets/index-CCO6YrGs.css +0 -32
  86. package/dist/public/assets/swimlanesDiagram-TC7HE7FX-aOhW9PVk.js +0 -8
@@ -0,0 +1,243 @@
1
+ import crypto from 'node:crypto';
2
+ import path from 'node:path';
3
+ import { fsyncDirectorySync, PrivateStateStore } from '../privateStateStore.js';
4
+ import { isSessionUuid } from './scanUtils.js';
5
+ const CODEX_AGENT_ID = 'codex';
6
+ const MAX_RECEIPTS = 128;
7
+ const OPERATION_ID_RE = /^[0-9a-f]{64}$/;
8
+ const PANE_ID_RE = /^%\d+$/;
9
+ const WINDOW_ID_RE = /^@\d+$/;
10
+ function isRecord(value) {
11
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
12
+ }
13
+ function validProcess(value) {
14
+ if (!isRecord(value))
15
+ return false;
16
+ return Number.isSafeInteger(value.pid) && Number(value.pid) > 0
17
+ && Number.isSafeInteger(value.ppid) && Number(value.ppid) >= 0
18
+ && Number.isSafeInteger(value.startedAt) && Number(value.startedAt) > 0
19
+ && typeof value.tty === 'string' && value.tty.length > 0 && value.tty.length <= 1_024
20
+ && typeof value.executable === 'string' && value.executable.length > 0 && value.executable.length <= 8_192;
21
+ }
22
+ function validReceipt(value) {
23
+ if (!isRecord(value) || !isRecord(value.pane) || !isRecord(value.process))
24
+ return false;
25
+ const pane = value.pane;
26
+ const process = value.process;
27
+ return typeof value.operationId === 'string' && OPERATION_ID_RE.test(value.operationId)
28
+ && value.agentId === CODEX_AGENT_ID
29
+ && typeof pane.paneId === 'string' && PANE_ID_RE.test(pane.paneId)
30
+ && typeof pane.sessionName === 'string' && pane.sessionName.length > 0 && pane.sessionName.length <= 1_024
31
+ && typeof pane.windowId === 'string' && WINDOW_ID_RE.test(pane.windowId)
32
+ && typeof pane.tty === 'string' && pane.tty.length > 0 && pane.tty.length <= 1_024
33
+ && typeof pane.tmuxEpoch === 'string' && pane.tmuxEpoch.length > 0 && pane.tmuxEpoch.length <= 1_024
34
+ && validProcess(process.tui) && validProcess(process.wrapper)
35
+ && (process.tuiShim === undefined
36
+ ? process.tui.ppid === process.wrapper.pid
37
+ : (validProcess(process.tuiShim) && process.tuiShim.ppid === process.wrapper.pid
38
+ && process.tui.ppid === process.tuiShim.pid))
39
+ && (process.appServer === undefined
40
+ || (validProcess(process.appServer) && (process.appServerShim === undefined
41
+ ? process.appServer.ppid === process.wrapper.pid
42
+ : (validProcess(process.appServerShim) && process.appServerShim.ppid === process.wrapper.pid
43
+ && process.appServer.ppid === process.appServerShim.pid))))
44
+ && (process.appServerShim === undefined || process.appServer !== undefined)
45
+ && typeof value.sessionId === 'string' && isSessionUuid(value.sessionId)
46
+ && typeof value.previousRunId === 'string' && value.previousRunId.length > 0 && value.previousRunId.length <= 1_024
47
+ && value.command === `handmux codex resume ${value.sessionId}`
48
+ && (value.phase === 'prepared' || value.phase === 'stopped'
49
+ || value.phase === 'resuming' || value.phase === 'ready')
50
+ && Number.isSafeInteger(value.createdAt) && Number(value.createdAt) > 0
51
+ && Number.isSafeInteger(value.updatedAt) && Number(value.updatedAt) >= Number(value.createdAt);
52
+ }
53
+ function persistedReceipt(receipt) {
54
+ return {
55
+ operationId: receipt.operationId,
56
+ agentId: CODEX_AGENT_ID,
57
+ pane: {
58
+ paneId: receipt.pane.paneId,
59
+ sessionName: receipt.pane.sessionName,
60
+ windowId: receipt.pane.windowId,
61
+ tty: receipt.pane.tty,
62
+ tmuxEpoch: receipt.pane.tmuxEpoch,
63
+ },
64
+ process: {
65
+ tui: persistedProcessIdentity(receipt.process.tui),
66
+ wrapper: persistedProcessIdentity(receipt.process.wrapper),
67
+ ...(receipt.process.tuiShim
68
+ ? { tuiShim: persistedProcessIdentity(receipt.process.tuiShim) } : {}),
69
+ ...(receipt.process.appServerShim
70
+ ? { appServerShim: persistedProcessIdentity(receipt.process.appServerShim) } : {}),
71
+ ...(receipt.process.appServer
72
+ ? { appServer: persistedProcessIdentity(receipt.process.appServer) }
73
+ : {}),
74
+ },
75
+ sessionId: receipt.sessionId,
76
+ previousRunId: receipt.previousRunId,
77
+ command: receipt.command,
78
+ phase: receipt.phase,
79
+ createdAt: receipt.createdAt,
80
+ updatedAt: receipt.updatedAt,
81
+ };
82
+ }
83
+ function parseState(value) {
84
+ if (value === null)
85
+ return { version: 1, receipts: [] };
86
+ if (!isRecord(value) || value.version !== 1 || !Array.isArray(value.receipts)
87
+ || value.receipts.length > MAX_RECEIPTS || !value.receipts.every(validReceipt)) {
88
+ throw new Error('Invalid Codex conversation restart state');
89
+ }
90
+ return { version: 1, receipts: value.receipts.map(persistedReceipt) };
91
+ }
92
+ function operationId(input) {
93
+ const stableInput = {
94
+ pane: input.pane,
95
+ process: {
96
+ tui: persistedProcessIdentity(input.process.tui),
97
+ wrapper: persistedProcessIdentity(input.process.wrapper),
98
+ ...(input.process.tuiShim ? { tuiShim: persistedProcessIdentity(input.process.tuiShim) } : {}),
99
+ ...(input.process.appServerShim ? { appServerShim: persistedProcessIdentity(input.process.appServerShim) } : {}),
100
+ appServer: persistedProcessIdentity(input.process.appServer),
101
+ },
102
+ sessionId: input.sessionId,
103
+ previousRunId: input.previousRunId,
104
+ };
105
+ return crypto.createHash('sha256').update(JSON.stringify({ agentId: CODEX_AGENT_ID, ...stableInput })).digest('hex');
106
+ }
107
+ function persistedProcessIdentity(identity) {
108
+ return {
109
+ pid: identity.pid,
110
+ ppid: identity.ppid,
111
+ startedAt: identity.startedAt,
112
+ tty: identity.tty,
113
+ executable: identity.executable,
114
+ };
115
+ }
116
+ function persistedInput(input) {
117
+ return {
118
+ pane: structuredClone(input.pane),
119
+ process: {
120
+ tui: persistedProcessIdentity(input.process.tui),
121
+ wrapper: persistedProcessIdentity(input.process.wrapper),
122
+ ...(input.process.tuiShim ? { tuiShim: persistedProcessIdentity(input.process.tuiShim) } : {}),
123
+ ...(input.process.appServerShim ? { appServerShim: persistedProcessIdentity(input.process.appServerShim) } : {}),
124
+ appServer: persistedProcessIdentity(input.process.appServer),
125
+ },
126
+ sessionId: input.sessionId,
127
+ previousRunId: input.previousRunId,
128
+ };
129
+ }
130
+ export class CodexRestartReceiptStore {
131
+ #store;
132
+ #now;
133
+ #write;
134
+ #fsyncDirectory;
135
+ #state;
136
+ #available = true;
137
+ constructor(file, { now = Date.now, write, fsyncDirectory = fsyncDirectorySync, } = {}) {
138
+ this.#store = new PrivateStateStore(file);
139
+ this.#now = now;
140
+ this.#write = write ?? ((state) => this.#store.write(state));
141
+ this.#fsyncDirectory = fsyncDirectory;
142
+ try {
143
+ const raw = this.#store.readStrict();
144
+ this.#state = parseState(raw);
145
+ if (raw !== null && JSON.stringify(raw) !== JSON.stringify(this.#state))
146
+ this.#flush(this.#state);
147
+ }
148
+ catch {
149
+ this.#state = { version: 1, receipts: [] };
150
+ this.#available = false;
151
+ }
152
+ }
153
+ list() {
154
+ this.#assertAvailable();
155
+ return structuredClone(this.#state.receipts);
156
+ }
157
+ latestForPane(paneId) {
158
+ this.#assertAvailable();
159
+ return structuredClone([...this.#state.receipts].reverse().find((receipt) => (receipt.pane.paneId === paneId)) ?? null);
160
+ }
161
+ get(operationId) {
162
+ this.#assertAvailable();
163
+ return structuredClone(this.#state.receipts.find((receipt) => receipt.operationId === operationId) ?? null);
164
+ }
165
+ isPending(agentId, sessionId) {
166
+ if (agentId !== CODEX_AGENT_ID)
167
+ return false;
168
+ this.#assertAvailable();
169
+ return this.#state.receipts.some((receipt) => (receipt.sessionId === sessionId && receipt.phase !== 'ready'));
170
+ }
171
+ prepare(input) {
172
+ this.#assertAvailable();
173
+ const id = operationId(input);
174
+ const existing = this.#state.receipts.find((receipt) => receipt.operationId === id);
175
+ if (existing)
176
+ return structuredClone(existing);
177
+ const now = Math.trunc(this.#now());
178
+ const receipt = {
179
+ operationId: id,
180
+ agentId: CODEX_AGENT_ID,
181
+ ...persistedInput(input),
182
+ command: `handmux codex resume ${input.sessionId}`,
183
+ phase: 'prepared',
184
+ createdAt: now,
185
+ updatedAt: now,
186
+ };
187
+ if (!validReceipt(receipt))
188
+ throw new Error('Invalid Codex conversation restart receipt');
189
+ const pending = this.#state.receipts.filter((candidate) => candidate.phase !== 'ready');
190
+ if (pending.length >= MAX_RECEIPTS)
191
+ throw new Error('Too many pending Codex conversation restarts');
192
+ const history = [...this.#state.receipts, receipt];
193
+ const readyCapacity = MAX_RECEIPTS - history.filter((candidate) => candidate.phase !== 'ready').length;
194
+ const completed = history.filter((candidate) => candidate.phase === 'ready');
195
+ const readyIds = new Set((readyCapacity > 0 ? completed.slice(-readyCapacity) : [])
196
+ .map((candidate) => candidate.operationId));
197
+ const next = {
198
+ version: 1,
199
+ receipts: history.filter((candidate) => candidate.phase !== 'ready' || readyIds.has(candidate.operationId)),
200
+ };
201
+ this.#flush(next);
202
+ this.#state = next;
203
+ return structuredClone(receipt);
204
+ }
205
+ transition(id, expected, phase) {
206
+ this.#assertAvailable();
207
+ const index = this.#state.receipts.findIndex((candidate) => candidate.operationId === id);
208
+ const receipt = this.#state.receipts[index];
209
+ const allowed = Array.isArray(expected) ? expected : [expected];
210
+ if (!receipt || !allowed.includes(receipt.phase))
211
+ throw new Error('Codex restart receipt changed');
212
+ if (receipt.phase === phase)
213
+ return structuredClone(receipt);
214
+ const updated = { ...receipt, phase, updatedAt: Math.trunc(this.#now()) };
215
+ if (!validReceipt(updated))
216
+ throw new Error('Invalid Codex conversation restart transition');
217
+ const next = {
218
+ version: 1,
219
+ receipts: this.#state.receipts.map((candidate, candidateIndex) => (candidateIndex === index ? updated : candidate)),
220
+ };
221
+ this.#flush(next);
222
+ this.#state = next;
223
+ return structuredClone(updated);
224
+ }
225
+ clear(id) {
226
+ this.#assertAvailable();
227
+ const receipts = this.#state.receipts.filter((receipt) => receipt.operationId !== id);
228
+ if (receipts.length === this.#state.receipts.length)
229
+ return false;
230
+ const next = { version: 1, receipts };
231
+ this.#flush(next);
232
+ this.#state = next;
233
+ return true;
234
+ }
235
+ #flush(next) {
236
+ this.#write(next);
237
+ this.#fsyncDirectory(path.dirname(this.#store.file));
238
+ }
239
+ #assertAvailable() {
240
+ if (!this.#available)
241
+ throw new Error('Codex conversation restart state is unavailable');
242
+ }
243
+ }
@@ -21,8 +21,9 @@ function baseline(sourceId, tracked) {
21
21
  run: tracked.lease.ref,
22
22
  source: { sourceId, cursor: row.cursor },
23
23
  state: row.state,
24
- ...(row.message === undefined ? {} : { message: row.message }),
25
- ...(row.reason === undefined ? {} : { reason: row.reason }),
24
+ // Keep the baseline receipt identical to the live full-value operation, including explicit clears.
25
+ message: row.message ?? null,
26
+ reason: row.reason ?? null,
26
27
  ...(row.correlationId === undefined ? {} : { correlationId: row.correlationId }),
27
28
  ...(row.eventId === undefined ? {} : { eventId: row.eventId }),
28
29
  ...(row.sourceOccurredAt === undefined ? {} : { sourceOccurredAt: row.sourceOccurredAt }),
@@ -53,6 +54,7 @@ export class NativeInboxCoordinator {
53
54
  #baselineReady = false;
54
55
  #availability;
55
56
  #availabilityMessage;
57
+ #projectionError;
56
58
  constructor({ agentId, sourceId, context, source, pollMs = 500, }) {
57
59
  if (!agentId || !sourceId || !context || !source || typeof source.read !== 'function'
58
60
  || !Number.isSafeInteger(pollMs) || pollMs < 100) {
@@ -194,12 +196,12 @@ export class NativeInboxCoordinator {
194
196
  associationError ??= error instanceof Error ? error.message : String(error);
195
197
  }
196
198
  }
197
- const effectiveAvailability = associationError ? 'degraded' : snapshot.availability;
198
- const effectiveMessage = associationError ?? snapshot.message;
199
+ let effectiveAvailability = associationError || this.#projectionError ? 'degraded' : snapshot.availability;
200
+ let effectiveMessage = associationError ?? this.#projectionError ?? snapshot.message;
199
201
  const availabilityChanged = this.#availability !== effectiveAvailability
200
202
  || this.#availabilityMessage !== effectiveMessage;
201
203
  const restoreNeeded = topologyChanged || availabilityChanged;
202
- if (restoreNeeded) {
204
+ const restore = async () => {
203
205
  const baselines = [...this.#tracked.values()].flatMap((tracked) => {
204
206
  const value = baseline(this.#sourceId, tracked);
205
207
  return value ? [value] : [];
@@ -210,17 +212,34 @@ export class NativeInboxCoordinator {
210
212
  ...(effectiveMessage === undefined ? {} : { message: effectiveMessage }),
211
213
  });
212
214
  this.#baselineReady = true;
213
- }
215
+ };
216
+ if (restoreNeeded)
217
+ await restore();
218
+ let projectionError;
214
219
  for (const row of rows.values()) {
215
220
  const tracked = this.#tracked.get(row.paneId);
216
221
  if (tracked.row.cursor === row.cursor)
217
222
  continue;
218
- const result = await tracked.projector.submit(operation(this.#sourceId, row));
219
- if (!result.accepted && result.reason !== 'duplicate_source' && result.reason !== 'duplicate_event') {
220
- throw new Error(`${this.#agentId} Inbox projection failed: ${result.reason ?? 'unknown'}`);
223
+ try {
224
+ const result = await tracked.projector.submit(operation(this.#sourceId, row));
225
+ if (!result.accepted) {
226
+ projectionError ??= `${this.#agentId} Inbox projection failed for ${row.paneId}: ${result.reason ?? 'unknown'}`;
227
+ continue;
228
+ }
229
+ tracked.row = row;
230
+ }
231
+ catch {
232
+ projectionError ??= `${this.#agentId} Inbox projection failed for ${row.paneId}: submission_failed`;
221
233
  }
222
- tracked.row = row;
223
234
  }
235
+ const nextAvailability = associationError || projectionError ? 'degraded' : snapshot.availability;
236
+ const nextMessage = associationError ?? projectionError ?? snapshot.message;
237
+ if (nextAvailability !== effectiveAvailability || nextMessage !== effectiveMessage) {
238
+ effectiveAvailability = nextAvailability;
239
+ effectiveMessage = nextMessage;
240
+ await restore();
241
+ }
242
+ this.#projectionError = projectionError;
224
243
  this.#availability = effectiveAvailability;
225
244
  this.#availabilityMessage = effectiveMessage;
226
245
  this.#context.health.report({
@@ -28,6 +28,7 @@ function canonical(kind) {
28
28
  function stableId(agentId, paneId, sessionId, state) {
29
29
  return `${agentId}:${createHash('sha256').update(JSON.stringify({
30
30
  paneId, sessionId, kind: state.kind, msg: state.msg ?? '', ts: state.ts ?? 0,
31
+ ...(state.correlationId === undefined ? {} : { correlationId: state.correlationId }),
31
32
  })).digest('hex')}`;
32
33
  }
33
34
  function row(agentId, paneId, sessionId, value) {
@@ -35,7 +36,13 @@ function row(agentId, paneId, sessionId, value) {
35
36
  if (state === 'ignore')
36
37
  return null;
37
38
  const message = inboxMessage(value.msg);
38
- const normalized = { ...value, ...(message === undefined ? { msg: '' } : { msg: message }) };
39
+ const correlationId = value.correlationId && value.correlationId.length <= 256
40
+ ? value.correlationId : undefined;
41
+ const normalized = { ...value, msg: message ?? '' };
42
+ if (correlationId === undefined)
43
+ delete normalized.correlationId;
44
+ else
45
+ normalized.correlationId = correlationId;
39
46
  const identity = stableId(agentId, paneId, sessionId, normalized);
40
47
  const terminal = state === 'waiting' || state === 'done' || state === 'error';
41
48
  return {
@@ -44,8 +51,7 @@ function row(agentId, paneId, sessionId, value) {
44
51
  cursor: identity,
45
52
  state,
46
53
  ...(message === undefined ? {} : { message }),
47
- ...(value.correlationId && value.correlationId.length <= 256
48
- ? { correlationId: value.correlationId } : {}),
54
+ ...(correlationId === undefined ? {} : { correlationId }),
49
55
  ...(terminal ? { eventId: identity } : {}),
50
56
  ...(typeof value.ts === 'number' && Number.isFinite(value.ts)
51
57
  ? { sourceOccurredAt: value.ts } : {}),
@@ -71,7 +71,7 @@ function parseDeepSeekBalance(value) {
71
71
  || typeof candidate.currency !== 'string'
72
72
  || candidate.currency.length < 1 || candidate.currency.length > 32
73
73
  || !decimalString(candidate.total_balance, true)
74
- || !decimalString(candidate.topped_up_balance)
74
+ || !decimalString(candidate.topped_up_balance, true)
75
75
  || !decimalString(candidate.granted_balance)) {
76
76
  throw new ProviderQueryError('unsupported_response');
77
77
  }
@@ -161,7 +161,7 @@ function validDeepSeekResult(value) {
161
161
  && value.balances.every((balance) => isRecord(balance)
162
162
  && hasExactKeys(balance, ['currency', 'totalBalance', 'toppedUpBalance', 'grantedBalance'])
163
163
  && typeof balance.currency === 'string' && balance.currency.length >= 1 && balance.currency.length <= 32
164
- && decimalString(balance.totalBalance, true) && decimalString(balance.toppedUpBalance)
164
+ && decimalString(balance.totalBalance, true) && decimalString(balance.toppedUpBalance, true)
165
165
  && decimalString(balance.grantedBalance));
166
166
  }
167
167
  function validMoonshotResult(value) {
@@ -2,13 +2,23 @@
2
2
  // npm dependency of handmux, so the bundled node_modules/.bin/tunlite means users need no separate install.
3
3
  // `run`/`exists` injectable so the pure resolution logic unit-tests without spawning.
4
4
  import fs from 'node:fs';
5
+ import { createRequire } from 'node:module';
5
6
  import path from 'node:path';
6
7
  import { spawnSync } from 'node:child_process';
7
- import { fileURLToPath } from 'node:url';
8
- const here = path.dirname(fileURLToPath(import.meta.url));
9
- const BUNDLED = path.resolve(here, '../../node_modules/.bin/tunlite');
8
+ const require = createRequire(import.meta.url);
9
+ const BUNDLED = (() => {
10
+ try {
11
+ // Resolve the package entry first: relative paths from src/cli point at the package root, but the
12
+ // compiled module lives one level deeper under dist/src/cli and would otherwise miss node_modules.
13
+ const entry = require.resolve('tunlite/bin/tunlite.js');
14
+ return path.resolve(path.dirname(entry), '../../.bin/tunlite');
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ })();
10
20
  export function resolveTunlite({ run = spawnSync, exists = fs.existsSync, bundled = BUNDLED, } = {}) {
11
- const candidate = exists(bundled) ? bundled : 'tunlite';
21
+ const candidate = bundled && exists(bundled) ? bundled : 'tunlite';
12
22
  const r = run(candidate, ['--version'], { encoding: 'utf8' });
13
23
  if (r && r.status === 0)
14
24
  return candidate;
@@ -2,6 +2,7 @@ import express from 'express';
2
2
  import { ConversationContractError } from '../agent-runtime/conversation.js';
3
3
  import { ConversationActivationError } from '../agent-runtime/conversationActivation.js';
4
4
  import { ConversationControlError } from '../agent-runtime/conversationControls.js';
5
+ import { ConversationRestartError } from '../agent-runtime/conversationRestart.js';
5
6
  import { ConversationLiveHub, ConversationLiveHubError, } from '../agent-runtime/conversationLiveHub.js';
6
7
  import { InteractionContractError } from '../agent-runtime/interaction.js';
7
8
  import { InteractionLiveHub, InteractionLiveHubError, } from '../agent-runtime/interactionLiveHub.js';
@@ -167,6 +168,76 @@ export function agentRoutes({ runtime }) {
167
168
  });
168
169
  return true;
169
170
  };
171
+ const conversationRestartError = (error, res) => {
172
+ if (!(error instanceof ConversationRestartError))
173
+ return false;
174
+ const status = error.code === 'unavailable' ? 503 : 409;
175
+ res.status(status).json({
176
+ error: error.message,
177
+ code: error.code,
178
+ ...(error.recovery === undefined ? {} : { recovery: error.recovery }),
179
+ });
180
+ return true;
181
+ };
182
+ router.post('/agents/conversation-restart', async (req, res, next) => {
183
+ try {
184
+ if (!runtime.conversationRestart) {
185
+ return res.status(409).json({ error: 'conversation restart unsupported', code: 'unsupported' });
186
+ }
187
+ const ref = run(req.body?.run);
188
+ if (!ref || !text(ref.sessionId, 1024)) {
189
+ return res.status(400).json({ error: 'invalid agent run' });
190
+ }
191
+ const lease = runtime.runs.resolve(ref);
192
+ if (!lease)
193
+ return res.status(409).json({ error: 'stale agent run', code: 'stale_run' });
194
+ // The user has confirmed the restart. Keep the bounded server-side operation alive if the browser
195
+ // navigates away or loses its connection; only the service's own hard timeout aborts its controller.
196
+ const receipt = await runtime.conversationRestart.restart(lease);
197
+ return res.json({ receipt });
198
+ }
199
+ catch (error) {
200
+ if (conversationRestartError(error, res))
201
+ return;
202
+ return next(error);
203
+ }
204
+ });
205
+ router.get('/agents/conversation-restart-recovery', async (req, res, next) => {
206
+ try {
207
+ if (!runtime.conversationRestart) {
208
+ return res.status(409).json({ error: 'conversation restart unsupported', code: 'unsupported' });
209
+ }
210
+ const paneId = typeof req.query.paneId === 'string' ? req.query.paneId : '';
211
+ if (!/^%\d+$/.test(paneId)) {
212
+ return res.status(400).json({ error: 'invalid conversation recovery pane' });
213
+ }
214
+ return res.json({ receipt: await runtime.conversationRestart.recovery(paneId) });
215
+ }
216
+ catch (error) {
217
+ if (conversationRestartError(error, res))
218
+ return;
219
+ return next(error);
220
+ }
221
+ });
222
+ router.post('/agents/conversation-restart-recovery', async (req, res, next) => {
223
+ try {
224
+ if (!runtime.conversationRestart) {
225
+ return res.status(409).json({ error: 'conversation restart unsupported', code: 'unsupported' });
226
+ }
227
+ const paneId = typeof req.body?.paneId === 'string' ? req.body.paneId : '';
228
+ const operationId = typeof req.body?.operationId === 'string' ? req.body.operationId : '';
229
+ if (!/^%\d+$/.test(paneId) || !/^[0-9a-f]{64}$/.test(operationId)) {
230
+ return res.status(400).json({ error: 'invalid conversation recovery request' });
231
+ }
232
+ const receipt = await runtime.conversationRestart.recover(paneId, operationId);
233
+ return res.json({ receipt });
234
+ }
235
+ catch (error) {
236
+ if (conversationRestartError(error, res))
237
+ return;
238
+ return next(error);
239
+ }
240
+ });
170
241
  router.get('/agents/conversation-activation', async (req, res, next) => {
171
242
  try {
172
243
  if (!runtime.conversationActivation) {
@@ -171,7 +171,7 @@ export function terminalRoutes({ commands }) {
171
171
  });
172
172
  r.post('/resize', async (req, res, next) => {
173
173
  const { window, pane, cols, rows, auto, layout } = requestBody(req);
174
- const c = Math.min(Math.max(Number(cols) || 0, 20), 500);
174
+ const c = cols != null ? Math.min(Math.max(Number(cols) || 0, 20), 500) : null;
175
175
  try {
176
176
  if (auto) {
177
177
  if (!isWindowId(window))
@@ -183,11 +183,18 @@ export function terminalRoutes({ commands }) {
183
183
  await commands.restoreWindowSize(window);
184
184
  }
185
185
  else if (isPaneId(pane)) {
186
- await commands.resizePane(pane, c); // a pane in a split — resize only it
186
+ const hasCols = cols != null;
187
+ const hasRows = rows != null;
188
+ if (!hasCols && !hasRows)
189
+ return res.status(400).json({ error: 'bad pane size' });
190
+ const r = hasRows ? Math.min(Math.max(Number(rows) || 0, 5), 500) : null;
191
+ await commands.resizePane(pane, hasCols ? c : null, r); // resize only the requested pane axis
187
192
  }
188
193
  else if (isWindowId(window)) {
189
194
  const rw = rows != null ? Math.min(Math.max(Number(rows) || 0, 5), 500) : null;
190
- await commands.resizeWindow(window, c, rw); // a lone pane fills the window
195
+ if (c == null && rw == null)
196
+ return res.status(400).json({ error: 'bad window size' });
197
+ await commands.resizeWindow(window, c, rw); // tmux redistributes the total window size through its layout
191
198
  }
192
199
  else {
193
200
  return res.status(400).json({ error: 'bad resize target' });
@@ -55,6 +55,7 @@ import { clearCodexConversationThroughTui } from './agents/codexTerminalControl.
55
55
  import { sessionsDir as codexSessionsDir } from './agents/codex.js';
56
56
  import { inspectCodexOpenRootSession } from './agents/codexOpenSession.js';
57
57
  import { CodexActivationReceiptStore } from './agents/codexActivationReceipt.js';
58
+ import { CodexRestartReceiptStore } from './agents/codexRestartReceipt.js';
58
59
  import { ApiAccountService, apiAccountsPath } from './apiAccounts.js';
59
60
  import { ClaudeHookBridgeConnector } from '../connectors/claude/index.js';
60
61
  import { CodeBuddyHookBridgeConnector } from '../connectors/codebuddy/index.js';
@@ -139,6 +140,7 @@ const stateFile = process.env.CLAUDE_STATE_FILE || claudeStatePath(home);
139
140
  let codexApp = null;
140
141
  const agentRuntimeDirectory = agentRuntimeDirectoryPath(home);
141
142
  const codexActivationReceipts = new CodexActivationReceiptStore(path.join(agentRuntimeDirectory, 'codex-activation-receipts.json'));
143
+ const codexRestartReceipts = new CodexRestartReceiptStore(path.join(agentRuntimeDirectory, 'codex-restart-receipts.json'));
142
144
  const legacyCodexOutbox = codexOutboxPath(home);
143
145
  let conversationStartupBlockReason;
144
146
  try {
@@ -214,6 +216,7 @@ const agentRuntime = createBuiltinAgentRuntime({
214
216
  panes: agentPanes,
215
217
  process: agentProcess,
216
218
  stateDirectory: agentRuntimeDirectory,
219
+ conversationRestartReceipts: codexRestartReceipts,
217
220
  ...(conversationStartupBlockReason === undefined ? {} : { conversationStartupBlockReason }),
218
221
  claudeEvents: events,
219
222
  claudeProjectsRoot: path.join(agentHome, '.claude', 'projects'),
@@ -243,6 +246,7 @@ const agentRuntime = createBuiltinAgentRuntime({
243
246
  },
244
247
  codexApp,
245
248
  codexActivationReceipts,
249
+ codexRestartReceipts,
246
250
  codexActivationCommands: {
247
251
  openOutputCapture: (pane) => commands.openPaneOutputCapture(pane),
248
252
  paneEpoch: async () => {
@@ -252,6 +256,14 @@ const agentRuntime = createBuiltinAgentRuntime({
252
256
  inspectOpenSession: (pid) => inspectCodexOpenRootSession(pid, codexSessionsDir(agentHome)),
253
257
  runPaneCommand: (pane, command) => commands.runPaneCommand(pane, command),
254
258
  },
259
+ codexRestartCommands: {
260
+ paneEpoch: async () => {
261
+ const environment = await workspaceTmux.observeEnvironment();
262
+ return environment.status === 'present' ? environment.tmuxServerId : null;
263
+ },
264
+ runPaneCommand: (pane, command) => commands.runPaneCommand(pane, command),
265
+ terminate: (pid, signal) => process.kill(pid, signal),
266
+ },
255
267
  codexClear: async (pane, threadId) => {
256
268
  await clearCodexConversationThroughTui(codexApp, commands, pane, threadId);
257
269
  },
@@ -286,9 +286,13 @@ export async function sendKey(paneId, key) {
286
286
  // window — including the PC) until restoreWindowSize is called. Pass rows = null to change
287
287
  // only the column count and leave the height untouched.
288
288
  export async function resizeWindow(windowId, cols, rows) {
289
- const args = ['resize-window', '-t', windowId, '-x', String(cols)];
289
+ const args = ['resize-window', '-t', windowId];
290
+ if (cols != null)
291
+ args.push('-x', String(cols));
290
292
  if (rows != null)
291
293
  args.push('-y', String(rows));
294
+ if (cols == null && rows == null)
295
+ throw new Error('resize-window requires a width or height');
292
296
  await runTmux(args);
293
297
  }
294
298
  // Hand sizing back to the attached clients (tmux default), so the PC's terminal dictates
@@ -296,11 +300,17 @@ export async function resizeWindow(windowId, cols, rows) {
296
300
  export async function restoreWindowSize(windowId) {
297
301
  await runTmux(['set-window-option', '-t', windowId, 'window-size', 'latest']);
298
302
  }
299
- // Resize just one pane's width inside its window (siblings absorb the difference; the window
300
- // total is unchanged). Use this for a pane in a split — resizing the whole window would
301
- // shrink every pane. A lone pane can't be resized this way (it fills the window).
302
- export async function resizePane(paneId, cols) {
303
- await runTmux(['resize-pane', '-t', paneId, '-x', String(cols)]);
303
+ // Resize one pane along either or both axes inside its window (siblings absorb the difference).
304
+ // A lone pane can't be resized this way (it fills the window).
305
+ export async function resizePane(paneId, cols, rows) {
306
+ const args = ['resize-pane', '-t', paneId];
307
+ if (cols != null)
308
+ args.push('-x', String(cols));
309
+ if (rows != null)
310
+ args.push('-y', String(rows));
311
+ if (cols == null && rows == null)
312
+ throw new Error('resize-pane requires a width or height');
313
+ await runTmux(args);
304
314
  }
305
315
  // The window's exact pane arrangement, captured so "restore" can put a split back the way it
306
316
  // was after resizePane changed the ratio. resizePane doesn't touch window size, so window-size
@@ -1,5 +1,5 @@
1
1
  const Q_ESCAPED = new Set([
2
- '|', '&', ';', '<', '>', '(', ')', '$', '`', '\\', '"', "'", '*', '?', '[', '#', ' ', '=', '%',
2
+ '|', '&', ';', '<', '>', '(', ')', '{', '}', '$', '`', '\\', '"', "'", '*', '?', '[', '#', ' ', '=', '%', '\n', '\t',
3
3
  ]);
4
4
  export function tmuxFormat(fields) {
5
5
  if (!Array.isArray(fields) || fields.length === 0)
@@ -42,6 +42,22 @@ export function parseTmuxRows(output, columns, label = 'tmux') {
42
42
  const value = String(output ?? '');
43
43
  if (value === '' || value === '\n' || value === '\r\n')
44
44
  return [];
45
- return value.replace(/\r?\n$/, '').split(/\r?\n/)
46
- .map((line) => parseTmuxFields(line, columns, label));
45
+ const rows = [];
46
+ let start = 0;
47
+ for (let i = 0; i < value.length; i++) {
48
+ // tmux 3.8 q-escapes literal LF. Skip complete escape pairs so that
49
+ // an escaped backslash before LF still leaves a record boundary.
50
+ if (value.charAt(i) === '\\') {
51
+ i++;
52
+ continue;
53
+ }
54
+ if (value.charAt(i) !== '\n')
55
+ continue;
56
+ const end = value.charAt(i - 1) === '\r' ? i - 1 : i;
57
+ rows.push(parseTmuxFields(value.slice(start, end), columns, label));
58
+ start = i + 1;
59
+ }
60
+ if (start < value.length)
61
+ rows.push(parseTmuxFields(value.slice(start), columns, label));
62
+ return rows;
47
63
  }