ai4ai 0.0.3 → 0.0.6

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 (184) 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 +254 -107
  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 +12 -4
  33. package/claude-plugin/dist/adapters/opencode/plugin.d.ts +3 -5
  34. package/claude-plugin/dist/adapters/opencode/plugin.js +3 -292
  35. package/claude-plugin/dist/adapters/opencode/setup.d.ts +9 -0
  36. package/claude-plugin/dist/adapters/opencode/setup.js +350 -0
  37. package/claude-plugin/dist/adapters/supervisor.js +64 -20
  38. package/claude-plugin/dist/adapters/types.d.ts +7 -0
  39. package/claude-plugin/dist/contract/schema.d.ts +8 -17
  40. package/claude-plugin/dist/contract/schema.js +3 -4
  41. package/claude-plugin/dist/contract/states.d.ts +11 -0
  42. package/claude-plugin/dist/contract/states.js +9 -0
  43. package/claude-plugin/dist/contract/types.d.ts +3 -3
  44. package/claude-plugin/dist/contract/validate.js +24 -14
  45. package/claude-plugin/dist/contract/version.d.ts +1 -1
  46. package/claude-plugin/dist/contract/version.js +1 -1
  47. package/claude-plugin/dist/core/dsh-selection.d.ts +43 -0
  48. package/claude-plugin/dist/core/dsh-selection.js +78 -0
  49. package/claude-plugin/dist/core/handoff.d.ts +42 -0
  50. package/claude-plugin/dist/core/handoff.js +63 -0
  51. package/claude-plugin/dist/core/index.d.ts +2 -0
  52. package/claude-plugin/dist/core/index.js +1 -0
  53. package/claude-plugin/dist/core/operations.js +33 -1
  54. package/claude-plugin/dist/core/retained-input.d.ts +24 -0
  55. package/claude-plugin/dist/core/retained-input.js +50 -0
  56. package/claude-plugin/dist/core/session-probe.js +11 -22
  57. package/claude-plugin/dist/core/store.d.ts +8 -3
  58. package/claude-plugin/dist/core/store.js +17 -3
  59. package/claude-plugin/request-schema.json +1 -2
  60. package/dist/adapters/claude/adapter.d.ts +10 -1
  61. package/dist/adapters/claude/adapter.js +35 -10
  62. package/dist/adapters/claude/journal.d.ts +8 -0
  63. package/dist/adapters/claude/journal.js +4 -1
  64. package/dist/adapters/claude/plugin.js +254 -107
  65. package/dist/adapters/claude/worker.js +30 -8
  66. package/dist/adapters/codex/adapter.d.ts +26 -19
  67. package/dist/adapters/codex/adapter.js +283 -187
  68. package/dist/adapters/codex/app-server.js +1 -1
  69. package/dist/adapters/codex/control.d.ts +36 -1
  70. package/dist/adapters/codex/control.js +74 -4
  71. package/dist/adapters/codex/native-handoff.d.ts +60 -0
  72. package/dist/adapters/codex/native-handoff.js +138 -0
  73. package/dist/adapters/codex/runner.js +35 -32
  74. package/dist/adapters/codex/tui-daemon-watch.js +60 -49
  75. package/dist/adapters/declarations.d.ts +0 -1
  76. package/dist/adapters/declarations.js +0 -1
  77. package/dist/adapters/dsh/adapter.d.ts +39 -2
  78. package/dist/adapters/dsh/adapter.js +164 -37
  79. package/dist/adapters/dsh/plugin.d.ts +3 -1
  80. package/dist/adapters/dsh/plugin.js +33 -22
  81. package/dist/adapters/executors.d.ts +25 -2
  82. package/dist/adapters/executors.js +58 -4
  83. package/dist/adapters/external.d.ts +21 -0
  84. package/dist/adapters/external.js +128 -18
  85. package/dist/adapters/opencode/adapter.d.ts +13 -2
  86. package/dist/adapters/opencode/adapter.js +53 -10
  87. package/dist/adapters/opencode/journal.d.ts +2 -0
  88. package/dist/adapters/opencode/journal.js +12 -4
  89. package/dist/adapters/opencode/plugin.d.ts +3 -5
  90. package/dist/adapters/opencode/plugin.js +3 -292
  91. package/dist/adapters/opencode/setup.d.ts +9 -0
  92. package/dist/adapters/opencode/setup.js +350 -0
  93. package/dist/adapters/supervisor.js +64 -20
  94. package/dist/adapters/types.d.ts +7 -0
  95. package/dist/contract/schema.d.ts +8 -17
  96. package/dist/contract/schema.js +3 -4
  97. package/dist/contract/states.d.ts +11 -0
  98. package/dist/contract/states.js +9 -0
  99. package/dist/contract/types.d.ts +3 -3
  100. package/dist/contract/validate.js +24 -14
  101. package/dist/contract/version.d.ts +1 -1
  102. package/dist/contract/version.js +1 -1
  103. package/dist/core/dsh-selection.d.ts +43 -0
  104. package/dist/core/dsh-selection.js +78 -0
  105. package/dist/core/handoff.d.ts +42 -0
  106. package/dist/core/handoff.js +63 -0
  107. package/dist/core/index.d.ts +2 -0
  108. package/dist/core/index.js +1 -0
  109. package/dist/core/operations.js +33 -1
  110. package/dist/core/retained-input.d.ts +24 -0
  111. package/dist/core/retained-input.js +50 -0
  112. package/dist/core/session-probe.js +11 -22
  113. package/dist/core/store.d.ts +8 -3
  114. package/dist/core/store.js +17 -3
  115. package/docs/contract.md +31 -15
  116. package/opencode-plugin/dist/adapters/claude/adapter.d.ts +10 -1
  117. package/opencode-plugin/dist/adapters/claude/adapter.js +35 -10
  118. package/opencode-plugin/dist/adapters/claude/journal.d.ts +8 -0
  119. package/opencode-plugin/dist/adapters/claude/journal.js +4 -1
  120. package/opencode-plugin/dist/adapters/claude/plugin.js +254 -107
  121. package/opencode-plugin/dist/adapters/claude/worker.js +30 -8
  122. package/opencode-plugin/dist/adapters/codex/adapter.d.ts +26 -19
  123. package/opencode-plugin/dist/adapters/codex/adapter.js +283 -187
  124. package/opencode-plugin/dist/adapters/codex/app-server.js +1 -1
  125. package/opencode-plugin/dist/adapters/codex/control.d.ts +36 -1
  126. package/opencode-plugin/dist/adapters/codex/control.js +74 -4
  127. package/opencode-plugin/dist/adapters/codex/native-handoff.d.ts +60 -0
  128. package/opencode-plugin/dist/adapters/codex/native-handoff.js +138 -0
  129. package/opencode-plugin/dist/adapters/codex/runner.js +35 -32
  130. package/opencode-plugin/dist/adapters/codex/tui-daemon-watch.js +60 -49
  131. package/opencode-plugin/dist/adapters/declarations.d.ts +0 -1
  132. package/opencode-plugin/dist/adapters/declarations.js +0 -1
  133. package/opencode-plugin/dist/adapters/dsh/adapter.d.ts +39 -2
  134. package/opencode-plugin/dist/adapters/dsh/adapter.js +164 -37
  135. package/opencode-plugin/dist/adapters/dsh/plugin.d.ts +3 -1
  136. package/opencode-plugin/dist/adapters/dsh/plugin.js +33 -22
  137. package/opencode-plugin/dist/adapters/executors.d.ts +25 -2
  138. package/opencode-plugin/dist/adapters/executors.js +58 -4
  139. package/opencode-plugin/dist/adapters/external.d.ts +21 -0
  140. package/opencode-plugin/dist/adapters/external.js +128 -18
  141. package/opencode-plugin/dist/adapters/opencode/adapter.d.ts +13 -2
  142. package/opencode-plugin/dist/adapters/opencode/adapter.js +53 -10
  143. package/opencode-plugin/dist/adapters/opencode/journal.d.ts +2 -0
  144. package/opencode-plugin/dist/adapters/opencode/journal.js +12 -4
  145. package/opencode-plugin/dist/adapters/opencode/plugin.d.ts +3 -5
  146. package/opencode-plugin/dist/adapters/opencode/plugin.js +3 -292
  147. package/opencode-plugin/dist/adapters/opencode/setup.d.ts +9 -0
  148. package/opencode-plugin/dist/adapters/opencode/setup.js +350 -0
  149. package/opencode-plugin/dist/adapters/supervisor.js +64 -20
  150. package/opencode-plugin/dist/adapters/types.d.ts +7 -0
  151. package/opencode-plugin/dist/contract/schema.d.ts +8 -17
  152. package/opencode-plugin/dist/contract/schema.js +3 -4
  153. package/opencode-plugin/dist/contract/states.d.ts +11 -0
  154. package/opencode-plugin/dist/contract/states.js +9 -0
  155. package/opencode-plugin/dist/contract/types.d.ts +3 -3
  156. package/opencode-plugin/dist/contract/validate.js +24 -14
  157. package/opencode-plugin/dist/contract/version.d.ts +1 -1
  158. package/opencode-plugin/dist/contract/version.js +1 -1
  159. package/opencode-plugin/dist/core/dsh-selection.d.ts +43 -0
  160. package/opencode-plugin/dist/core/dsh-selection.js +78 -0
  161. package/opencode-plugin/dist/core/handoff.d.ts +42 -0
  162. package/opencode-plugin/dist/core/handoff.js +63 -0
  163. package/opencode-plugin/dist/core/index.d.ts +2 -0
  164. package/opencode-plugin/dist/core/index.js +1 -0
  165. package/opencode-plugin/dist/core/operations.js +33 -1
  166. package/opencode-plugin/dist/core/retained-input.d.ts +24 -0
  167. package/opencode-plugin/dist/core/retained-input.js +50 -0
  168. package/opencode-plugin/dist/core/session-probe.js +11 -22
  169. package/opencode-plugin/dist/core/store.d.ts +8 -3
  170. package/opencode-plugin/dist/core/store.js +17 -3
  171. package/opencode-plugin/package.json +1 -1
  172. package/package.json +1 -1
  173. package/claude-plugin/dist/adapters/codex/tui-restart-watch.d.ts +0 -2
  174. package/claude-plugin/dist/adapters/codex/tui-restart-watch.js +0 -330
  175. package/claude-plugin/dist/tmux/backend.d.ts +0 -55
  176. package/claude-plugin/dist/tmux/backend.js +0 -161
  177. package/dist/adapters/codex/tui-restart-watch.d.ts +0 -2
  178. package/dist/adapters/codex/tui-restart-watch.js +0 -330
  179. package/dist/tmux/backend.d.ts +0 -55
  180. package/dist/tmux/backend.js +0 -161
  181. package/opencode-plugin/dist/adapters/codex/tui-restart-watch.d.ts +0 -2
  182. package/opencode-plugin/dist/adapters/codex/tui-restart-watch.js +0 -330
  183. package/opencode-plugin/dist/tmux/backend.d.ts +0 -55
  184. package/opencode-plugin/dist/tmux/backend.js +0 -161
