ai4ai 0.0.3 → 0.0.5

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 (169) hide show
  1. package/README.md +6 -0
  2. package/README.zh-CN.md +6 -0
  3. package/claude-plugin/.claude-plugin/plugin.json +1 -1
  4. package/claude-plugin/dist/adapters/claude/adapter.d.ts +10 -1
  5. package/claude-plugin/dist/adapters/claude/adapter.js +35 -10
  6. package/claude-plugin/dist/adapters/claude/journal.d.ts +8 -0
  7. package/claude-plugin/dist/adapters/claude/journal.js +4 -1
  8. package/claude-plugin/dist/adapters/claude/plugin.js +198 -91
  9. package/claude-plugin/dist/adapters/claude/worker.js +30 -8
  10. package/claude-plugin/dist/adapters/codex/adapter.d.ts +26 -19
  11. package/claude-plugin/dist/adapters/codex/adapter.js +283 -187
  12. package/claude-plugin/dist/adapters/codex/app-server.js +1 -1
  13. package/claude-plugin/dist/adapters/codex/control.d.ts +36 -1
  14. package/claude-plugin/dist/adapters/codex/control.js +74 -4
  15. package/claude-plugin/dist/adapters/codex/native-handoff.d.ts +60 -0
  16. package/claude-plugin/dist/adapters/codex/native-handoff.js +138 -0
  17. package/claude-plugin/dist/adapters/codex/runner.js +35 -32
  18. package/claude-plugin/dist/adapters/codex/tui-daemon-watch.js +60 -49
  19. package/claude-plugin/dist/adapters/declarations.d.ts +0 -1
  20. package/claude-plugin/dist/adapters/declarations.js +0 -1
  21. package/claude-plugin/dist/adapters/dsh/adapter.d.ts +39 -2
  22. package/claude-plugin/dist/adapters/dsh/adapter.js +164 -37
  23. package/claude-plugin/dist/adapters/dsh/plugin.d.ts +3 -1
  24. package/claude-plugin/dist/adapters/dsh/plugin.js +33 -22
  25. package/claude-plugin/dist/adapters/executors.d.ts +25 -2
  26. package/claude-plugin/dist/adapters/executors.js +58 -4
  27. package/claude-plugin/dist/adapters/external.d.ts +21 -0
  28. package/claude-plugin/dist/adapters/external.js +128 -18
  29. package/claude-plugin/dist/adapters/opencode/adapter.d.ts +13 -2
  30. package/claude-plugin/dist/adapters/opencode/adapter.js +53 -10
  31. package/claude-plugin/dist/adapters/opencode/journal.d.ts +2 -0
  32. package/claude-plugin/dist/adapters/opencode/journal.js +8 -3
  33. package/claude-plugin/dist/adapters/opencode/plugin.js +2 -2
  34. package/claude-plugin/dist/adapters/supervisor.js +64 -20
  35. package/claude-plugin/dist/adapters/types.d.ts +7 -0
  36. package/claude-plugin/dist/contract/schema.d.ts +8 -17
  37. package/claude-plugin/dist/contract/schema.js +3 -4
  38. package/claude-plugin/dist/contract/states.d.ts +11 -0
  39. package/claude-plugin/dist/contract/states.js +9 -0
  40. package/claude-plugin/dist/contract/types.d.ts +3 -3
  41. package/claude-plugin/dist/contract/validate.js +24 -14
  42. package/claude-plugin/dist/contract/version.d.ts +1 -1
  43. package/claude-plugin/dist/contract/version.js +1 -1
  44. package/claude-plugin/dist/core/dsh-selection.d.ts +43 -0
  45. package/claude-plugin/dist/core/dsh-selection.js +78 -0
  46. package/claude-plugin/dist/core/handoff.d.ts +42 -0
  47. package/claude-plugin/dist/core/handoff.js +63 -0
  48. package/claude-plugin/dist/core/index.d.ts +2 -0
  49. package/claude-plugin/dist/core/index.js +1 -0
  50. package/claude-plugin/dist/core/operations.js +33 -1
  51. package/claude-plugin/dist/core/session-probe.js +11 -22
  52. package/claude-plugin/dist/core/store.d.ts +8 -3
  53. package/claude-plugin/dist/core/store.js +17 -3
  54. package/claude-plugin/request-schema.json +1 -2
  55. package/dist/adapters/claude/adapter.d.ts +10 -1
  56. package/dist/adapters/claude/adapter.js +35 -10
  57. package/dist/adapters/claude/journal.d.ts +8 -0
  58. package/dist/adapters/claude/journal.js +4 -1
  59. package/dist/adapters/claude/plugin.js +198 -91
  60. package/dist/adapters/claude/worker.js +30 -8
  61. package/dist/adapters/codex/adapter.d.ts +26 -19
  62. package/dist/adapters/codex/adapter.js +283 -187
  63. package/dist/adapters/codex/app-server.js +1 -1
  64. package/dist/adapters/codex/control.d.ts +36 -1
  65. package/dist/adapters/codex/control.js +74 -4
  66. package/dist/adapters/codex/native-handoff.d.ts +60 -0
  67. package/dist/adapters/codex/native-handoff.js +138 -0
  68. package/dist/adapters/codex/runner.js +35 -32
  69. package/dist/adapters/codex/tui-daemon-watch.js +60 -49
  70. package/dist/adapters/declarations.d.ts +0 -1
  71. package/dist/adapters/declarations.js +0 -1
  72. package/dist/adapters/dsh/adapter.d.ts +39 -2
  73. package/dist/adapters/dsh/adapter.js +164 -37
  74. package/dist/adapters/dsh/plugin.d.ts +3 -1
  75. package/dist/adapters/dsh/plugin.js +33 -22
  76. package/dist/adapters/executors.d.ts +25 -2
  77. package/dist/adapters/executors.js +58 -4
  78. package/dist/adapters/external.d.ts +21 -0
  79. package/dist/adapters/external.js +128 -18
  80. package/dist/adapters/opencode/adapter.d.ts +13 -2
  81. package/dist/adapters/opencode/adapter.js +53 -10
  82. package/dist/adapters/opencode/journal.d.ts +2 -0
  83. package/dist/adapters/opencode/journal.js +8 -3
  84. package/dist/adapters/opencode/plugin.js +2 -2
  85. package/dist/adapters/supervisor.js +64 -20
  86. package/dist/adapters/types.d.ts +7 -0
  87. package/dist/contract/schema.d.ts +8 -17
  88. package/dist/contract/schema.js +3 -4
  89. package/dist/contract/states.d.ts +11 -0
  90. package/dist/contract/states.js +9 -0
  91. package/dist/contract/types.d.ts +3 -3
  92. package/dist/contract/validate.js +24 -14
  93. package/dist/contract/version.d.ts +1 -1
  94. package/dist/contract/version.js +1 -1
  95. package/dist/core/dsh-selection.d.ts +43 -0
  96. package/dist/core/dsh-selection.js +78 -0
  97. package/dist/core/handoff.d.ts +42 -0
  98. package/dist/core/handoff.js +63 -0
  99. package/dist/core/index.d.ts +2 -0
  100. package/dist/core/index.js +1 -0
  101. package/dist/core/operations.js +33 -1
  102. package/dist/core/session-probe.js +11 -22
  103. package/dist/core/store.d.ts +8 -3
  104. package/dist/core/store.js +17 -3
  105. package/docs/contract.md +25 -15
  106. package/opencode-plugin/dist/adapters/claude/adapter.d.ts +10 -1
  107. package/opencode-plugin/dist/adapters/claude/adapter.js +35 -10
  108. package/opencode-plugin/dist/adapters/claude/journal.d.ts +8 -0
  109. package/opencode-plugin/dist/adapters/claude/journal.js +4 -1
  110. package/opencode-plugin/dist/adapters/claude/plugin.js +198 -91
  111. package/opencode-plugin/dist/adapters/claude/worker.js +30 -8
  112. package/opencode-plugin/dist/adapters/codex/adapter.d.ts +26 -19
  113. package/opencode-plugin/dist/adapters/codex/adapter.js +283 -187
  114. package/opencode-plugin/dist/adapters/codex/app-server.js +1 -1
  115. package/opencode-plugin/dist/adapters/codex/control.d.ts +36 -1
  116. package/opencode-plugin/dist/adapters/codex/control.js +74 -4
  117. package/opencode-plugin/dist/adapters/codex/native-handoff.d.ts +60 -0
  118. package/opencode-plugin/dist/adapters/codex/native-handoff.js +138 -0
  119. package/opencode-plugin/dist/adapters/codex/runner.js +35 -32
  120. package/opencode-plugin/dist/adapters/codex/tui-daemon-watch.js +60 -49
  121. package/opencode-plugin/dist/adapters/declarations.d.ts +0 -1
  122. package/opencode-plugin/dist/adapters/declarations.js +0 -1
  123. package/opencode-plugin/dist/adapters/dsh/adapter.d.ts +39 -2
  124. package/opencode-plugin/dist/adapters/dsh/adapter.js +164 -37
  125. package/opencode-plugin/dist/adapters/dsh/plugin.d.ts +3 -1
  126. package/opencode-plugin/dist/adapters/dsh/plugin.js +33 -22
  127. package/opencode-plugin/dist/adapters/executors.d.ts +25 -2
  128. package/opencode-plugin/dist/adapters/executors.js +58 -4
  129. package/opencode-plugin/dist/adapters/external.d.ts +21 -0
  130. package/opencode-plugin/dist/adapters/external.js +128 -18
  131. package/opencode-plugin/dist/adapters/opencode/adapter.d.ts +13 -2
  132. package/opencode-plugin/dist/adapters/opencode/adapter.js +53 -10
  133. package/opencode-plugin/dist/adapters/opencode/journal.d.ts +2 -0
  134. package/opencode-plugin/dist/adapters/opencode/journal.js +8 -3
  135. package/opencode-plugin/dist/adapters/opencode/plugin.js +2 -2
  136. package/opencode-plugin/dist/adapters/supervisor.js +64 -20
  137. package/opencode-plugin/dist/adapters/types.d.ts +7 -0
  138. package/opencode-plugin/dist/contract/schema.d.ts +8 -17
  139. package/opencode-plugin/dist/contract/schema.js +3 -4
  140. package/opencode-plugin/dist/contract/states.d.ts +11 -0
  141. package/opencode-plugin/dist/contract/states.js +9 -0
  142. package/opencode-plugin/dist/contract/types.d.ts +3 -3
  143. package/opencode-plugin/dist/contract/validate.js +24 -14
  144. package/opencode-plugin/dist/contract/version.d.ts +1 -1
  145. package/opencode-plugin/dist/contract/version.js +1 -1
  146. package/opencode-plugin/dist/core/dsh-selection.d.ts +43 -0
  147. package/opencode-plugin/dist/core/dsh-selection.js +78 -0
  148. package/opencode-plugin/dist/core/handoff.d.ts +42 -0
  149. package/opencode-plugin/dist/core/handoff.js +63 -0
  150. package/opencode-plugin/dist/core/index.d.ts +2 -0
  151. package/opencode-plugin/dist/core/index.js +1 -0
  152. package/opencode-plugin/dist/core/operations.js +33 -1
  153. package/opencode-plugin/dist/core/session-probe.js +11 -22
  154. package/opencode-plugin/dist/core/store.d.ts +8 -3
  155. package/opencode-plugin/dist/core/store.js +17 -3
  156. package/opencode-plugin/package.json +1 -1
  157. package/package.json +1 -1
  158. package/claude-plugin/dist/adapters/codex/tui-restart-watch.d.ts +0 -2
  159. package/claude-plugin/dist/adapters/codex/tui-restart-watch.js +0 -330
  160. package/claude-plugin/dist/tmux/backend.d.ts +0 -55
  161. package/claude-plugin/dist/tmux/backend.js +0 -161
  162. package/dist/adapters/codex/tui-restart-watch.d.ts +0 -2
  163. package/dist/adapters/codex/tui-restart-watch.js +0 -330
  164. package/dist/tmux/backend.d.ts +0 -55
  165. package/dist/tmux/backend.js +0 -161
  166. package/opencode-plugin/dist/adapters/codex/tui-restart-watch.d.ts +0 -2
  167. package/opencode-plugin/dist/adapters/codex/tui-restart-watch.js +0 -330
  168. package/opencode-plugin/dist/tmux/backend.d.ts +0 -55
  169. package/opencode-plugin/dist/tmux/backend.js +0 -161
