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,655 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { ConversationRestartError, } from '../agent-runtime/conversationRestart.js';
4
+ import { serializePaneInput } from '../paneInput.js';
5
+ import { codexAppSocketPath } from '../cli/codexManaged.js';
6
+ import { isSessionUuid, normTty } from './scanUtils.js';
7
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'fish', 'dash', 'ksh', 'tcsh']);
8
+ const CODEX_EXE_RE = /^codex(?:\.exe)?$/i;
9
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
10
+ class RestartFault extends Error {
11
+ code;
12
+ constructor(message, code) {
13
+ super(message);
14
+ this.code = code;
15
+ this.name = 'RestartFault';
16
+ }
17
+ }
18
+ function commandTokens(identity) {
19
+ return identity.commandLine?.trim().split(/\s+/).filter(Boolean) ?? [];
20
+ }
21
+ function executableName(identity) {
22
+ return identity.executable?.split(/[\\/]/).at(-1)?.toLowerCase() ?? '';
23
+ }
24
+ function samePane(first, second) {
25
+ return first.paneId === second.paneId
26
+ && first.sessionName === second.sessionName
27
+ && first.windowId === second.windowId
28
+ && normTty(first.tty) !== ''
29
+ && normTty(first.tty) === normTty(second.tty);
30
+ }
31
+ function sameRecordedPane(pane, receipt) {
32
+ return pane.paneId === receipt.pane.paneId
33
+ && pane.sessionName === receipt.pane.sessionName
34
+ && pane.windowId === receipt.pane.windowId
35
+ && normTty(pane.tty) === normTty(receipt.pane.tty);
36
+ }
37
+ function sameIdentity(first, second) {
38
+ return first.pid === second.pid
39
+ && first.startedAt !== undefined && second.startedAt === first.startedAt
40
+ && first.tty !== undefined && normTty(first.tty) === normTty(second.tty)
41
+ && first.executable !== undefined && second.executable === first.executable
42
+ && first.ppid !== undefined && second.ppid === first.ppid
43
+ && first.commandLine !== undefined && second.commandLine === first.commandLine;
44
+ }
45
+ function sameOptionalIdentity(first, second) {
46
+ return first === undefined ? second === undefined : second !== undefined && sameIdentity(first, second);
47
+ }
48
+ function sameRunProcess(locked, identity) {
49
+ return !!locked && locked.pid === identity.pid
50
+ && locked.startedAt !== undefined && locked.startedAt === identity.startedAt
51
+ && !!locked.tty && normTty(locked.tty) === normTty(identity.tty);
52
+ }
53
+ function sameGeneration(first, second) {
54
+ return first.pid === second.pid
55
+ && first.startedAt === second.startedAt
56
+ && normTty(first.tty) === normTty(second.tty)
57
+ && first.executable === second.executable;
58
+ }
59
+ function toStoredIdentity(identity) {
60
+ if (!identity.startedAt || !identity.tty || !identity.executable
61
+ || !Number.isSafeInteger(identity.pid) || identity.pid <= 0
62
+ || !Number.isSafeInteger(identity.ppid) || (identity.ppid ?? -1) < 0)
63
+ return null;
64
+ return {
65
+ pid: identity.pid,
66
+ ppid: identity.ppid,
67
+ startedAt: identity.startedAt,
68
+ tty: identity.tty,
69
+ executable: identity.executable,
70
+ };
71
+ }
72
+ function isHandmuxCodexWrapper(identity) {
73
+ const tokens = commandTokens(identity);
74
+ const scriptIndex = tokens.findIndex((token) => /(?:^|[\\/])handmux(?:\.js)?$/i.test(token));
75
+ return scriptIndex >= 0
76
+ && tokens.slice(scriptIndex + 1).some((token) => token === 'codex')
77
+ && !!identity.startedAt && !!identity.tty && !!identity.executable && !!identity.commandLine;
78
+ }
79
+ function isCodexTui(identity, socketPath) {
80
+ const tokens = commandTokens(identity);
81
+ return CODEX_EXE_RE.test(executableName(identity))
82
+ && tokens.includes('--remote')
83
+ && tokens.includes(`unix://${socketPath}`)
84
+ && !!identity.startedAt && !!identity.tty && !!identity.executable && !!identity.commandLine;
85
+ }
86
+ function isCodexAppServer(identity, socketPath) {
87
+ const tokens = commandTokens(identity);
88
+ const listenIndex = tokens.indexOf('--listen');
89
+ return CODEX_EXE_RE.test(executableName(identity))
90
+ && tokens.includes('app-server')
91
+ && listenIndex >= 0 && tokens[listenIndex + 1] === `unix://${socketPath}`
92
+ && !!identity.startedAt && !!identity.tty && !!identity.executable && !!identity.commandLine
93
+ && Number.isSafeInteger(identity.ppid);
94
+ }
95
+ function isNpmCodexShim(identity, socketPath, role) {
96
+ if (!/^node(?:\.exe)?$/i.test(executableName(identity)) || !identity.startedAt
97
+ || !identity.tty || !identity.commandLine || !Number.isSafeInteger(identity.ppid))
98
+ return false;
99
+ const tokens = commandTokens(identity);
100
+ if (!/^node(?:\.exe)?$/i.test(path.basename(tokens[0] ?? '')) || !path.isAbsolute(tokens[1] ?? ''))
101
+ return false;
102
+ let entrypoint;
103
+ try {
104
+ entrypoint = fs.realpathSync(tokens[1]);
105
+ }
106
+ catch {
107
+ return false;
108
+ }
109
+ if (!/[\\/]@openai[\\/]codex[\\/]bin[\\/]codex\.js$/i.test(entrypoint))
110
+ return false;
111
+ const args = tokens.slice(2);
112
+ if (role === 'tui') {
113
+ const remote = args.indexOf('--remote');
114
+ return remote >= 0 && args[remote + 1] === `unix://${socketPath}` && !args.includes('app-server');
115
+ }
116
+ const listen = args.indexOf('--listen');
117
+ return args[0] === 'app-server' && listen >= 0 && args[listen + 1] === `unix://${socketPath}`;
118
+ }
119
+ function managedParent(group, child, socketPath, role) {
120
+ const parent = group.find((candidate) => candidate.pid === child.ppid
121
+ && normTty(candidate.tty) === normTty(child.tty));
122
+ if (!parent)
123
+ return null;
124
+ if (isHandmuxCodexWrapper(parent))
125
+ return { wrapper: parent };
126
+ if (!isNpmCodexShim(parent, socketPath, role))
127
+ return null;
128
+ const wrapper = group.find((candidate) => candidate.pid === parent.ppid
129
+ && normTty(candidate.tty) === normTty(parent.tty)
130
+ && isHandmuxCodexWrapper(candidate));
131
+ return wrapper ? { wrapper, shim: parent } : null;
132
+ }
133
+ function recoveryOf(receipt) {
134
+ return {
135
+ kind: 'codex_resume',
136
+ sessionId: receipt.sessionId,
137
+ command: receipt.command,
138
+ };
139
+ }
140
+ function validCodexRestartRecovery(value) {
141
+ return value.kind === 'codex_resume' && isSessionUuid(value.sessionId)
142
+ && value.command === `handmux codex resume ${value.sessionId}`;
143
+ }
144
+ function stableRun(run, resolveRun) {
145
+ return !run.signal.aborted && resolveRun(run.ref) === run;
146
+ }
147
+ export function createCodexConversationRestartController({ app, panes, process, commands, receipts, pauseSessionDelivery, resolveRun, isRuntimeRunReady, home, now = Date.now, wait = pause, pollMs = 250, timeoutMs = 45_000, }) {
148
+ if (!app || typeof app.discover !== 'function' || !panes || !process
149
+ || typeof process.inspectForegroundFresh !== 'function'
150
+ || typeof process.inspectForegroundGroupFresh !== 'function'
151
+ || typeof process.inspectProcessGenerationFresh !== 'function'
152
+ || !commands || typeof commands.paneEpoch !== 'function'
153
+ || typeof commands.runPaneCommand !== 'function' || typeof commands.terminate !== 'function'
154
+ || !receipts || typeof receipts.prepare !== 'function'
155
+ || typeof pauseSessionDelivery !== 'function' || typeof resolveRun !== 'function'
156
+ || typeof isRuntimeRunReady !== 'function'
157
+ || !Number.isSafeInteger(pollMs) || pollMs < 1
158
+ || !Number.isSafeInteger(timeoutMs) || timeoutMs < pollMs) {
159
+ throw new TypeError('Codex Conversation restart requires fresh process, pane, and runtime controls');
160
+ }
161
+ const socketPath = (paneId) => codexAppSocketPath(paneId, home);
162
+ const deliveryFenceReleases = new Map();
163
+ const releaseDeliveryFence = (operationId) => {
164
+ const release = deliveryFenceReleases.get(operationId);
165
+ if (!release)
166
+ return;
167
+ release();
168
+ deliveryFenceReleases.delete(operationId);
169
+ };
170
+ const oldAppServerStatus = async (receipt) => {
171
+ if (!receipt.process.appServer)
172
+ return 'unknown';
173
+ try {
174
+ return await process.inspectProcessGenerationFresh(receipt.process.appServer);
175
+ }
176
+ catch {
177
+ return 'unknown';
178
+ }
179
+ };
180
+ const paneFor = async (paneId) => ((await panes.list()).find((candidate) => candidate.paneId === paneId) ?? null);
181
+ const freshForeground = async (pane) => (process.inspectForegroundFresh(pane));
182
+ const freshGroup = async (pane) => (process.inspectForegroundGroupFresh(pane));
183
+ const paneAndEpochMatch = async (receipt) => {
184
+ const current = await paneFor(receipt.pane.paneId);
185
+ if (!current || !sameRecordedPane(current, receipt))
186
+ return null;
187
+ const epoch = await commands.paneEpoch(current.paneId);
188
+ return epoch === receipt.pane.tmuxEpoch ? current : null;
189
+ };
190
+ const recoveryShell = async (receipt) => {
191
+ const serverStatus = await oldAppServerStatus(receipt);
192
+ if (serverStatus !== 'exited' && serverStatus !== 'replaced')
193
+ return null;
194
+ const pane = await paneAndEpochMatch(receipt);
195
+ if (!pane)
196
+ return null;
197
+ const ownership = await app.discover(pane.paneId);
198
+ if (ownership?.managed !== false)
199
+ return null;
200
+ const [foreground, group] = await Promise.all([freshForeground(pane), freshGroup(pane)]);
201
+ if (!foreground || !SHELLS.has(executableName(foreground)))
202
+ return null;
203
+ const originalPresent = group.some((identity) => (sameGeneration(receipt.process.tui, identity)
204
+ || sameGeneration(receipt.process.wrapper, identity)
205
+ || (receipt.process.tuiShim && sameGeneration(receipt.process.tuiShim, identity))
206
+ || (receipt.process.appServerShim && sameGeneration(receipt.process.appServerShim, identity))));
207
+ return originalPresent ? null : { pane, identity: foreground };
208
+ };
209
+ const managedTui = async (pane, forSocket) => {
210
+ const [foreground, group] = await Promise.all([freshForeground(pane), freshGroup(pane)]);
211
+ if (!foreground)
212
+ return null;
213
+ const anchor = group.find((candidate) => candidate.pid === foreground.pid);
214
+ if (!anchor || !sameIdentity(foreground, anchor))
215
+ return null;
216
+ const matches = group.flatMap((tui) => {
217
+ if (!isCodexTui(tui, forSocket))
218
+ return [];
219
+ const parent = managedParent(group, tui, forSocket, 'tui');
220
+ if (!parent || !Number.isSafeInteger(parent.wrapper.ppid) || !parent.wrapper.startedAt)
221
+ return [];
222
+ const servers = group.filter((candidate) => isCodexAppServer(candidate, forSocket)
223
+ && managedParent(group, candidate, forSocket, 'appServer')?.wrapper.pid === parent.wrapper.pid);
224
+ if (servers.length !== 1 || (!sameIdentity(anchor, tui) && !sameIdentity(anchor, servers[0])))
225
+ return [];
226
+ return [{ tui, ...parent }];
227
+ });
228
+ return matches.length === 1 ? matches[0] : null;
229
+ };
230
+ const inspectEvidence = async (run) => {
231
+ const pane = await paneFor(run.ref.paneId);
232
+ if (!pane || pane.paneId !== run.ref.paneId || !normTty(pane.tty)) {
233
+ throw new RestartFault('The original terminal pane is unavailable', 'stale_run');
234
+ }
235
+ const epoch = await commands.paneEpoch(pane.paneId);
236
+ if (!epoch)
237
+ throw new RestartFault('The terminal pane identity cannot be verified', 'unavailable');
238
+ const ownership = await app.discover(pane.paneId);
239
+ if (ownership?.managed !== true || ownership.threadId !== run.ref.sessionId) {
240
+ throw new RestartFault('The managed Codex session no longer matches this conversation', 'unavailable');
241
+ }
242
+ const identity = await freshForeground(pane);
243
+ const group = await freshGroup(pane);
244
+ if (!identity || !sameRunProcess(run.process, identity)) {
245
+ throw new RestartFault('The Codex process changed; no process was stopped', 'stale_run');
246
+ }
247
+ const anchor = group.find((candidate) => candidate.pid === identity.pid);
248
+ if (!anchor || !sameIdentity(identity, anchor)) {
249
+ throw new RestartFault('The foreground Codex TUI cannot be verified as managed', 'unavailable');
250
+ }
251
+ // The generic foreground selector may pick the older App Server sibling instead of the TUI.
252
+ // Accept that lease anchor only when one exact TUI and App Server pair shares this verified wrapper.
253
+ const matches = [];
254
+ for (const target of group) {
255
+ if (!isCodexTui(target, socketPath(pane.paneId)))
256
+ continue;
257
+ const parent = managedParent(group, target, socketPath(pane.paneId), 'tui');
258
+ const wrapper = parent?.wrapper;
259
+ if (!parent || !wrapper?.startedAt || !wrapper.executable || !wrapper.commandLine
260
+ || !Number.isSafeInteger(wrapper.ppid))
261
+ continue;
262
+ const servers = group.filter((candidate) => isCodexAppServer(candidate, socketPath(pane.paneId))
263
+ && normTty(candidate.tty) === normTty(wrapper.tty)
264
+ && managedParent(group, candidate, socketPath(pane.paneId), 'appServer')?.wrapper.pid === wrapper.pid);
265
+ if (servers.length !== 1)
266
+ continue;
267
+ const server = servers[0];
268
+ const serverParent = server ? managedParent(group, server, socketPath(pane.paneId), 'appServer') : null;
269
+ if (!server || !serverParent || !sameIdentity(wrapper, serverParent.wrapper)
270
+ || (!sameIdentity(anchor, target) && !sameIdentity(anchor, server)))
271
+ continue;
272
+ matches.push({
273
+ pane, epoch, tui: target, wrapper, appServer: server,
274
+ ...(parent.shim ? { tuiShim: parent.shim } : {}),
275
+ ...(serverParent.shim ? { appServerShim: serverParent.shim } : {}),
276
+ });
277
+ }
278
+ if (matches.length !== 1) {
279
+ throw new RestartFault('The managed Codex TUI and App Server pair cannot be verified uniquely', 'unavailable');
280
+ }
281
+ return matches[0];
282
+ };
283
+ const recordInput = (run, evidence) => {
284
+ const tui = toStoredIdentity(evidence.tui);
285
+ const wrapper = toStoredIdentity(evidence.wrapper);
286
+ const tuiShim = evidence.tuiShim ? toStoredIdentity(evidence.tuiShim) : undefined;
287
+ const appServerShim = evidence.appServerShim ? toStoredIdentity(evidence.appServerShim) : undefined;
288
+ const appServer = toStoredIdentity(evidence.appServer);
289
+ if (!tui || !wrapper || !appServer || (evidence.tuiShim && !tuiShim)
290
+ || (evidence.appServerShim && !appServerShim) || !run.ref.sessionId) {
291
+ throw new RestartFault('The Codex process generation is incomplete', 'unavailable');
292
+ }
293
+ return {
294
+ pane: {
295
+ paneId: evidence.pane.paneId,
296
+ sessionName: evidence.pane.sessionName,
297
+ windowId: evidence.pane.windowId,
298
+ tty: evidence.pane.tty,
299
+ tmuxEpoch: evidence.epoch,
300
+ },
301
+ process: {
302
+ tui, wrapper, appServer,
303
+ ...(tuiShim ? { tuiShim } : {}),
304
+ ...(appServerShim ? { appServerShim } : {}),
305
+ },
306
+ sessionId: run.ref.sessionId,
307
+ previousRunId: run.ref.runId,
308
+ };
309
+ };
310
+ const receiptView = async (receipt, { allowResume = true } = {}) => {
311
+ const recovery = recoveryOf(receipt);
312
+ let state = 'stale';
313
+ let canResume = false;
314
+ try {
315
+ const currentPane = await paneAndEpochMatch(receipt);
316
+ if (currentPane) {
317
+ state = 'current';
318
+ if (allowResume && receipt.phase !== 'resuming' && receipt.phase !== 'ready') {
319
+ canResume = await recoveryShell(receipt) !== null;
320
+ }
321
+ }
322
+ }
323
+ catch {
324
+ state = 'stale';
325
+ canResume = false;
326
+ }
327
+ return {
328
+ agentId: receipt.agentId,
329
+ paneId: receipt.pane.paneId,
330
+ operationId: receipt.operationId,
331
+ recovery,
332
+ phase: receipt.phase,
333
+ state,
334
+ canResume,
335
+ };
336
+ };
337
+ const errorWithReceipt = async (message, code, receipt, allowResume = true) => new ConversationRestartError(message, code, await receiptView(receipt, { allowResume }));
338
+ const originalStillPresent = async (receipt) => {
339
+ try {
340
+ const probePane = {
341
+ paneId: receipt.pane.paneId,
342
+ sessionName: receipt.pane.sessionName,
343
+ windowId: receipt.pane.windowId,
344
+ windowName: receipt.pane.sessionName,
345
+ currentCommand: 'codex',
346
+ tty: receipt.pane.tty,
347
+ };
348
+ const [ownership, group] = await Promise.all([
349
+ app.discover(receipt.pane.paneId), freshGroup(probePane),
350
+ ]);
351
+ return ownership?.managed === true && ownership.threadId === receipt.sessionId
352
+ && group.some((identity) => sameGeneration(receipt.process.tui, identity));
353
+ }
354
+ catch {
355
+ return false;
356
+ }
357
+ };
358
+ const resumeReady = async (receipt) => {
359
+ const serverStatus = await oldAppServerStatus(receipt);
360
+ if (serverStatus !== 'exited' && serverStatus !== 'replaced')
361
+ return false;
362
+ const pane = await paneAndEpochMatch(receipt);
363
+ if (!pane)
364
+ throw new RestartFault('The original pane was replaced during restart', 'unavailable');
365
+ const ownership = await app.discover(pane.paneId);
366
+ if (ownership?.managed === true && ownership.threadId !== receipt.sessionId) {
367
+ throw new RestartFault('A different Codex session appeared in the original pane', 'unavailable');
368
+ }
369
+ if (ownership?.managed !== true)
370
+ return false;
371
+ const current = await managedTui(pane, socketPath(pane.paneId));
372
+ if (!current || sameGeneration(receipt.process.tui, current.tui)
373
+ || sameGeneration(receipt.process.wrapper, current.wrapper)
374
+ || (receipt.process.tuiShim && current.shim
375
+ && sameGeneration(receipt.process.tuiShim, current.shim)))
376
+ return false;
377
+ return await isRuntimeRunReady(pane.paneId, receipt.sessionId, receipt.previousRunId);
378
+ };
379
+ const waitForShell = async (receipt, signal) => {
380
+ const deadline = now() + timeoutMs;
381
+ while (now() <= deadline) {
382
+ if (signal.aborted)
383
+ throw new RestartFault('Conversation restart timed out after stopping Codex', 'unavailable');
384
+ const pane = await paneAndEpochMatch(receipt);
385
+ if (!pane)
386
+ throw new RestartFault('The original pane was replaced during restart', 'unavailable');
387
+ const [ownership, foreground, group, serverStatus] = await Promise.all([
388
+ app.discover(pane.paneId), freshForeground(pane), freshGroup(pane), oldAppServerStatus(receipt),
389
+ ]);
390
+ if (ownership?.managed === true && ownership.threadId !== receipt.sessionId) {
391
+ throw new RestartFault('A different Codex session appeared in the original pane', 'unavailable');
392
+ }
393
+ const originalPresent = group.some((identity) => (sameGeneration(receipt.process.tui, identity)
394
+ || sameGeneration(receipt.process.wrapper, identity)
395
+ || (receipt.process.tuiShim && sameGeneration(receipt.process.tuiShim, identity))
396
+ || (receipt.process.appServerShim && sameGeneration(receipt.process.appServerShim, identity))));
397
+ if ((serverStatus === 'exited' || serverStatus === 'replaced')
398
+ && ownership?.managed === false && !originalPresent && foreground
399
+ && SHELLS.has(executableName(foreground)))
400
+ return foreground;
401
+ await wait(pollMs);
402
+ }
403
+ throw new RestartFault('Codex did not return to the original shell before the restart timed out', 'unavailable');
404
+ };
405
+ const waitForReady = async (receipt, signal) => {
406
+ const deadline = now() + timeoutMs;
407
+ while (now() <= deadline) {
408
+ if (signal.aborted)
409
+ throw new RestartFault('Conversation restart timed out; copy the recovery command', 'unavailable');
410
+ if (await resumeReady(receipt))
411
+ return;
412
+ await wait(pollMs);
413
+ }
414
+ throw new RestartFault('The Codex session did not become ready before the restart timed out', 'unavailable');
415
+ };
416
+ const finalizeReady = (receipt) => {
417
+ const ready = receipts.transition(receipt.operationId, ['prepared', 'stopped', 'resuming', 'ready'], 'ready');
418
+ releaseDeliveryFence(receipt.operationId);
419
+ return ready;
420
+ };
421
+ const maybeReconcileReady = async (receipt) => {
422
+ if (receipt.phase === 'ready') {
423
+ releaseDeliveryFence(receipt.operationId);
424
+ return receipt;
425
+ }
426
+ if (await resumeReady(receipt)) {
427
+ return finalizeReady(receipt);
428
+ }
429
+ return receipt;
430
+ };
431
+ return {
432
+ apiVersion: 1,
433
+ validRecovery: validCodexRestartRecovery,
434
+ async reconcileRun(run) {
435
+ if (run.ref.agentId !== 'codex' || !run.ref.sessionId || !stableRun(run, resolveRun))
436
+ return;
437
+ const pending = receipts.list().filter((receipt) => receipt.phase !== 'ready'
438
+ && receipt.sessionId === run.ref.sessionId && receipt.previousRunId !== run.ref.runId);
439
+ if (!pending.length)
440
+ return;
441
+ const evidence = await inspectEvidence(run);
442
+ for (const receipt of pending) {
443
+ // A new runId or vanished pane cannot prove the stopped process family is gone.
444
+ // Legacy receipts without the App Server generation remain fail closed.
445
+ if (!receipt.process.appServer)
446
+ continue;
447
+ const identities = [receipt.process.tui, receipt.process.wrapper, receipt.process.appServer,
448
+ ...(receipt.process.tuiShim ? [receipt.process.tuiShim] : []),
449
+ ...(receipt.process.appServerShim ? [receipt.process.appServerShim] : [])];
450
+ const statuses = await Promise.all(identities.map((identity) => (process.inspectProcessGenerationFresh(identity))));
451
+ if (!statuses.every((status) => status === 'exited' || status === 'replaced'))
452
+ continue;
453
+ // Reloaded receipts have no in-memory release callback. Reuse the existing fence lifecycle
454
+ // so its eventual release also wakes Core's normal Queue dispatcher.
455
+ if (!deliveryFenceReleases.has(receipt.operationId)) {
456
+ const release = await pauseSessionDelivery({ agentId: 'codex', sessionId: receipt.sessionId });
457
+ if (deliveryFenceReleases.has(receipt.operationId))
458
+ release();
459
+ else
460
+ deliveryFenceReleases.set(receipt.operationId, release);
461
+ }
462
+ const current = await inspectEvidence(run);
463
+ if (!samePane(evidence.pane, current.pane) || evidence.epoch !== current.epoch
464
+ || !sameIdentity(evidence.tui, current.tui) || !sameIdentity(evidence.wrapper, current.wrapper)
465
+ || !sameIdentity(evidence.appServer, current.appServer)
466
+ || !sameOptionalIdentity(evidence.tuiShim, current.tuiShim)
467
+ || !sameOptionalIdentity(evidence.appServerShim, current.appServerShim)
468
+ || !stableRun(run, resolveRun) || run.ref.sessionId !== receipt.sessionId)
469
+ return;
470
+ finalizeReady(receipt);
471
+ }
472
+ },
473
+ async restart(run, signal) {
474
+ if (run.ref.agentId !== 'codex')
475
+ throw new ConversationRestartError('Conversation restart is not supported for this Agent', 'unsupported');
476
+ if (!run.ref.sessionId || !isSessionUuid(run.ref.sessionId) || !stableRun(run, resolveRun)) {
477
+ throw new ConversationRestartError('The Agent run changed; restart was not started', 'not_started');
478
+ }
479
+ const existing = receipts.latestForPane(run.ref.paneId);
480
+ if (existing && existing.sessionId === run.ref.sessionId && existing.phase !== 'ready') {
481
+ throw new ConversationRestartError('Conversation restart is already in progress', 'in_progress', await receiptView(existing));
482
+ }
483
+ let evidence;
484
+ try {
485
+ evidence = await inspectEvidence(run);
486
+ }
487
+ catch (error) {
488
+ if (error instanceof RestartFault) {
489
+ throw new ConversationRestartError(`Restart not started: ${error.message}`, 'not_started');
490
+ }
491
+ throw new ConversationRestartError('Codex process could not be verified; restart was not started', 'not_started');
492
+ }
493
+ if (!stableRun(run, resolveRun))
494
+ throw new ConversationRestartError('The Agent run changed; restart was not started', 'not_started');
495
+ let receipt;
496
+ try {
497
+ receipt = receipts.prepare(recordInput(run, evidence));
498
+ }
499
+ catch {
500
+ throw new ConversationRestartError('Restart state could not be saved; Codex was not stopped', 'not_started');
501
+ }
502
+ let release;
503
+ let signalAttempted = false;
504
+ let terminationFailed = false;
505
+ const clearBeforeStop = async (message) => {
506
+ // Before terminate() is called we know this request did not stop anything, even if the
507
+ // original process independently vanished during the final identity probe.
508
+ if (!signalAttempted || await originalStillPresent(receipt)) {
509
+ let cleared = false;
510
+ try {
511
+ cleared = receipts.clear(receipt.operationId);
512
+ }
513
+ catch { /* The durable pending marker still blocks delivery; fail closed. */ }
514
+ if (cleared) {
515
+ releaseDeliveryFence(receipt.operationId);
516
+ throw new ConversationRestartError(`Restart not started: ${message}`, 'not_started');
517
+ }
518
+ }
519
+ throw await errorWithReceipt(message, 'unavailable', receipt, false);
520
+ };
521
+ try {
522
+ release = await pauseSessionDelivery({ agentId: 'codex', sessionId: run.ref.sessionId });
523
+ deliveryFenceReleases.set(receipt.operationId, release);
524
+ if (signal.aborted)
525
+ return await clearBeforeStop('The operation timed out before Codex was stopped');
526
+ const result = await serializePaneInput(run.ref.paneId, async () => {
527
+ if (!stableRun(run, resolveRun)) {
528
+ return await clearBeforeStop('The Agent run changed before Codex could be stopped');
529
+ }
530
+ let current;
531
+ try {
532
+ current = await inspectEvidence(run);
533
+ }
534
+ catch (error) {
535
+ return await clearBeforeStop(error instanceof Error ? error.message : 'Codex process could not be verified before the stop boundary');
536
+ }
537
+ if (!samePane(evidence.pane, current.pane) || evidence.epoch !== current.epoch
538
+ || !sameIdentity(evidence.tui, current.tui) || !sameIdentity(evidence.wrapper, current.wrapper)
539
+ || !sameOptionalIdentity(evidence.tuiShim, current.tuiShim)
540
+ || !sameOptionalIdentity(evidence.appServerShim, current.appServerShim)
541
+ || !sameIdentity(evidence.appServer, current.appServer)) {
542
+ return await clearBeforeStop('The original Codex process or pane changed before the stop boundary');
543
+ }
544
+ if (!stableRun(run, resolveRun)) {
545
+ return await clearBeforeStop('The Agent run changed during the final process identity probe');
546
+ }
547
+ if (signal.aborted)
548
+ return await clearBeforeStop('The operation timed out before Codex was stopped');
549
+ signalAttempted = true;
550
+ let terminateError;
551
+ try {
552
+ const accepted = await commands.terminate(receipt.process.tui.pid, 'SIGTERM');
553
+ if (accepted === false) {
554
+ terminationFailed = true;
555
+ terminateError = new Error('SIGTERM was not accepted');
556
+ }
557
+ }
558
+ catch (error) {
559
+ terminationFailed = true;
560
+ terminateError = error;
561
+ }
562
+ let shell;
563
+ try {
564
+ shell = await waitForShell(receipt, signal);
565
+ }
566
+ catch (error) {
567
+ if (terminateError && await originalStillPresent(receipt)) {
568
+ return await clearBeforeStop('Codex is still running; the restart signal could not be delivered');
569
+ }
570
+ throw error;
571
+ }
572
+ receipt = receipts.transition(receipt.operationId, 'prepared', 'stopped');
573
+ const beforeResume = await paneAndEpochMatch(receipt);
574
+ const currentShell = beforeResume ? await freshForeground(beforeResume) : null;
575
+ if (!beforeResume || !currentShell || !sameIdentity(shell, currentShell)
576
+ || !SHELLS.has(executableName(currentShell))) {
577
+ throw new RestartFault('The original shell changed before the recovery command could be sent', 'unavailable');
578
+ }
579
+ if (signal.aborted)
580
+ throw new RestartFault('Conversation restart timed out; copy the recovery command', 'unavailable');
581
+ receipt = receipts.transition(receipt.operationId, 'stopped', 'resuming');
582
+ await commands.runPaneCommand(run.ref.paneId, receipt.command);
583
+ await waitForReady(receipt, signal);
584
+ receipt = finalizeReady(receipt);
585
+ return await receiptView(receipt, { allowResume: false });
586
+ });
587
+ return result;
588
+ }
589
+ catch (error) {
590
+ if (error instanceof ConversationRestartError)
591
+ throw error;
592
+ if (!signalAttempted) {
593
+ await clearBeforeStop(error instanceof Error ? error.message : 'Restart failed before Codex was stopped');
594
+ }
595
+ if (terminationFailed && await originalStillPresent(receipt)) {
596
+ try {
597
+ if (receipts.clear(receipt.operationId)) {
598
+ releaseDeliveryFence(receipt.operationId);
599
+ throw new ConversationRestartError('Codex is still running; the restart signal could not be delivered', 'not_started');
600
+ }
601
+ }
602
+ catch (cleanupError) {
603
+ if (cleanupError instanceof ConversationRestartError)
604
+ throw cleanupError;
605
+ // If the durable clear failed, preserve the on-disk marker and its delivery fence.
606
+ }
607
+ }
608
+ throw await errorWithReceipt(error instanceof Error ? error.message : 'Codex restart was not completed', error instanceof RestartFault ? error.code : 'unavailable', receipt);
609
+ }
610
+ },
611
+ async recovery(paneId) {
612
+ let receipt = receipts.latestForPane(paneId);
613
+ if (!receipt)
614
+ return null;
615
+ try {
616
+ receipt = await maybeReconcileReady(receipt);
617
+ }
618
+ catch { /* persisted recovery remains available */ }
619
+ return await receiptView(receipt);
620
+ },
621
+ async recover(paneId, operationId, signal) {
622
+ return await serializePaneInput(paneId, async () => {
623
+ let receipt = receipts.get(operationId);
624
+ if (!receipt || receipt.pane.paneId !== paneId || receipt.phase === 'ready') {
625
+ throw new ConversationRestartError('Conversation restart recovery is no longer available', 'unavailable');
626
+ }
627
+ const existing = await maybeReconcileReady(receipt);
628
+ if (existing.phase === 'ready')
629
+ return await receiptView(existing, { allowResume: false });
630
+ const view = await receiptView(existing);
631
+ const beforeResume = await recoveryShell(existing);
632
+ if (signal.aborted || view.state !== 'current' || !view.canResume
633
+ || !beforeResume || existing.phase === 'resuming') {
634
+ throw new ConversationRestartError('The original pane is not safe to resume; copy the recovery command and continue in the terminal', view.state === 'stale' ? 'stale_run' : 'unavailable', view);
635
+ }
636
+ receipt = receipts.transition(existing.operationId, ['prepared', 'stopped'], 'resuming');
637
+ const afterResume = await recoveryShell(receipt);
638
+ const rechecked = await receiptView(receipt, { allowResume: false });
639
+ if (signal.aborted || !afterResume || !sameIdentity(beforeResume.identity, afterResume.identity)
640
+ || rechecked.state !== 'current') {
641
+ throw new ConversationRestartError('The original pane changed before recovery', 'stale_run', rechecked);
642
+ }
643
+ await commands.runPaneCommand(paneId, receipt.command);
644
+ try {
645
+ await waitForReady(receipt, signal);
646
+ receipt = finalizeReady(receipt);
647
+ return await receiptView(receipt, { allowResume: false });
648
+ }
649
+ catch (error) {
650
+ throw await errorWithReceipt(error instanceof Error ? error.message : 'Codex recovery did not become ready', error instanceof RestartFault ? error.code : 'unavailable', receipt);
651
+ }
652
+ });
653
+ },
654
+ };
655
+ }