@@ -7,10 +7,10 @@ import { fileURLToPath } from 'node:url';
7
7
  import { randomUUID } from 'node:crypto';
8
8
  import { ExternalExecutorAdapter, contextFromUsage } from '../external.js';
9
9
  import { handoffMode, handoffOutcome } from '../../contract/states.js';
10
- import { executorDir } from '../executors.js';
10
+ import { executorDir, pidAlive } from '../executors.js';
11
11
  import { declaration } from '../declarations.js';
12
- import { paneForProcess, paneForWorkspace, tmuxAvailable } from '../../tmux/backend.js';
13
- import { CodexDaemon, daemonSocket, listThreads } from './control.js';
12
+ import { CodexDaemon, daemonSocket, resolveTuiThread } from './control.js';
13
+ import { legacyProofMechanism, sameSessionProof } from '../../core/handoff.js';
14
14
  import { codexSessionUsage } from '../../core/session-probe.js';
15
15
  import { probeCodexConfig } from '../../core/config-probe.js';
16
16
  import { firstVerified, verifiedText, verifiedTokens, verifiedWindow } from '../../core/ladder.js';
@@ -19,9 +19,10 @@ import { firstVerified, verifiedText, verifiedTokens, verifiedWindow } from '../
19
19
  *
20
20
  * Carriers are per-executor `codex app-server` processes driven by