@@ -1,330 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Detached watcher for a Codex TUI restart handoff.
4
- *
5
- * The handoff tool call runs inside the source turn, so it cannot wait for that
6
- * turn to end. This watcher waits for the tmux pane to become idle, then sends
7
- * the harness-native `/new` command and the caller material as the next visible
8
- * turn. The TUI process and pane are never replaced.
9
- *
10
- * The source turn can still be writing after the tool returns and the footer
11
- * shows transient idle-looking frames, so the gate requires a sustained Ready
12
- * state and re-checks it immediately before the keys are sent. `/new` being
13
- * rejected mid-turn is retried only after the pane is genuinely idle again.
14
- * Delivery is proven from a rollout created after the reset that contains the
15
- * material as a *user* message; the source rollout already contains the
16
- * material as a tool argument and must never count as delivery.
17
- *
18
- * It then records the successor thread (the newest rollout for the workspace)
19
- * in a durable journal file and completes the pending operation record.
20
- */
21
- import { readFile, readdir, stat, writeFile, mkdir, rename } from 'node:fs/promises';
22
- import { existsSync } from 'node:fs';
23
- import os from 'node:os';
24
- import path from 'node:path';
25
- import { capture, pasteText, sendKeys, PROFILES } from '../../tmux/backend.js';
26
- import { Ai4aiStore } from '../../core/store.js';
27
- import { result } from '../../contract/validate.js';
28
- const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
29
- /** Status footer only: the transcript may itself contain words like "working". */
30
- const footer = (screen) => screen.split(/\r?\n/).slice(-16).join('\n');
31
- const running = (text) => /esc to interrupt|\bWorking \(|\bThinking \(|\bCompacting\b/.test(text);
32
- const rejected = (text) => /\/new is disabled while a task is in progress/i.test(text);
33
- const promptVisible = (screen) => /Ask Codex to do anything/i.test(screen) || /(?:^|\n)\s*›\s*$/m.test(screen.slice(-3000));
34
- const footerish = (line) => /Ask Codex to do anything|Context \d+% used|\bReady\b|for shortcuts|esc to interrupt|\bWorking \(|\bThinking \(/i.test(line);
35
- const transcript = (screen) => screen.split(/\r?\n/).map(line => line.trim()).filter(line => line.length >= 8 && !footerish(line));
36
- /** The fresh-conversation worktree dialog blocks every other interaction. */
37
- const worktreeDialog = (screen) => /Where should the new conversation run/i.test(screen);
38
- /** `/new` is selected by the first Enter and submitted by the second in 0.169. */
39
- const composerNew = (screen) => /(?:^|\n)\s*›\s*\/new\s*$/m.test(screen);
40
- /** A sustained idle frame: no running footer, no /new rejection, Ready or prompt. */
41
- const idleFrame = (screen) => {
42
- const foot = footer(screen);
43
- return !running(foot) && !rejected(screen.slice(-2000)) && (/Ready/i.test(foot) || promptVisible(screen));
44
- };
45
- async function main() {
46
- const file = process.argv[2];
47
- if (!file)
48
- throw new Error('payload path missing');
49
- const payload = JSON.parse(await readFile(file, 'utf8'));
50
- const { identity, request, operationId, marker, paneId } = payload;
51
- const profile = PROFILES.codex;
52
- const started = Date.parse(payload.startedAt);
53
- const journalDir = path.join(payload.home, '.ai4ai', 'codex', 'tui-restart');
54
- const journal = path.join(journalDir, `${operationId.replace(/[^A-Za-z0-9._-]/g, '_')}.json`);
55
- const writeJournal = async (value) => {
56
- await mkdir(journalDir, { recursive: true, mode: 0o700 });
57
- const temporary = `${journal}.${process.pid}.tmp`;
58
- await writeFile(temporary, JSON.stringify(value, null, 2) + '\n');
59
- await rename(temporary, journal);
60
- };
61
- const deadline = Date.now() + payload.timeoutMs;
62
- const fail = async (phase, reason, successor = null) => {
63
- await writeJournal({ format: 1, operationId, marker, phase, mechanism: 'restart', reason, successor });
64
- await complete(payload, result({ operation: 'handoff', operationId }, phase, reason, {
65
- durable: true, state: phase,
66
- ...(phase === 'failed' ? { unavailable: ['handoff.restart'], error: { code: 'handoff-timeout', message: reason } } : {}),
67
- }));
68
- };
69
- /** Wait for a sustained idle pane; the returned sample is the last good frame. */
70
- const waitIdle = async (until, samples = 6) => {
71
- let stable = 0;
72
- while (Date.now() < until) {
73
- const screen = await capture(paneId);
74
- // A dialog or a half-submitted /new blocks the prompt forever; clear it
75
- // instead of waiting for an idle frame that cannot occur.
76
- if (screen && worktreeDialog(screen)) {
77
- await sendKeys(paneId, ['Enter']);
78
- stable = 0;
79
- await sleep(1200);
80
- continue;
81
- }
82
- if (screen && composerNew(screen) && !running(footer(screen))) {
83
- await sendKeys(paneId, ['Enter']);
84
- stable = 0;
85
- await sleep(900);
86
- continue;
87
- }
88
- stable = screen && idleFrame(screen) ? stable + 1 : 0;
89
- if (stable >= samples) {
90
- // Settle: the agent may still be writing its closing message after the
91
- // footer first looks Ready. Re-check once more after a pause.
92
- await sleep(2000);
93
- const again = await capture(paneId);
94
- if (again && !worktreeDialog(again) && !composerNew(again) && idleFrame(again))
95
- return again;
96
- stable = 0;
97
- }
98
- await sleep(750);
99
- }
100
- return undefined;
101
- };
102
- const beforeIdle = await waitIdle(deadline);
103
- if (!beforeIdle)
104
- return fail('failed', 'The TUI pane did not become idle before the timeout');
105
- // Snapshot the rollouts that already exist: the source rollout contains the
106
- // material as a tool argument and must not satisfy delivery.
107
- const snapshot = await rolloutSnapshot(started);
108
- const beforeLines = transcript(beforeIdle).slice(-24);
109
- /** True when the pane switched to a fresh conversation: the old transcript is gone. */
110
- const paneCleared = (screen) => {
111
- const retained = beforeLines.filter(line => screen.includes(line)).length;
112
- const ratio = beforeLines.length ? retained / beforeLines.length : 1;
113
- return /Context 0% used/i.test(screen.slice(-1500)) || ratio < 0.3;
114
- };
115
- let sentNew = false;
116
- let applied = false;
117
- for (let attempt = 0; attempt < 4 && !applied; attempt++) {
118
- if (attempt > 0) {
119
- const idle = await waitIdle(Math.min(deadline, Date.now() + 120_000), 4);
120
- if (!idle)
121
- break;
122
- }
123
- sentNew = await sendKeys(paneId, profile.newChatKeys);
124
- if (!sentNew)
125
- break;
126
- // Codex selects the `/new` entry on the first Enter; the command runs on
127
- // the second one. Without it the composer just holds the literal text.
128
- await sleep(500);
129
- await sendKeys(paneId, ['Enter']);
130
- const until = Math.min(deadline, Date.now() + 120_000);
131
- while (Date.now() < until) {
132
- const now = await capture(paneId);
133
- if (!now) {
134
- await sleep(700);
135
- continue;
136
- }
137
- if (rejected(now.slice(-2500)))
138
- break; // retried after the pane is idle again
139
- if (worktreeDialog(now)) {
140
- await sendKeys(paneId, ['Enter']);
141
- await sleep(1200);
142
- continue;
143
- }
144
- if (composerNew(now) && !running(footer(now))) {
145
- await sendKeys(paneId, ['Enter']);
146
- await sleep(900);
147
- continue;
148
- }
149
- if (running(footer(now))) {
150
- await sleep(700);
151
- continue;
152
- }
153
- if (promptVisible(now) && paneCleared(now)) {
154
- applied = true;
155
- break;
156
- }
157
- await sleep(700);
158
- }
159
- }
160
- if (!sentNew)
161
- return fail('failed', 'The native /new command could not be delivered');
162
- if (!applied)
163
- return fail('failed', 'The native /new reset could not be confirmed; the material was not typed into the old conversation');
164
- const task = request.task ?? '';
165
- if (!task)
166
- return fail('failed', 'The handoff material is empty');
167
- // A fresh conversation may take a moment to finish redrawing; wait for its
168
- // idle prompt before pasting so the keys are not swallowed.
169
- if (!(await waitIdle(Math.min(deadline, Date.now() + 60_000), 2))) {
170
- return fail('unknown', 'The new Codex conversation did not reach an idle prompt');
171
- }
172
- let pasted = await pasteText(paneId, task);
173
- if (!pasted) {
174
- // Bracketed paste is unavailable in some tmux builds; the literal key path
175
- // is the compatibility fallback.
176
- pasted = await sendKeys(paneId, ['-l', '--', task]);
177
- await sleep(800);
178
- }
179
- await sleep(600);
180
- let submitted = false;
181
- for (let attempt = 0; attempt < 6 && !submitted; attempt++) {
182
- await sendKeys(paneId, ['C-m']);
183
- await sleep(1500);
184
- const now = await capture(paneId);
185
- // A running turn, or a composer that no longer holds the material, means
186
- // the submit was accepted.
187
- if (running(footer(now)))
188
- submitted = true;
189
- else if (!now.includes(task.slice(0, Math.min(40, task.length))))
190
- submitted = true;
191
- }
192
- // The durable native proof is a rollout created after the reset that holds
193
- // the material as a user message. Poll it: the successor turn starts
194
- // asynchronously after the submit.
195
- let delivered = false;
196
- const deliverUntil = Math.min(deadline, Date.now() + 120_000);
197
- while (Date.now() < deliverUntil && !delivered) {
198
- delivered = await rolloutHasMaterial(snapshot, started, task);
199
- if (!delivered)
200
- await sleep(2000);
201
- }
202
- const successor = await discoverThread(identity.workspace, snapshot, started);
203
- const visible = delivered && !/Where should the new conversation run/i.test(await capture(paneId));
204
- const phase = visible ? 'completed' : 'unknown';
205
- await writeJournal({
206
- format: 1, operationId, marker, phase, mechanism: 'restart',
207
- nativeEvidence: 'codex-tui:/new', successor,
208
- reason: visible
209
- ? 'Native /new reset the context in place; the material is visible as a user turn in the successor rollout'
210
- : 'The /new reset was applied in the pane, but delivery could not be confirmed from a successor rollout',
211
- });
212
- await complete(payload, result({ operation: 'handoff', operationId }, visible ? 'completed' : 'unknown', visible
213
- ? 'Codex /new reset the context in the same TUI; the task material was delivered as the next user turn'
214
- : 'Codex /new was applied but the material delivery was not confirmed', {
215
- durable: true,
216
- state: visible ? 'completed' : 'unknown',
217
- handoff: { phase: visible ? 'completed' : 'pending' },
218
- sessionId: successor?.session ?? identity.session,
219
- proof: {
220
- source: identity,
221
- successor: successor ?? { ...identity, generation: marker },
222
- mechanism: 'new-session',
223
- nativeEvidence: 'codex-tui:/new',
224
- },
225
- }));
226
- }
227
- /** Complete the pending operation record with the successor identity. */
228
- async function complete(payload, outcome) {
229
- try {
230
- const store = await Ai4aiStore.open(payload.home);
231
- await store.completePending(payload.identity, payload.operationId, outcome);
232
- }
233
- catch { /* the journal file remains the durable evidence */ }
234
- }
235
- /** Rollout files that existed before the reset, keyed by absolute path. */
236
- async function rolloutSnapshot(started) {
237
- const files = await rolloutFiles(started);
238
- return new Set(files.map(entry => entry.file));
239
- }
240
- async function rolloutFiles(started) {
241
- const root = path.join(process.env.CODEX_HOME || path.join(os.homedir(), '.codex'), 'sessions');
242
- if (!existsSync(root))
243
- return [];
244
- const files = [];
245
- for (let offset = 0; offset < 2; offset++) {
246
- const date = new Date(started - offset * 86_400_000);
247
- const directory = path.join(root, String(date.getFullYear()), String(date.getMonth() + 1).padStart(2, '0'), String(date.getDate()).padStart(2, '0'));
248
- for (const entry of await readdir(directory, { withFileTypes: true }).catch(() => [])) {
249
- if (!entry.isFile() || !entry.name.endsWith('.jsonl'))
250
- continue;
251
- const file = path.join(directory, entry.name);
252
- const info = await stat(file).catch(() => undefined);
253
- if (info && info.mtimeMs >= started - 2000)
254
- files.push({ file, mtime: info.mtimeMs });
255
- }
256
- }
257
- return files;
258
- }
259
- /** True when a rollout created after the reset holds the material as a user message. */
260
- async function rolloutHasMaterial(snapshot, started, task) {
261
- const needle = task.slice(0, Math.min(40, task.length));
262
- if (!needle)
263
- return false;
264
- for (const entry of await rolloutFiles(started)) {
265
- if (snapshot.has(entry.file))
266
- continue;
267
- const text = await readFile(entry.file, 'utf8').catch(() => '');
268
- if (!text.includes(needle))
269
- continue;
270
- for (const line of text.split(/\r?\n/)) {
271
- if (!line.includes(needle))
272
- continue;
273
- try {
274
- const row = JSON.parse(line);
275
- const item = row?.payload ?? row;
276
- const role = item?.role;
277
- const content = item?.content;
278
- const parts = Array.isArray(content) ? content : [];
279
- const isUser = role === 'user'
280
- || (row?.type === 'event_msg' && typeof item?.message === 'string' && row?.payload?.type === 'user_message')
281
- || parts.some((part) => part?.type === 'input_text' || part?.type === 'text');
282
- if (isUser && !/tool_call|function_call/.test(String(row?.type ?? '')))
283
- return true;
284
- }
285
- catch { /* not a JSON row */ }
286
- }
287
- }
288
- return false;
289
- }
290
- /** Newest rollout for this workspace created after the handoff, excluding pre-existing files. */
291
- async function discoverThread(workspace, snapshot, started) {
292
- const candidates = (await rolloutFiles(started)).filter(entry => !snapshot.has(entry.file));
293
- candidates.sort((a, b) => b.mtime - a.mtime);
294
- for (const candidate of candidates) {
295
- try {
296
- const head = (await readFile(candidate.file, 'utf8')).split(/\r?\n/).slice(0, 5).map(line => {
297
- try {
298
- return JSON.parse(line);
299
- }
300
- catch {
301
- return undefined;
302
- }
303
- }).filter(Boolean);
304
- const meta = head.find(row => row.type === 'session_meta')?.payload;
305
- const id = typeof meta?.session_id === 'string' ? meta.session_id : typeof meta?.id === 'string' ? meta.id : undefined;
306
- if (!id)
307
- continue;
308
- if (typeof meta?.cwd === 'string' && meta.cwd.replace(/[\\/]+$/, '') !== workspace.replace(/[\\/]+$/, ''))
309
- continue;
310
- return { harness: 'codex', workspace, surface: 'tui', session: id, generation: id, agent: 'main' };
311
- }
312
- catch { /* try the next candidate */ }
313
- }
314
- return null;
315
- }
316
- main().catch(async (error) => {
317
- try {
318
- const file = process.argv[2];
319
- if (file) {
320
- const payload = JSON.parse(await readFile(file, 'utf8'));
321
- const journalDir = path.join(payload.home, '.ai4ai', 'codex', 'tui-restart');
322
- await mkdir(journalDir, { recursive: true, mode: 0o700 });
323
- await writeFile(path.join(journalDir, `${payload.operationId}.json`), JSON.stringify({
324
- format: 1, operationId: payload.operationId, phase: 'failed', mechanism: 'restart', reason: String(error?.message ?? error),
325
- }, null, 2) + '\n');
326
- }
327
- }
328
- catch { /* best effort */ }
329
- process.exit(1);
330
- });
@@ -1,55 +0,0 @@
1
- export interface TmuxPane {
2
- paneId: string;
3
- pid: number;
4
- command: string;
5
- session: string;
6
- active: boolean;
7
- path: string;
8
- }
9
- export interface TmuxProfile {
10
- harness: 'codex' | 'claude-code' | 'opencode';
11
- commandPattern: RegExp;
12
- idlePattern: RegExp;
13
- busyPattern: RegExp;
14
- newChatKeys: string[];
15
- }
16
- export interface TmuxResult {
17
- status: 'applied' | 'unsupported' | 'failed' | 'unknown';
18
- strategy: 'tmux';
19
- experimental: true;
20
- reason: string;
21
- paneId?: string;
22
- }
23
- export declare const PROFILES: Record<TmuxProfile['harness'], TmuxProfile>;
24
- declare const equalPath: (a: string, b: string) => boolean;
25
- /** tmux is unavailable on native Windows by design. */
26
- export declare function tmuxAvailable(): Promise<boolean>;
27
- export declare function listPanes(): Promise<TmuxPane[]>;
28
- /** Walk the process ancestry to find the owning tmux pane. */
29
- export declare function paneForProcess(pid: number): Promise<TmuxPane | undefined>;
30
- /** Fallback attribution when the harness runs behind a managed daemon: match the pane's harness command and workspace. */
31
- export declare function paneForWorkspace(harness: TmuxProfile['harness'], workspace: string): Promise<TmuxPane | undefined>;
32
- export declare function capture(paneId: string): Promise<string>;
33
- export declare function sendKeys(paneId: string, keys: string[]): Promise<boolean>;
34
- /**
35
- * Deliver arbitrary text without key-name interpretation. `send-keys` treats
36
- * arguments such as "Enter" or "C-m" as key names, so material that happens to
37
- * contain them would be corrupted. A buffer plus bracketed paste is the same
38
- * path a human paste uses: embedded newlines stay in the composer instead of
39
- * submitting the turn early.
40
- */
41
- export declare function pasteText(paneId: string, text: string): Promise<boolean>;
42
- /**
43
- * Experimental same-window handoff by key injection.
44
- *
45
- * Safety is enforced by preconditions, not prompts: the pane must run the
46
- * expected harness, must be idle, and a single attempt is made. Any doubt
47
- * returns a structured refusal and never retries.
48
- */
49
- export declare function tmuxHandoff(input: {
50
- harness: TmuxProfile['harness'];
51
- paneId?: string;
52
- pid?: number;
53
- task?: string;
54
- }): Promise<TmuxResult>;
55
- export { equalPath };
@@ -1,161 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
- import { readFile } from 'node:fs/promises';
3
- export const PROFILES = {
4
- codex: {
5
- harness: 'codex', commandPattern: /^(codex|node|codex-cli)$/i,
6
- idlePattern: /(?:^|\n)\s*(?:›|>|codex>)\s*$/i,
7
- busyPattern: /(?:esc to interrupt|working|thinking|⏳|running)/i,
8
- newChatKeys: ['/new', 'Enter'],
9
- },
10
- 'claude-code': {
11
- harness: 'claude-code', commandPattern: /^(claude|node)$/i,
12
- idlePattern: /(?:^|\n)\s*(?:>|❯)\s*$/i,
13
- busyPattern: /(?:esc to interrupt|Working|Thinking)/i,
14
- newChatKeys: ['/clear', 'Enter'],
15
- },
16
- opencode: {
17
- harness: 'opencode', commandPattern: /^(opencode|node)$/i,
18
- idlePattern: /(?:^|\n)\s*(?:>|›)\s*$/i,
19
- busyPattern: /(?:esc to interrupt|working)/i,
20
- newChatKeys: ['/new', 'Enter'],
21
- },
22
- };
23
- function run(command, args, timeoutMs = 10000) {
24
- return new Promise(resolve => {
25
- let child;
26
- try {
27
- child = spawn(command, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
28
- }
29
- catch (error) {
30
- resolve({ code: null, stdout: '', stderr: String(error) });
31
- return;
32
- }
33
- let stdout = '', stderr = '';
34
- const timer = setTimeout(() => { try {
35
- child.kill('SIGKILL');
36
- }
37
- catch { /* gone */ } }, timeoutMs);
38
- child.stdout.on('data', data => { stdout = (stdout + String(data)).slice(-65536); });
39
- child.stderr.on('data', data => { stderr = (stderr + String(data)).slice(-16384); });
40
- child.once('error', error => { clearTimeout(timer); resolve({ code: null, stdout, stderr: error.message }); });
41
- child.once('close', code => { clearTimeout(timer); resolve({ code, stdout, stderr }); });
42
- });
43
- }
44
- const socketArgs = () => {
45
- const socket = process.env.AI4AI_TMUX_SOCKET || process.env.TMUX_SOCKET;
46
- return socket ? ['-S', socket] : [];
47
- };
48
- const equalPath = (a, b) => process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
49
- /** tmux is unavailable on native Windows by design. */
50
- export async function tmuxAvailable() {
51
- if (process.platform === 'win32')
52
- return false;
53
- const result = await run(process.env.AI4AI_TMUX_BIN || 'tmux', [...socketArgs(), '-V']);
54
- return result.code === 0;
55
- }
56
- export async function listPanes() {
57
- const result = await run(process.env.AI4AI_TMUX_BIN || 'tmux', [...socketArgs(), 'list-panes', '-a', '-F', '#{pane_id}|#{pane_pid}|#{pane_current_command}|#{session_name}|#{window_active}|#{pane_current_path}']);
58
- if (result.code !== 0)
59
- return [];
60
- return result.stdout.split('\n').filter(Boolean).map(line => {
61
- const [paneId, pid, command, session, active, panePath] = line.split('|');
62
- return { paneId: paneId, pid: Number(pid), command: command, session: session, active: active === '1', path: panePath ?? '' };
63
- }).filter(pane => pane.paneId?.startsWith('%') && Number.isSafeInteger(pane.pid));
64
- }
65
- async function parentPid(pid) {
66
- try {
67
- const stat = await readFile(`/proc/${pid}/stat`, 'utf8');
68
- const close = stat.lastIndexOf(')');
69
- const fields = stat.slice(close + 2).split(' ');
70
- const ppid = Number(fields[1]);
71
- return Number.isSafeInteger(ppid) && ppid > 0 ? ppid : undefined;
72
- }
73
- catch {
74
- return undefined;
75
- }
76
- }
77
- /** Walk the process ancestry to find the owning tmux pane. */
78
- export async function paneForProcess(pid) {
79
- const panes = await listPanes();
80
- if (!panes.length)
81
- return undefined;
82
- const byPid = new Map(panes.map(pane => [pane.pid, pane]));
83
- let current = pid;
84
- for (let depth = 0; depth < 64 && current; depth++) {
85
- const pane = byPid.get(current);
86
- if (pane)
87
- return pane;
88
- current = await parentPid(current);
89
- }
90
- return undefined;
91
- }
92
- /** Fallback attribution when the harness runs behind a managed daemon: match the pane's harness command and workspace. */
93
- export async function paneForWorkspace(harness, workspace) {
94
- const profile = PROFILES[harness];
95
- const panes = (await listPanes()).filter(pane => profile.commandPattern.test(pane.command) && equalPath(pathNormalize(pane.path), pathNormalize(workspace)));
96
- return panes.length === 1 ? panes[0] : undefined;
97
- }
98
- const pathNormalize = (value) => value.replace(/[\\/]+$/, '');
99
- export async function capture(paneId) {
100
- const result = await run(process.env.AI4AI_TMUX_BIN || 'tmux', [...socketArgs(), 'capture-pane', '-p', '-t', paneId, '-S', '-40']);
101
- return result.code === 0 ? result.stdout : '';
102
- }
103
- export async function sendKeys(paneId, keys) {
104
- const result = await run(process.env.AI4AI_TMUX_BIN || 'tmux', [...socketArgs(), 'send-keys', '-t', paneId, ...keys]);
105
- return result.code === 0;
106
- }
107
- /**
108
- * Deliver arbitrary text without key-name interpretation. `send-keys` treats
109
- * arguments such as "Enter" or "C-m" as key names, so material that happens to
110
- * contain them would be corrupted. A buffer plus bracketed paste is the same
111
- * path a human paste uses: embedded newlines stay in the composer instead of
112
- * submitting the turn early.
113
- */
114
- export async function pasteText(paneId, text) {
115
- const bin = process.env.AI4AI_TMUX_BIN || 'tmux';
116
- const buffer = await run(bin, [...socketArgs(), 'set-buffer', '--', text]);
117
- if (buffer.code !== 0)
118
- return false;
119
- const paste = await run(bin, [...socketArgs(), 'paste-buffer', '-p', '-d', '-t', paneId]);
120
- return paste.code === 0;
121
- }
122
- /**
123
- * Experimental same-window handoff by key injection.
124
- *
125
- * Safety is enforced by preconditions, not prompts: the pane must run the
126
- * expected harness, must be idle, and a single attempt is made. Any doubt
127
- * returns a structured refusal and never retries.
128
- */
129
- export async function tmuxHandoff(input) {
130
- if (!(await tmuxAvailable()))
131
- return { status: 'unsupported', strategy: 'tmux', experimental: true, reason: 'tmux is not available on this platform' };
132
- const profile = PROFILES[input.harness];
133
- const pane = input.paneId
134
- ? (await listPanes()).find(candidate => candidate.paneId === input.paneId)
135
- : input.pid ? await paneForProcess(input.pid) : undefined;
136
- if (!pane)
137
- return { status: 'unknown', strategy: 'tmux', experimental: true, reason: 'No tmux pane could be attributed to this session' };
138
- if (!profile.commandPattern.test(pane.command)) {
139
- return { status: 'unsupported', strategy: 'tmux', experimental: true, paneId: pane.paneId, reason: `Pane command ${pane.command} does not match the ${input.harness} profile` };
140
- }
141
- const screen = await capture(pane.paneId);
142
- if (!screen)
143
- return { status: 'unknown', strategy: 'tmux', experimental: true, paneId: pane.paneId, reason: 'Pane content could not be captured' };
144
- if (profile.busyPattern.test(screen.slice(-2000))) {
145
- return { status: 'failed', strategy: 'tmux', experimental: true, paneId: pane.paneId, reason: 'Pane is busy; a single attempt is not made while the harness is running' };
146
- }
147
- if (!profile.idlePattern.test(screen.slice(-2000))) {
148
- return { status: 'failed', strategy: 'tmux', experimental: true, paneId: pane.paneId, reason: 'Pane is not at an idle prompt' };
149
- }
150
- if (!(await sendKeys(pane.paneId, profile.newChatKeys))) {
151
- return { status: 'unknown', strategy: 'tmux', experimental: true, paneId: pane.paneId, reason: 'Key injection returned no confirmation' };
152
- }
153
- if (input.task) {
154
- // Deliver the task material as a separate, visible turn rather than
155
- // smuggling it into the command line.
156
- await new Promise(resolve => setTimeout(resolve, 750));
157
- await sendKeys(pane.paneId, [input.task, 'Enter']);
158
- }
159
- return { status: 'applied', strategy: 'tmux', experimental: true, paneId: pane.paneId, reason: 'Keys injected once; the harness owns the resulting native effect' };
160
- }
161
- export { equalPath };
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};