21
21
  * `runner.js`; the protocol is upstream-experimental. Same-window handoff uses
22
- * the local app-server daemon that the interactive TUI already runs: compact the
23
- * live thread, then start the successor turn in the same thread. tmux remains an
24
- * experimental fallback for sessions without a reachable daemon.
22
+ * the local app-server daemon that the interactive TUI already runs: revert the
23
+ * live thread to its start, then start the material turn in the same thread.
24
+ * There is no tmux/new-thread fallback: a session without a reachable daemon
25
+ * returns a structured `codex-no-daemon` boundary.
25
26
  */
26
27
  /** Resolve a harness binary against the caller's PATH so detached carriers do not depend on the supervisor PATH. */
27
28
  function resolveBinary(name) {
@@ -73,23 +74,50 @@ export class CodexAdapter extends ExternalExecutorAdapter {
73
74
  capabilities(os) {
74
75
  const linux = os === 'linux';
75
76
  const mac = os === 'darwin';
77
+ // macOS authentication is the opencode-go provider via OPENCODE_API_KEY,
78
+ // not `codex login`. Codex 0.170.0 was exercised on macOS: go/no-go
79
+ // (thread/revert, old secret UNKNOWN, no compact), a headless restart
80
+ // handoff and a TUI restart handoff all completed in the same thread. The
81
+ // native compact opt-in was not exercised on macOS, so it is not claimed
82
+ // there.
76
83
  const reason = linux
77
- ? 'Linux headless spawn/status and restart handoff (new app-server thread + material) were verified with a real app-server process; TUI restart uses the pane\'s native /new command in tmux or the native new_context tool on a bare TUI; compact remains available. The app-server protocol is upstream-experimental.'
84
+ ? 'Linux headless spawn/status and the same-thread restart handoff were verified with a real app-server: thread/revert to the thread start, then the material turn in the same thread id with no summary call. TUI restart uses the shared daemon and the same revert; compact is the explicit native-summary opt-in. The app-server protocol is upstream-experimental.'
78
85
  : mac
79
- ? 'macOS headless spawn/status and restart handoff (new app-server thread + material) run in the same app-server process; TUI restart uses /new in tmux or the native new_context tool on a bare TUI, with compact available explicitly. The app-server protocol is upstream-experimental.'
86
+ ? 'macOS was exercised with Codex 0.170.0 using the opencode-go provider from the environment (not `codex login`): thread/revert preserved the thread, the headless handoff and the TUI handoff both completed in the same thread, and the old codeword was not in the replaced live context. Native compact was not exercised on macOS, so only restart is claimed. The app-server protocol is upstream-experimental.'
80
87
  : 'Codex is supported via WSL on Windows; native Windows harness integration is out of scope and was not exercised.';
81
88
  const level = linux || mac ? 'supported' : 'not-tested';
89
+ const modes = (linux ? ['restart', 'compact'] : ['restart']);
82
90
  const common = {
83
- handoff: { availability: level, modes: ['restart', 'compact'], tmuxFallback: 'experimental' },
91
+ handoff: { availability: level, modes },
84
92
  spawn: { availability: level, maxConcurrent: 4 },
85
93
  status: { availability: level, model: 'not-tested', reasoningEffort: 'unsupported', context: level, percentSource: 'derived' },
86
- ...(linux || mac ? { evidence: `matrix:codex/${os}/2026-11-18` } : {}),
94
+ ...(linux || mac ? { evidence: `matrix:codex/${os}/2026-11-21` } : {}),
87
95
  };
88
96
  return [
89
- declaration({ harness: 'codex', os, interface: 'headless', reason, experimental: ['app-server', 'tmux-fallback'], ...common }),
90
- declaration({ harness: 'codex', os, interface: 'tui', reason, experimental: ['app-server', 'tmux-fallback'], ...common }),
97
+ declaration({ harness: 'codex', os, interface: 'headless', reason, experimental: ['app-server'], ...common }),
98
+ declaration({ harness: 'codex', os, interface: 'tui', reason, experimental: ['app-server'], ...common }),
91
99
  ];
92
100
  }
101
+ /**
102
+ * A detached Codex executor inherits the profile model and reasoning effort:
103
+ * the runner starts a thread without per-request overrides. Refuse them
104
+ * loudly instead of accepting values that would never reach the harness.
105
+ */
106
+ async spawn(request, ctx) {
107
+ const unavailable = [];
108
+ if (request.model !== undefined)
109
+ unavailable.push('spawn.model');
110
+ if (request.reasoningEffort !== undefined)
111
+ unavailable.push('spawn.reasoningEffort');
112
+ if (unavailable.length) {
113
+ return {
114
+ status: 'unsupported',
115
+ reason: `codex detached executors inherit the profile model and reasoning effort; overrides are not applied (${unavailable.join(', ')}); configure the Codex profile instead and omit them`,
116
+ unavailable,
117
+ };
118
+ }
119
+ return super.spawn(request, ctx);
120
+ }
93
121
  async carrier(request, ctx, _executorId, resumeSessionId) {
94
122
  if (process.platform === 'darwin' && process.env.CODEX_SANDBOX && process.env.CODEX_SANDBOX !== 'none') {
95
123
  throw new Error('The caller runs inside the Codex seatbelt sandbox, which confines every descendant process; a detached executor cannot write its app-server runtime outside the workspace. '
@@ -119,18 +147,18 @@ export class CodexAdapter extends ExternalExecutorAdapter {
119
147
  /**
120
148
  * Same-window handoff through the local app-server daemon.
121
149
  *
122
- * The daemon owns the TUI's live thread. Compacting it and starting the
123
- * successor turn through the daemon changes what the user sees in the same
124
- * window: a compaction marker followed by the handoff task as the next turn.
125
- * When no daemon or live thread is reachable, the experimental tmux fallback
126
- * is attempted once.
150
+ * The daemon owns the TUI's live thread. Reverting it and starting the
151
+ * material turn through the daemon changes what the user sees in the same
152
+ * window: a reset history followed by the handoff task as the next turn.
153
+ * When no daemon or live thread is reachable, the call fails as the
154
+ * structured `codex-no-daemon` host boundary; no new thread is created.
127
155
  */
128
156
  async handoff(request, ctx) {
129
157
  if (request.target !== 'self') {
130
158
  return { status: 'unsupported', reason: 'Codex handoff targets the caller self only; detached executors cannot replace their context in place', unavailable: ['handoff.executor'] };
131
159
  }
132
160
  if (request.surface !== undefined && request.surface !== 'preserve') {
133
- return { status: 'unsupported', reason: 'Codex handoff preserves the TUI surface; cross-surface handoff is not implemented', unavailable: ['handoff.crossSurface'] };
161
+ return { status: 'unsupported', reason: 'Codex handoff preserves the surface; cross-surface handoff is not implemented', unavailable: ['handoff.crossSurface'] };
134
162
  }
135
163
  const mode = handoffMode(request.mode);
136
164
  // A detached Codex executor is itself an app-server thread. It owns its
@@ -139,145 +167,139 @@ export class CodexAdapter extends ExternalExecutorAdapter {
139
167
  if (ctx.identity.surface === 'headless' || ctx.executorId !== undefined) {
140
168
  return headlessSelfHandoff(request, ctx, mode);
141
169
  }
142
- if (mode === 'restart')
143
- return this.tuiRestart(request, ctx);
144
- const socket = await daemonSocket(process.env.AI4AI_CODEX_BIN || 'codex');
145
- if (socket) {
146
- let daemon;
147
- try {
148
- daemon = await CodexDaemon.connect(socket);
149
- }
150
- catch {
151
- daemon = undefined;
152
- }
153
- if (daemon) {
154
- let mutated = false;
155
- try {
156
- return await nativeHandoff(daemon, request, ctx, () => { mutated = true; });
157
- }
158
- catch (error) {
159
- if (error instanceof NoLiveThread) {
160
- // Nothing native was changed; there is no safe fallback for compact.
161
- }
162
- else {
163
- return {
164
- status: mutated ? 'unknown' : 'failed',
165
- reason: `Codex native handoff ${mutated ? 'started but could not be confirmed' : 'failed'}: ${error instanceof Error ? error.message : 'unknown error'}`,
166
- durable: mutated,
167
- state: mutated ? 'unknown' : 'failed',
168
- unavailable: ['handoff.native'],
169
- error: { code: 'codex-native-handoff', message: error instanceof Error ? error.message : 'unknown error' },
170
- };
171
- }
172
- }
173
- finally {
174
- daemon.close();
175
- }
176
- }
177
- }
178
- return {
179
- status: 'unsupported',
180
- reason: 'No live Codex app-server daemon or TUI thread was found for a compact handoff; restart is the default and uses the native /new path',
181
- unavailable: ['handoff.native'],
182
- };
170
+ return mode === 'compact' ? this.tuiCompact(request, ctx) : this.tuiRestart(request, ctx);
183
171
  }
184
172
  /**
185
- * Native TUI restart. The visible terminal is the only surface the user
186
- * sees, so ai4ai drives that terminal's own `/new` command (a documented
187
- * harness action) and then delivers the material as the next turn. The
188
- * source turn is still running when this call is made, so a detached watcher
189
- * applies the reset at the turn boundary. The process, pane and host channel
190
- * are never replaced.
173
+ * Re-query a pending handoff written by the headless runner or the detached
174
+ * TUI watcher. Without this, the same operationId would return the original
175
+ * pending result forever even after the native side completed.
176
+ */
177
+ async reconcileHandoff(request, ctx) {
178
+ return reconcileCodexHandoff(request, ctx);
179
+ }
180
+ /**
181
+ * Native TUI restart. The TUI's shared app-server daemon owns the live
182
+ * thread; a detached watcher waits for the safe point, archives best-effort,
183
+ * reverts the thread to its start and starts the material turn in the same
184
+ * thread. No tmux, no `/new`, no new thread.
191
185
  */
192
186
  async tuiRestart(request, ctx) {
193
187
  if (!request.task) {
194
188
  return { status: 'unsupported', reason: 'A restart handoff needs task material; the new context contains only that material', unavailable: ['handoff.task'] };
195
189
  }
196
- const attributed = !(await tmuxAvailable()) ? undefined
197
- : (process.env.AI4AI_TMUX_PANE || process.env.TMUX_PANE)
198
- ? { paneId: process.env.AI4AI_TMUX_PANE || process.env.TMUX_PANE }
199
- : await paneForProcess(process.pid).then(pane => pane ? { paneId: pane.paneId } : undefined)
200
- ?? await paneForWorkspace('codex', ctx.identity.workspace).then(pane => pane ? { paneId: pane.paneId } : undefined);
201
- if (!attributed?.paneId)
202
- return this.daemonRestart(request, ctx);
203
- const marker = `ai4ai-context-${randomUUID()}`;
204
- const directory = path.join(ctx.home, '.ai4ai', 'codex', 'tui-restart');
205
- await mkdir(directory, { recursive: true, mode: 0o700 });
206
- const payloadFile = path.join(directory, `${request.operationId.replace(/[^A-Za-z0-9._-]/g, '_')}.payload.json`);
207
- const payload = {
208
- home: ctx.home, identity: ctx.identity, request, operationId: request.operationId, marker,
209
- paneId: attributed.paneId, startedAt: new Date().toISOString(),
210
- timeoutMs: Math.min(Math.max(request.timeoutMs ?? 10 * 60 * 1000, 1000), 30 * 60 * 1000),
211
- };
212
- await writeFile(payloadFile, JSON.stringify(payload, null, 2) + '\n');
213
- const watcher = fileURLToPath(new URL('./tui-restart-watch.js', import.meta.url));
214
- const child = spawn(process.execPath, [watcher, payloadFile], { detached: true, stdio: 'ignore', env: process.env });
215
- child.unref();
216
- return {
217
- status: 'pending',
218
- reason: 'The native TUI /new restart and material delivery are scheduled at the turn boundary; the successor thread is recorded in the journal',
219
- durable: true, state: 'running', handoff: { phase: 'pending' },
220
- notices: [{
221
- code: 'codex-tui-restart', impact: 'none', action_required: false,
222
- message: 'Finish the current turn; the watcher sends /new and the material in the same pane.',
223
- }],
224
- verification: { model: 'unknown', context: 'reported' },
225
- };
190
+ const socket = await daemonSocket(process.env.AI4AI_CODEX_BIN || 'codex');
191
+ if (!socket) {
192
+ return {
193
+ status: 'unsupported',
194
+ reason: 'The Codex TUI exposes no reachable app-server daemon (embedded server or --no-daemon); ai4ai has no native control channel to replace its context in place',
195
+ unavailable: ['handoff.restart'],
196
+ error: { code: 'codex-no-daemon', message: 'No reachable app-server daemon' },
197
+ };
198
+ }
199
+ let daemon;
200
+ try {
201
+ daemon = await CodexDaemon.connect(socket);
202
+ }
203
+ catch {
204
+ daemon = undefined;
205
+ }
206
+ if (!daemon) {
207
+ return {
208
+ status: 'unsupported',
209
+ reason: 'The Codex app-server daemon did not accept a control connection; the handoff cannot be driven without changing the session',
210
+ unavailable: ['handoff.restart'],
211
+ error: { code: 'codex-no-daemon', message: 'Daemon connection failed' },
212
+ };
213
+ }
214
+ try {
215
+ await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.6' } });
216
+ const resolution = await resolveTuiThread(daemon, ctx.identity.workspace, process.env.AI4AI_CODEX_THREAD);
217
+ if (!resolution.ok) {
218
+ return {
219
+ status: 'unsupported',
220
+ reason: resolution.reason,
221
+ unavailable: ['handoff.thread'],
222
+ error: { code: resolution.code, message: resolution.reason },
223
+ };
224
+ }
225
+ const threadId = resolution.thread.id;
226
+ const marker = `ai4ai-context-${randomUUID()}`;
227
+ const directory = path.join(ctx.home, '.ai4ai', 'codex', 'tui-handoff');
228
+ await mkdir(directory, { recursive: true, mode: 0o700 });
229
+ const payloadFile = path.join(directory, `${request.operationId.replace(/[^A-Za-z0-9._-]/g, '_')}.payload.json`);
230
+ const payload = {
231
+ home: ctx.home, identity: ctx.identity, request, operationId: request.operationId, marker, threadId, socket,
232
+ archiveDir: path.join(ctx.home, '.ai4ai', 'handoff-archive', threadId, new Date().toISOString().replace(/[:.]/g, '-')),
233
+ startedAt: new Date().toISOString(),
234
+ timeoutMs: Math.min(Math.max(request.timeoutMs ?? 10 * 60 * 1000, 1000), 30 * 60 * 1000),
235
+ };
236
+ await writeFile(payloadFile, JSON.stringify(payload, null, 2) + '\n');
237
+ const watcher = fileURLToPath(new URL('./tui-daemon-watch.js', import.meta.url));
238
+ const child = spawn(process.execPath, [watcher, payloadFile], { detached: true, stdio: 'ignore', env: process.env });
239
+ child.unref();
240
+ return {
241
+ status: 'pending',
242
+ reason: `The same-thread restart is scheduled at the turn boundary on thread ${threadId}: thread/revert to the thread start, then the material turn`,
243
+ durable: true, state: 'running', handoff: { phase: 'pending' }, sessionId: threadId,
244
+ notices: [{
245
+ code: 'codex-tui-handoff', impact: 'none', action_required: false,
246
+ message: 'Finish the current turn; the watcher reverts the same thread and delivers the material there.',
247
+ }],
248
+ verification: { model: 'unknown', context: 'reported' },
249
+ };
250
+ }
251
+ finally {
252
+ daemon.close();
253
+ }
226
254
  }
227
255
  /**
228
- * tmux-independent TUI restart. A bare terminal TUI still speaks to its
229
- * local app-server daemon. ai4ai asks the model to call the core
230
- * `new_context` tool (an in-thread reset without a summary) and a detached
231
- * watcher starts the material turn once the reset is observed. Same thread,
232
- * same process, no tmux and no process replacement.
256
+ * Explicit compact opt-in for the TUI: the harness's native compaction runs
257
+ * (and may spend summary tokens), then the material is the next turn in the
258
+ * same thread. Proof uses the native thread id for both source and successor.
233
259
  */
234
- async daemonRestart(request, ctx) {
260
+ async tuiCompact(request, ctx) {
261
+ if (!request.task) {
262
+ return { status: 'unsupported', reason: 'A compact handoff needs task material to deliver after the native summary', unavailable: ['handoff.task'] };
263
+ }
235
264
  const socket = await daemonSocket(process.env.AI4AI_CODEX_BIN || 'codex');
236
265
  if (!socket) {
237
266
  return {
238
- status: 'unknown',
239
- reason: 'The Codex TUI exposes no reachable app-server daemon (embedded server) and no tmux pane; ai4ai has no native input channel to reset it in place',
240
- unavailable: ['handoff.restart'],
267
+ status: 'unsupported',
268
+ reason: 'No reachable Codex app-server daemon for the native compact handoff',
269
+ unavailable: ['handoff.compact'],
241
270
  error: { code: 'codex-no-daemon', message: 'No reachable app-server daemon' },
242
271
  };
243
272
  }
244
- const threads = await listThreads().catch(() => []);
245
- const workspace = path.resolve(ctx.identity.workspace);
246
- const candidates = threads
247
- .filter(thread => typeof thread.cwd === 'string' && path.resolve(thread.cwd) === workspace && typeof thread.id === 'string')
248
- .sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
249
- const threadId = candidates[0]?.id;
250
- if (!threadId) {
273
+ let daemon;
274
+ try {
275
+ daemon = await CodexDaemon.connect(socket);
276
+ }
277
+ catch {
278
+ daemon = undefined;
279
+ }
280
+ if (!daemon) {
281
+ return { status: 'unsupported', reason: 'The Codex app-server daemon did not accept a control connection', unavailable: ['handoff.compact'], error: { code: 'codex-no-daemon', message: 'Daemon connection failed' } };
282
+ }
283
+ let mutated = false;
284
+ try {
285
+ return await nativeCompactHandoff(daemon, request, ctx, () => { mutated = true; });
286
+ }
287
+ catch (error) {
288
+ if (error instanceof NoLiveThread) {
289
+ return { status: 'unsupported', reason: error.message, unavailable: ['handoff.thread'], error: { code: 'codex-thread-unresolved', message: error.message } };
290
+ }
251
291
  return {
252
- status: 'unknown',
253
- reason: 'No live app-server thread matches this Codex TUI workspace; restart needs the thread the TUI is showing',
254
- unavailable: ['handoff.thread'],
255
- error: { code: 'codex-tui-no-thread', message: 'No matching live thread' },
292
+ status: mutated ? 'unknown' : 'failed',
293
+ reason: `Codex compact handoff ${mutated ? 'started but could not be confirmed' : 'failed'}: ${error instanceof Error ? error.message : 'unknown error'}`,
294
+ durable: mutated,
295
+ state: mutated ? 'unknown' : 'failed',
296
+ unavailable: ['handoff.native'],
297
+ error: { code: 'codex-native-handoff', message: error instanceof Error ? error.message : 'unknown error' },
256
298
  };
257
299
  }
258
- const marker = `ai4ai-context-${randomUUID()}`;
259
- const directory = path.join(ctx.home, '.ai4ai', 'codex', 'tui-restart');
260
- await mkdir(directory, { recursive: true, mode: 0o700 });
261
- const payloadFile = path.join(directory, `${request.operationId.replace(/[^A-Za-z0-9._-]/g, '_')}.daemon.json`);
262
- const payload = {
263
- home: ctx.home, identity: ctx.identity, request, operationId: request.operationId, marker, threadId, socket,
264
- startedAt: new Date().toISOString(),
265
- timeoutMs: Math.min(Math.max(request.timeoutMs ?? 10 * 60 * 1000, 1000), 30 * 60 * 1000),
266
- };
267
- await writeFile(payloadFile, JSON.stringify(payload, null, 2) + '\n');
268
- const watcher = fileURLToPath(new URL('./tui-daemon-watch.js', import.meta.url));
269
- const child = spawn(process.execPath, [watcher, payloadFile], { detached: true, stdio: 'ignore', env: process.env });
270
- child.unref();
271
- return {
272
- status: 'pending',
273
- reason: 'The native new_context reset is requested; the successor material runs in the same thread after the source turn',
274
- durable: true, state: 'running', handoff: { phase: 'pending' },
275
- notices: [{
276
- code: 'codex-new-context', impact: 'none', action_required: false,
277
- message: 'Call the new_context tool now, then end this turn; the material is delivered in the fresh context.',
278
- }],
279
- verification: { model: 'unknown', context: 'reported' },
280
- };
300
+ finally {
301
+ daemon.close();
302
+ }
281
303
  }
282
304
  async statusDetails(record, status, _log, ctx) {
283
305
  return codexUsage(executorDir(ctx.home, record.executorId), {
@@ -309,10 +331,10 @@ function executorDirectory(ctx) {
309
331
  * Headless self-handoff intent.
310
332
  *
311
333
  * The detached runner owns the executor's app-server process and thread
312
- * connection; a separate CLI process cannot drive that stdio channel.
313
- * The executor therefore records a durable intent and finishes its turn, and
314
- * the runner applies it at the turn boundary: compact the executor's own
315
- * thread, then start the successor turn in the same thread with the task.
334
+ * connection; a separate CLI process cannot drive that stdio channel. The
335
+ * executor records a durable intent and finishes its turn, and the runner
336
+ * applies it at the turn boundary: `thread/revert` to the thread start (same
337
+ * thread id, no summary) and then the material turn in that thread.
316
338
  */
317
339
  async function headlessSelfHandoff(request, ctx, mode) {
318
340
  const directory = executorDirectory(ctx);
@@ -330,18 +352,7 @@ async function headlessSelfHandoff(request, ctx, mode) {
330
352
  const file = path.join(directory, HANDOFF_FILE);
331
353
  const existing = await readJson(file);
332
354
  if (existing && existing.operationId === request.operationId) {
333
- const phase = String(existing.phase ?? 'intent');
334
- const lifecycle = handoffOutcome(phase, { appliedIsTerminal: true });
335
- if (phase === 'completed' || phase === 'applied') {
336
- return {
337
- status: 'completed', reason: 'The detached runner already applied this handoff', durable: true,
338
- state: lifecycle.state, ...(lifecycle.handoff ? { handoff: lifecycle.handoff } : {}), sessionId: threadId,
339
- };
340
- }
341
- return {
342
- status: 'pending', reason: `The detached runner is applying this handoff (${phase})`, durable: true,
343
- state: lifecycle.state, ...(lifecycle.handoff ? { handoff: lifecycle.handoff } : {}), sessionId: threadId,
344
- };
355
+ return handoffRecordOutcome(existing, threadId, mode);
345
356
  }
346
357
  if (existing && !['completed', 'applied', 'failed', 'cancelled'].includes(String(existing.phase))) {
347
358
  return {
@@ -349,9 +360,10 @@ async function headlessSelfHandoff(request, ctx, mode) {
349
360
  error: { code: 'handoff-busy', message: `Pending operation ${String(existing.operationId)}` },
350
361
  };
351
362
  }
363
+ const proofMechanism = mode === 'restart' ? 'surface-replacement' : 'native-compaction';
352
364
  const record = {
353
365
  format: 2, kind: 'handoff', operationId: request.operationId, request, source: ctx.identity,
354
- executorId: ctx.executorId ?? process.env.AI4AI_EXECUTOR_ID, threadId, mode, mechanism: mode,
366
+ executorId: ctx.executorId ?? process.env.AI4AI_EXECUTOR_ID, threadId, mode, mechanism: mode, proofMechanism,
355
367
  phase: 'intent', createdAt: new Date().toISOString(),
356
368
  };
357
369
  const temporary = `${file}.${process.pid}.tmp`;
@@ -360,7 +372,7 @@ async function headlessSelfHandoff(request, ctx, mode) {
360
372
  return {
361
373
  status: 'pending',
362
374
  reason: mode === 'restart'
363
- ? 'The detached runner owns this app-server process; it starts a new thread and delivers the material when the current turn completes'
375
+ ? 'The detached runner owns this thread; at the turn boundary it reverts the same thread to its start (no summary) and delivers the material'
364
376
  : 'The detached runner owns this app-server thread; it compacts the thread and starts the successor turn when the current turn completes',
365
377
  durable: true, state: 'running', handoff: { phase: 'pending' }, sessionId: threadId,
366
378
  notices: [{
@@ -370,37 +382,121 @@ async function headlessSelfHandoff(request, ctx, mode) {
370
382
  verification: { model: 'unknown', context: 'reported' },
371
383
  };
372
384
  }
373
- const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
385
+ /** Native thread identity for proof: the thread id, never the CLI carrier. */
386
+ function nativeCodexSource(record, threadId) {
387
+ const source = record?.source ?? { harness: 'codex', workspace: '', surface: 'headless', session: threadId, generation: 'codex-thread', agent: 'main' };
388
+ // The CLI carrier's session is `cli-<uuid>`; proof must name the native
389
+ // thread, not that carrier.
390
+ return { ...source, session: threadId, generation: 'codex-thread' };
391
+ }
392
+ /** Proof for a durable codex handoff record, including pre-0.0.5 records. */
393
+ function handoffRecordProof(record, threadId, fallbackMode) {
394
+ const source = nativeCodexSource(record, threadId);
395
+ const stored = record.proofMechanism;
396
+ const mode = record.mode === 'compact' ? 'compact' : fallbackMode;
397
+ const mechanism = stored ?? legacyProofMechanism(mode);
398
+ const successorThread = String(record.successorThreadId ?? record.successorSessionId ?? threadId);
399
+ const generation = String(record.successorTurnId ?? record.appliedAt ?? successorThread);
400
+ const evidence = `codex-app-server:thread/${threadId}/revert+turn/${generation}`;
401
+ if (mechanism === 'new-session') {
402
+ // A legacy restart really did change the thread; keep the historical
403
+ // evidence instead of relabelling it as a same-session replacement.
404
+ return { source, successor: { ...source, session: successorThread, generation }, mechanism, nativeEvidence: evidence };
405
+ }
406
+ return sameSessionProof(source, generation, mechanism, evidence);
407
+ }
408
+ /** Map a durable headless record onto a contract outcome, proof included. */
409
+ function handoffRecordOutcome(record, threadId, fallbackMode = 'restart') {
410
+ const phase = String(record.phase ?? 'intent');
411
+ const lifecycle = handoffOutcome(phase, { appliedIsTerminal: true });
412
+ const base = {
413
+ durable: true, sessionId: threadId,
414
+ state: lifecycle.state,
415
+ ...(lifecycle.handoff ? { handoff: lifecycle.handoff } : {}),
416
+ };
417
+ if (phase === 'completed' || phase === 'applied') {
418
+ return {
419
+ ...base,
420
+ status: phase === 'completed' ? 'completed' : 'applied',
421
+ reason: String(record.reason ?? (phase === 'completed' ? 'The detached runner applied this handoff' : 'The detached runner applied this handoff; the successor turn is still running')),
422
+ proof: handoffRecordProof(record, threadId, fallbackMode),
423
+ };
424
+ }
425
+ if (phase === 'failed') {
426
+ return { ...base, status: 'failed', reason: String(record.reason ?? record.error ?? 'The detached runner failed to apply this handoff'), durable: false, error: { code: 'codex-handoff-failed', message: String(record.error ?? 'headless handoff failed') } };
427
+ }
428
+ if (phase === 'cancelled')
429
+ return { ...base, status: 'cancelled', reason: 'The handoff was cancelled' };
430
+ return { ...base, status: 'pending', reason: `The detached runner is applying this handoff (${phase})` };
431
+ }
374
432
  /**
375
- * Compact the live TUI thread and run the handoff task as its next turn.
376
- * `markMutated` is called before the first native mutation so the caller can
377
- * report an unknown state instead of retrying through another channel.
433
+ * Reconcile a pending handoff from the runner's `handoff.json` or the TUI
434
+ * watcher journal. An `intent` whose executor is gone becomes failed instead
435
+ * of pending forever.
378
436
  */
379
- async function nativeHandoff(daemon, request, ctx, markMutated) {
380
- await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.3' } });
381
- let threadId = process.env.AI4AI_CODEX_THREAD;
382
- let model = null;
383
- if (!threadId) {
384
- const listing = await daemon.call('thread/list', { limit: 50 });
385
- const rows = (listing?.data ?? []);
386
- const workspace = path.resolve(ctx.identity.workspace);
387
- const candidates = rows
388
- .filter(thread => typeof thread.cwd === 'string' && path.resolve(thread.cwd) === workspace)
389
- .filter(thread => thread.status?.type !== 'notLoaded')
390
- .sort((left, right) => (right.updatedAt ?? 0) - (left.updatedAt ?? 0));
391
- threadId = candidates[0]?.id;
392
- model = candidates[0]?.model ?? null;
393
- if (!threadId) {
394
- throw new NoLiveThread('No live Codex TUI thread is attached to the local app-server daemon for this workspace');
437
+ async function reconcileCodexHandoff(request, ctx) {
438
+ const directory = executorDirectory(ctx);
439
+ if (directory) {
440
+ const record = await readJson(path.join(directory, HANDOFF_FILE));
441
+ if (record && record.operationId === request.operationId) {
442
+ const phase = String(record.phase ?? 'intent');
443
+ if (['intent', 'applying', 'applied'].includes(phase)) {
444
+ const status = await readJson(path.join(directory, 'status.json'));
445
+ const pid = status?.pid;
446
+ if (typeof pid === 'number' && !pidAlive(pid)) {
447
+ return {
448
+ status: 'failed', durable: false, state: 'failed',
449
+ reason: 'The detached executor no longer exists before applying the handoff; start a new handoff if the task still matters',
450
+ error: { code: 'handoff-executor-gone', message: `Executor pid ${pid} is gone with the handoff still ${phase}` },
451
+ };
452
+ }
453
+ }
454
+ const threadId = String(record.threadId ?? '');
455
+ if (threadId)
456
+ return handoffRecordOutcome(record, threadId, record.mode === 'compact' ? 'compact' : 'restart');
395
457
  }
396
458
  }
397
- const thread = threadId;
398
- await daemon.call('thread/resume', { threadId: thread, excludeTurns: true });
399
- if (!model) {
400
- const listing = await daemon.call('thread/list', { limit: 50 });
401
- const row = (listing?.data ?? []).find((entry) => entry.id === thread);
402
- model = row?.model ?? null;
459
+ const journalFile = path.join(ctx.home, '.ai4ai', 'codex', 'tui-handoff', `${request.operationId.replace(/[^A-Za-z0-9._-]/g, '_')}.json`);
460
+ const journal = await readJson(journalFile);
461
+ if (journal && journal.operationId === request.operationId) {
462
+ const phase = String(journal.phase ?? 'pending');
463
+ const threadId = String(journal.threadId ?? journal.successor?.session ?? ctx.identity.session);
464
+ if (phase === 'completed' || phase === 'applied') {
465
+ const successor = journal.successor ?? { ...ctx.identity, session: threadId };
466
+ const mechanism = journal.proofMechanism ?? legacyProofMechanism('restart');
467
+ return {
468
+ status: phase === 'completed' ? 'completed' : 'applied', durable: true, sessionId: threadId,
469
+ state: phase === 'completed' ? 'completed' : 'running',
470
+ handoff: { phase: phase === 'completed' ? 'completed' : 'applied' },
471
+ reason: String(journal.reason ?? 'The TUI watcher applied the handoff'),
472
+ proof: mechanism === 'new-session'
473
+ ? { source: ctx.identity, successor, mechanism, nativeEvidence: String(journal.nativeEvidence ?? 'codex-tui:legacy') }
474
+ : sameSessionProof(nativeCodexSource({ source: ctx.identity }, threadId), String(journal.successorTurnId ?? 'codex-revert'), mechanism, String(journal.nativeEvidence ?? 'codex-tui:revert')),
475
+ };
476
+ }
477
+ if (phase === 'failed') {
478
+ return { status: 'failed', durable: false, state: 'failed', reason: String(journal.reason ?? 'The TUI watcher failed to apply the handoff'), error: { code: 'codex-handoff-failed', message: String(journal.reason ?? 'TUI handoff failed') } };
479
+ }
480
+ return { status: 'pending', durable: true, state: 'running', handoff: { phase: 'pending' }, sessionId: threadId, reason: `The TUI watcher is applying this handoff (${phase})` };
403
481
  }
482
+ return undefined;
483
+ }
484
+ const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
485
+ /**
486
+ * Explicit compact opt-in for the live TUI thread: the native compaction runs,
487
+ * then the material is the next turn in the same thread. `markMutated` is
488
+ * called before the first native mutation so the caller can report an unknown
489
+ * state instead of retrying through another channel.
490
+ */
491
+ async function nativeCompactHandoff(daemon, request, ctx, markMutated) {
492
+ await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.6' } });
493
+ const resolution = await resolveTuiThread(daemon, ctx.identity.workspace, process.env.AI4AI_CODEX_THREAD);
494
+ if (!resolution.ok)
495
+ throw new NoLiveThread(resolution.reason);
496
+ const thread = resolution.thread.id;
497
+ const model = resolution.thread.model ?? null;
498
+ await daemon.call('thread/resume', { threadId: thread, excludeTurns: true });
499
+ const source = nativeCodexSource({ source: ctx.identity }, thread);
404
500
  const compactTimeout = Math.min(120000, request.timeoutMs ?? 120000);
405
501
  const taskTimeout = Math.min(300000, request.timeoutMs ?? 180000);
406
502
  let events = [];
@@ -425,9 +521,8 @@ async function nativeHandoff(daemon, request, ctx, markMutated) {
425
521
  const waitIdle = async (timeoutMs) => {
426
522
  const deadline = Date.now() + timeoutMs;
427
523
  for (;;) {
428
- const listing = await daemon.call('thread/list', { limit: 50 });
429
- const row = (listing?.data ?? []).find((entry) => entry.id === thread);
430
- if (row && row.status?.type === 'idle')
524
+ const read = await daemon.call('thread/read', { threadId: thread, includeTurns: false }, 15000).catch(() => undefined);
525
+ if (read?.thread?.status?.type === 'idle')
431
526
  return true;
432
527
  if (Date.now() >= deadline)
433
528
  return false;
@@ -464,7 +559,6 @@ async function nativeHandoff(daemon, request, ctx, markMutated) {
464
559
  const answer = [...events].reverse().find(message => message.method === 'item/completed' && message.params?.threadId === thread
465
560
  && message.params?.item?.type === 'agentMessage')?.params?.item?.text;
466
561
  const context = contextFromUsage(usage?.last?.inputTokens ?? null, usage?.modelContextWindow ?? null);
467
- const successor = { ...ctx.identity, generation: turnId ?? 'codex-compacted' };
468
562
  return {
469
563
  status: completed ? 'completed' : 'applied',
470
564
  reason: completed
@@ -480,7 +574,9 @@ async function nativeHandoff(daemon, request, ctx, markMutated) {
480
574
  verification: { model: model ? 'reported' : 'unknown', context: context.percentSource === 'derived' ? 'derived' : 'reported' },
481
575
  context,
482
576
  unavailable: model ? ['context.window'] : ['model'],
483
- proof: { source: ctx.identity, successor, mechanism: 'surface-replacement', nativeEvidence: `codex-app-server:thread/${thread}/compact+turn/${turnId ?? 'unknown'}` },
577
+ // The native thread id is the source and successor session; only the
578
+ // generation (turn) advances.
579
+ proof: sameSessionProof(source, turnId ?? 'codex-compacted', 'native-compaction', `codex-app-server:thread/${thread}/compact+turn/${turnId ?? 'unknown'}`),
484
580
  notices: [{
485
581
  code: 'codex-tui-handoff', impact: 'none', action_required: false,
486
582
  message: 'The compaction marker and the handoff task appear in the same TUI; the daemon protocol is upstream-experimental.',
@@ -85,7 +85,7 @@ export class CodexAppServer {
85
85
  return;
86
86
  this.child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method, params }) + '\n');
87
87
  }
88
- async initialize(clientName = 'ai4ai', version = '0.0.3') {
88
+ async initialize(clientName = 'ai4ai', version = '0.0.6') {
89
89
  const result = await this.request('initialize', { clientInfo: { name: clientName, version } });
90
90
  this.notify('initialized');
91
91
  return result;