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
@@ -12,7 +12,42 @@ export interface CodexThread {
12
12
  status?: {
13
13
  type?: string;
14
14
  };
15
+ historyMode?: string;
16
+ model?: string;
15
17
  }
18
+ export type ThreadResolution = {
19
+ ok: true;
20
+ thread: CodexThread;
21
+ loaded: CodexThread[];
22
+ } | {
23
+ ok: false;
24
+ code: 'codex-thread-missing' | 'codex-thread-ambiguous' | 'codex-thread-mismatch';
25
+ reason: string;
26
+ loaded: CodexThread[];
27
+ };
28
+ /** A thread that the app-server currently has loaded (idle or active). */
29
+ export declare const isLoadedThread: (thread: CodexThread) => boolean;
30
+ /**
31
+ * Read every page of `thread/list`. A machine with many threads (180 locally)
32
+ * returns them paginated; checking only the first page silently mis-resolves
33
+ * the TUI's thread and can make a false same-SID proof.
34
+ */
35
+ export declare function listAllThreads(daemon: CodexDaemon, options?: {
36
+ cwd?: string;
37
+ limit?: number;
38
+ maxPages?: number;
39
+ }): Promise<CodexThread[]>;
40
+ /**
41
+ * Resolve the native thread a TUI handoff may target.
42
+ *
43
+ * Order: an explicit `AI4AI_CODEX_THREAD`, otherwise exactly one loaded thread
44
+ * for this workspace across every page. Zero or several loaded threads are a
45
+ * structured failure; guessing by cwd/updatedAt would target a thread the user
46
+ * is not looking at and make the same-SID proof vacuous.
47
+ */
48
+ export declare function resolveTuiThread(daemon: CodexDaemon, workspace: string, explicit?: string): Promise<ThreadResolution>;
49
+ /** Metadata-only thread status, cheap enough to poll without scanning pages. */
50
+ export declare function threadStatus(daemon: CodexDaemon, threadId: string): Promise<CodexThread | undefined>;
16
51
  export declare class CodexDaemon {
17
52
  private socket;
18
53
  private buffer;
@@ -40,5 +75,5 @@ export declare class CodexDaemon {
40
75
  export declare function codexHome(): string;
41
76
  /** Ask the CLI for the managed daemon socket; fall back to the documented path. */
42
77
  export declare function daemonSocket(codexBin?: string): Promise<string | undefined>;
43
- /** List threads on the daemon. */
78
+ /** List every thread on the daemon (all pages). */
44
79
  export declare function listThreads(): Promise<CodexThread[]>;
@@ -4,6 +4,77 @@ import { existsSync, realpathSync } from 'node:fs';
4
4
  import { homedir } from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { spawn } from 'node:child_process';
7
+ /** A thread that the app-server currently has loaded (idle or active). */
8
+ export const isLoadedThread = (thread) => typeof thread.status?.type === 'string' && thread.status.type !== 'notLoaded';
9
+ /**
10
+ * Read every page of `thread/list`. A machine with many threads (180 locally)
11
+ * returns them paginated; checking only the first page silently mis-resolves
12
+ * the TUI's thread and can make a false same-SID proof.
13
+ */
14
+ export async function listAllThreads(daemon, options = {}) {
15
+ const limit = options.limit ?? 100;
16
+ const maxPages = options.maxPages ?? 200;
17
+ const seen = new Map();
18
+ let cursor;
19
+ for (let page = 0; page < maxPages; page++) {
20
+ const params = { limit };
21
+ if (options.cwd)
22
+ params.cwd = options.cwd;
23
+ if (cursor)
24
+ params.cursor = cursor;
25
+ const listing = await daemon.call('thread/list', params, 30000);
26
+ for (const thread of listing?.data ?? [])
27
+ if (typeof thread?.id === 'string')
28
+ seen.set(thread.id, thread);
29
+ cursor = listing?.nextCursor ?? undefined;
30
+ if (!cursor)
31
+ break;
32
+ }
33
+ return [...seen.values()];
34
+ }
35
+ /**
36
+ * Resolve the native thread a TUI handoff may target.
37
+ *
38
+ * Order: an explicit `AI4AI_CODEX_THREAD`, otherwise exactly one loaded thread
39
+ * for this workspace across every page. Zero or several loaded threads are a
40
+ * structured failure; guessing by cwd/updatedAt would target a thread the user
41
+ * is not looking at and make the same-SID proof vacuous.
42
+ */
43
+ export async function resolveTuiThread(daemon, workspace, explicit) {
44
+ const absolute = path.resolve(workspace);
45
+ const all = await listAllThreads(daemon, explicit ? {} : { cwd: absolute });
46
+ const rows = all.filter(thread => typeof thread.cwd === 'string' && path.resolve(thread.cwd) === absolute);
47
+ const loaded = rows.filter(isLoadedThread);
48
+ if (explicit) {
49
+ const found = all.find(thread => thread.id === explicit);
50
+ if (!found)
51
+ return { ok: false, code: 'codex-thread-missing', reason: `AI4AI_CODEX_THREAD ${explicit} is not present on the app-server`, loaded };
52
+ if (typeof found.cwd === 'string' && path.resolve(found.cwd) !== absolute) {
53
+ return { ok: false, code: 'codex-thread-mismatch', reason: `AI4AI_CODEX_THREAD ${explicit} belongs to another workspace`, loaded };
54
+ }
55
+ return { ok: true, thread: found, loaded };
56
+ }
57
+ if (loaded.length === 1)
58
+ return { ok: true, thread: loaded[0], loaded };
59
+ if (loaded.length === 0) {
60
+ return { ok: false, code: 'codex-thread-missing', reason: 'No loaded Codex thread matches this workspace; set AI4AI_CODEX_THREAD explicitly', loaded };
61
+ }
62
+ return {
63
+ ok: false, code: 'codex-thread-ambiguous',
64
+ reason: `${loaded.length} loaded Codex threads match this workspace (${loaded.map(t => t.id).join(', ')}); set AI4AI_CODEX_THREAD to choose one`,
65
+ loaded,
66
+ };
67
+ }
68
+ /** Metadata-only thread status, cheap enough to poll without scanning pages. */
69
+ export async function threadStatus(daemon, threadId) {
70
+ try {
71
+ const read = await daemon.call('thread/read', { threadId, includeTurns: false }, 15000);
72
+ return read?.thread;
73
+ }
74
+ catch {
75
+ return undefined;
76
+ }
77
+ }
7
78
  export class CodexDaemon {
8
79
  socket;
9
80
  buffer = Buffer.alloc(0);
@@ -246,16 +317,15 @@ export async function daemonSocket(codexBin = process.env.AI4AI_CODEX_BIN || 'co
246
317
  });
247
318
  });
248
319
  }
249
- /** List threads on the daemon. */
320
+ /** List every thread on the daemon (all pages). */
250
321
  export async function listThreads() {
251
322
  const socket = await daemonSocket();
252
323
  if (!socket)
253
324
  return [];
254
325
  const daemon = await CodexDaemon.connect(socket);
255
326
  try {
256
- await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.3' } });
257
- const listing = await daemon.call('thread/list', { limit: 50 });
258
- return (listing?.data ?? []);
327
+ await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.6' } });
328
+ return await listAllThreads(daemon);
259
329
  }
260
330
  finally {
261
331
  daemon.close();
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Native same-thread Codex handoff.
3
+ *
4
+ * `restart` is a `thread/revert` to the thread's first turn followed by a
5
+ * `turn/start` with the caller material. The app-server closes and reloads the
6
+ * same thread, so the native thread id never changes and no summarizer runs.
7
+ * Old rollouts stay on disk (the store switches its pointer), so archiving is
8
+ * best-effort: it is for the user's records, not a data-loss guard.
9
+ *
10
+ * Both transports (the per-executor stdio app-server and the TUI's shared
11
+ * WebSocket daemon) expose the same JSON-RPC methods; this module only needs
12
+ * `call` and `onMessage`.
13
+ */
14
+ export interface RpcTransport {
15
+ call(method: string, params: Record<string, unknown>, timeoutMs?: number): Promise<any>;
16
+ onMessage(listener: (message: any) => void): () => void;
17
+ }
18
+ /** Read every page of a paginated list method. */
19
+ export declare function listAllPages(transport: RpcTransport, method: string, params: Record<string, unknown>, timeoutMs?: number): Promise<any[]>;
20
+ export interface ArchiveOutcome {
21
+ ok: boolean;
22
+ path?: string;
23
+ notice?: string;
24
+ }
25
+ /**
26
+ * Export turns and items before the revert. Failure never blocks the handoff:
27
+ * the upstream implementation keeps the old rollout files intact.
28
+ */
29
+ export declare function archiveThread(transport: RpcTransport, threadId: string, directory: string, timeoutMs?: number): Promise<ArchiveOutcome>;
30
+ /** The thread's first turn; reverting before it clears the whole history. */
31
+ export declare function firstTurnId(transport: RpcTransport, threadId: string, timeoutMs?: number): Promise<string | undefined>;
32
+ export declare function threadIsIdle(transport: RpcTransport, threadId: string): Promise<boolean>;
33
+ /**
34
+ * Wait for the thread to be idle. Reverting an active turn would interrupt it
35
+ * and any message sent between the archive and the revert would miss the
36
+ * export, so the safe point is mandatory.
37
+ */
38
+ export declare function waitThreadIdle(transport: RpcTransport, threadId: string, timeoutMs: number): Promise<boolean>;
39
+ export interface RevertHandoffOptions {
40
+ threadId: string;
41
+ deliveryText: string;
42
+ archiveDir: string;
43
+ idleTimeoutMs?: number;
44
+ turnTimeoutMs?: number;
45
+ }
46
+ export interface RevertHandoffOutcome {
47
+ ok: boolean;
48
+ /** True when the successor turn completed; `applied` when it only started. */
49
+ completed?: boolean;
50
+ archive?: ArchiveOutcome;
51
+ firstTurnId?: string;
52
+ successorTurnId?: string;
53
+ reason: string;
54
+ code?: string;
55
+ }
56
+ /**
57
+ * Apply a restart handoff in the same thread: wait for the safe point, archive
58
+ * best-effort, revert before the first turn, then start the material turn.
59
+ */
60
+ export declare function applyRevertHandoff(transport: RpcTransport, options: RevertHandoffOptions): Promise<RevertHandoffOutcome>;
@@ -0,0 +1,138 @@
1
+ import { mkdir, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
4
+ /** Read every page of a paginated list method. */
5
+ export async function listAllPages(transport, method, params, timeoutMs = 30000) {
6
+ const rows = [];
7
+ let cursor;
8
+ for (let page = 0; page < 200; page++) {
9
+ const request = { ...params, ...(cursor ? { cursor } : {}) };
10
+ const listing = await transport.call(method, request, timeoutMs);
11
+ rows.push(...(Array.isArray(listing?.data) ? listing.data : []));
12
+ cursor = listing?.nextCursor ?? undefined;
13
+ if (!cursor)
14
+ break;
15
+ }
16
+ return rows;
17
+ }
18
+ /**
19
+ * Export turns and items before the revert. Failure never blocks the handoff:
20
+ * the upstream implementation keeps the old rollout files intact.
21
+ */
22
+ export async function archiveThread(transport, threadId, directory, timeoutMs = 30000) {
23
+ try {
24
+ await mkdir(directory, { recursive: true, mode: 0o700 });
25
+ const turns = await listAllPages(transport, 'thread/turns/list', { threadId, itemsView: 'full', limit: 100 }, timeoutMs);
26
+ const items = await listAllPages(transport, 'thread/items/list', { threadId, limit: 100 }, timeoutMs);
27
+ await writeFile(path.join(directory, 'turns.json'), JSON.stringify(turns, null, 2) + '\n');
28
+ await writeFile(path.join(directory, 'items.json'), JSON.stringify(items, null, 2) + '\n');
29
+ await writeFile(path.join(directory, 'manifest.json'), JSON.stringify({
30
+ threadId, archivedAt: new Date().toISOString(), turnCount: turns.length, itemCount: items.length,
31
+ note: 'Pre-handoff records. The upstream app-server keeps the original rollout file; this export is for convenience.',
32
+ }, null, 2) + '\n');
33
+ return { ok: true, path: directory };
34
+ }
35
+ catch (error) {
36
+ return { ok: false, notice: `Archive export failed (${error instanceof Error ? error.message : String(error)}); the original rollout is still on disk` };
37
+ }
38
+ }
39
+ /** The thread's first turn; reverting before it clears the whole history. */
40
+ export async function firstTurnId(transport, threadId, timeoutMs = 30000) {
41
+ const listing = await transport.call('thread/turns/list', { threadId, itemsView: 'summary', limit: 100, sortDirection: 'asc' }, timeoutMs);
42
+ const first = Array.isArray(listing?.data) ? listing.data[0] : undefined;
43
+ return typeof first?.id === 'string' ? first.id : undefined;
44
+ }
45
+ export async function threadIsIdle(transport, threadId) {
46
+ try {
47
+ const read = await transport.call('thread/read', { threadId, includeTurns: false }, 15000);
48
+ return read?.thread?.status?.type === 'idle';
49
+ }
50
+ catch {
51
+ return false;
52
+ }
53
+ }
54
+ /**
55
+ * Wait for the thread to be idle. Reverting an active turn would interrupt it
56
+ * and any message sent between the archive and the revert would miss the
57
+ * export, so the safe point is mandatory.
58
+ */
59
+ export async function waitThreadIdle(transport, threadId, timeoutMs) {
60
+ const deadline = Date.now() + timeoutMs;
61
+ for (;;) {
62
+ if (await threadIsIdle(transport, threadId))
63
+ return true;
64
+ if (Date.now() >= deadline)
65
+ return false;
66
+ await sleep(500);
67
+ }
68
+ }
69
+ /**
70
+ * Apply a restart handoff in the same thread: wait for the safe point, archive
71
+ * best-effort, revert before the first turn, then start the material turn.
72
+ */
73
+ export async function applyRevertHandoff(transport, options) {
74
+ const { threadId, deliveryText } = options;
75
+ const idleTimeoutMs = options.idleTimeoutMs ?? 5 * 60 * 1000;
76
+ const turnTimeoutMs = options.turnTimeoutMs ?? 5 * 60 * 1000;
77
+ const events = [];
78
+ const off = transport.onMessage(message => events.push(message));
79
+ try {
80
+ if (!(await waitThreadIdle(transport, threadId, idleTimeoutMs))) {
81
+ return { ok: false, code: 'codex-thread-busy', reason: 'The Codex thread did not reach an idle safe point; the handoff was not applied and no turn was interrupted' };
82
+ }
83
+ if (!(await threadIsIdle(transport, threadId))) {
84
+ return { ok: false, code: 'codex-thread-busy', reason: 'A new turn started at the safe point; the handoff was not applied' };
85
+ }
86
+ const archive = await archiveThread(transport, threadId, options.archiveDir);
87
+ const first = await firstTurnId(transport, threadId);
88
+ if (!first) {
89
+ return { ok: false, code: 'codex-no-turns', reason: 'The thread has no persisted turn to revert before; nothing was changed', archive };
90
+ }
91
+ try {
92
+ await transport.call('thread/revert', { threadId, beforeTurnId: first }, turnTimeoutMs);
93
+ }
94
+ catch (error) {
95
+ const message = error instanceof Error ? error.message : String(error);
96
+ const legacy = /paginated/i.test(message);
97
+ return {
98
+ ok: false,
99
+ code: legacy ? 'codex-legacy-thread' : 'codex-revert-failed',
100
+ reason: legacy
101
+ ? `thread/revert only supports paginated threads; this legacy thread must be migrated before a same-session handoff (${message})`
102
+ : `thread/revert failed; the task was not delivered (${message})`,
103
+ archive,
104
+ };
105
+ }
106
+ const remaining = await listAllPages(transport, 'thread/turns/list', { threadId, itemsView: 'summary', limit: 100 }, turnTimeoutMs);
107
+ if (remaining.length !== 0) {
108
+ return { ok: false, code: 'codex-revert-incomplete', reason: `thread/revert left ${remaining.length} turn(s); the material was not delivered`, archive };
109
+ }
110
+ events.length = 0;
111
+ const started = await transport.call('turn/start', { threadId, input: [{ type: 'text', text: deliveryText }] }, turnTimeoutMs);
112
+ const successorTurnId = typeof started?.turn?.id === 'string' ? started.turn.id : undefined;
113
+ const deadline = Date.now() + turnTimeoutMs;
114
+ while (Date.now() < deadline) {
115
+ const done = events.find(message => message?.method === 'turn/completed' && message?.params?.threadId === threadId
116
+ && (successorTurnId === undefined || message?.params?.turn?.id === successorTurnId));
117
+ if (done) {
118
+ const status = done.params?.turn?.status;
119
+ if (status === 'failed') {
120
+ return { ok: false, code: 'codex-successor-failed', reason: 'The successor turn failed after the revert', archive, firstTurnId: first, ...(successorTurnId ? { successorTurnId } : {}) };
121
+ }
122
+ return { ok: true, completed: true, archive, firstTurnId: first, ...(successorTurnId ? { successorTurnId } : {}), reason: 'The thread was reverted to an empty history and the material turn completed in the same thread' };
123
+ }
124
+ const failed = events.find(message => message?.method === 'error' || message?.method === 'turn/failed');
125
+ if (failed) {
126
+ return { ok: false, code: 'codex-successor-failed', reason: `The successor turn failed after the revert: ${JSON.stringify(failed.params?.error ?? failed.params).slice(0, 300)}`, archive, firstTurnId: first, ...(successorTurnId ? { successorTurnId } : {}) };
127
+ }
128
+ await sleep(200);
129
+ }
130
+ return {
131
+ ok: true, completed: false, archive, firstTurnId: first, ...(successorTurnId ? { successorTurnId } : {}),
132
+ reason: 'The thread was reverted to an empty history and the material turn started; completion was not confirmed within the timeout',
133
+ };
134
+ }
135
+ finally {
136
+ off();
137
+ }
138
+ }
@@ -17,6 +17,7 @@
17
17
  import { readFile, rename, writeFile } from 'node:fs/promises';
18
18
  import path from 'node:path';
19
19
  import { CodexAppServer } from './app-server.js';
20
+ import { applyRevertHandoff } from './native-handoff.js';
20
21
  const args = process.argv.slice(2);
21
22
  const threadIndex = args.indexOf('--thread');
22
23
  const resumeThreadId = threadIndex >= 0 ? args[threadIndex + 1] : undefined;
@@ -141,53 +142,54 @@ const applyHandoff = async () => {
141
142
  let successorThreadId = threadId;
142
143
  let successorTurnId;
143
144
  if (mode === 'restart') {
144
- // Native in-place restart in the same app-server process: a new thread
145
- // with no history and the material as its first turn. No summarizer runs.
146
- const fresh = await server.request('thread/start', {
147
- cwd, approvalPolicy: 'never', sandbox: 'workspace-write', sessionStartSource: 'clear',
148
- }, handoffTimeoutMs);
149
- successorThreadId = fresh.thread?.id ?? '';
150
- if (!successorThreadId)
151
- throw new Error('thread/start returned no thread id');
152
- threadId = successorThreadId;
153
- if (fresh.thread?.model) {
154
- threadModel = fresh.thread.model;
155
- if (executorDir) {
156
- try {
157
- await writeFile(path.join(executorDir, 'model.json'), JSON.stringify({ model: threadModel }) + '\n');
158
- }
159
- catch { /* best effort */ }
160
- }
161
- }
162
- // The supervisor observes session_id lines and replaces the executor's
163
- // session pointer while keeping the executorId.
164
- process.stdout.write(JSON.stringify({ session_id: threadId }) + '\n');
165
- events = [];
145
+ // Same-thread restart: revert the thread to its start (durable and live
146
+ // context), then run the material as the next turn in that thread. The
147
+ // thread id is unchanged and no summarizer runs.
148
+ const transport = {
149
+ call: (method, params, timeoutMs) => server.request(method, params, timeoutMs),
150
+ onMessage: listener => {
151
+ server.onNotification((method, params) => listener({ method, params }));
152
+ return () => undefined;
153
+ },
154
+ };
155
+ const archiveDir = path.join(executorDir ?? path.join(cwd, '.ai4ai'), 'handoff-archive', threadId, new Date().toISOString().replace(/[:.]/g, '-'));
166
156
  answer = '';
167
- const started = await server.request('turn/start', { threadId, input: [{ type: 'text', text: delivery }] }, handoffTimeoutMs);
168
- successorTurnId = started?.turn?.id;
169
- const settled = await settle(successorTurnId, handoffTimeoutMs);
157
+ const outcome = await applyRevertHandoff(transport, {
158
+ threadId, deliveryText: delivery, archiveDir,
159
+ idleTimeoutMs: handoffTimeoutMs, turnTimeoutMs: handoffTimeoutMs,
160
+ });
161
+ successorThreadId = threadId;
162
+ successorTurnId = outcome.successorTurnId;
163
+ const phase = outcome.ok ? (outcome.completed ? 'completed' : 'applied') : 'failed';
170
164
  const finalRecord = {
171
165
  ...record,
172
- phase: settled.ok ? 'completed' : 'failed',
166
+ phase,
173
167
  mechanism: 'restart',
168
+ proofMechanism: 'surface-replacement',
174
169
  successorThreadId,
175
170
  successorSessionId: successorThreadId,
176
171
  successorTurnId,
177
- ...(settled.ok ? {} : { error: settled.detail }),
172
+ archive: outcome.archive ?? null,
173
+ reason: outcome.reason,
174
+ ...(outcome.code ? { errorCode: outcome.code } : {}),
175
+ ...(outcome.ok ? {} : { error: outcome.reason }),
178
176
  appliedAt: new Date().toISOString(),
179
177
  };
180
178
  await writeHandoff(finalRecord);
181
179
  handoff = {
182
- operationId, phase: finalRecord.phase, mechanism: 'restart',
180
+ operationId, phase, mechanism: 'restart', proofMechanism: 'surface-replacement',
183
181
  successorThreadId, successorTurnId,
184
- ...(settled.ok ? {} : { error: settled.detail }),
182
+ archive: outcome.archive ?? null,
183
+ ...(outcome.ok ? {} : { error: outcome.reason }),
185
184
  };
186
- if (!settled.ok) {
187
- failure = `codex headless restart handoff failed: ${settled.detail}`;
185
+ if (!outcome.ok) {
186
+ failure = `codex headless restart handoff failed: ${outcome.reason}`;
188
187
  exitCode = 1;
189
188
  return false;
190
189
  }
190
+ // The successor identity is the same thread; report it so a supervisor
191
+ // can reconcile without inventing a new session.
192
+ process.stdout.write(JSON.stringify({ session_id: threadId }) + '\n');
191
193
  return true;
192
194
  }
193
195
  // `thread/compact/start` starts a compaction turn. The thread is only
@@ -207,6 +209,7 @@ const applyHandoff = async () => {
207
209
  phase: settled.ok ? 'completed' : 'failed',
208
210
  compacted: true,
209
211
  mechanism: 'compact',
212
+ proofMechanism: 'native-compaction',
210
213
  successorThreadId: threadId,
211
214
  successorTurnId,
212
215
  ...(settled.ok ? {} : { error: settled.detail }),
@@ -214,7 +217,7 @@ const applyHandoff = async () => {
214
217
  };
215
218
  await writeHandoff(finalRecord);
216
219
  handoff = {
217
- operationId, phase: finalRecord.phase, compacted: true, mechanism: 'compact', successorThreadId: threadId, successorTurnId,
220
+ operationId, phase: finalRecord.phase, compacted: true, mechanism: 'compact', proofMechanism: 'native-compaction', successorThreadId: threadId, successorTurnId,
218
221
  ...(settled.ok ? {} : { error: settled.detail }),
219
222
  };
220
223
  if (!settled.ok) {
@@ -1,27 +1,28 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Detached watcher for a Codex TUI restart when the TUI has no tmux pane.
3
+ * Detached watcher for a Codex TUI restart handoff.
4
4
  *
5
- * A bare terminal TUI still speaks to its local app-server daemon. ai4ai asks
6
- * the model to call the core `new_context` tool (an in-thread context reset
7
- * with no summary); this watcher observes that tool call, waits for the source
8
- * turn to end, and then starts the successor turn with only the caller
9
- * material. The TUI process, thread and host channel are never replaced and
10
- * no tmux is required.
5
+ * The handoff tool call runs inside the source turn, so the adapter cannot
6
+ * wait for that turn to end. This watcher owns the shared app-server daemon
7
+ * connection instead: it waits for the thread's idle safe point, archives the
8
+ * current turns best-effort, `thread/revert`s the same thread to its start
9
+ * (same thread id, no summarizer) and starts the material as the next turn in
10
+ * that thread. The TUI process, thread and host channel are never replaced.
11
11
  */
12
12
  import { readFile, writeFile, mkdir, rename } from 'node:fs/promises';
13
13
  import path from 'node:path';
14
14
  import { CodexDaemon } from './control.js';
15
+ import { applyRevertHandoff } from './native-handoff.js';
15
16
  import { Ai4aiStore } from '../../core/store.js';
16
17
  import { result } from '../../contract/validate.js';
17
- const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
18
+ import { sameSessionProof } from '../../core/handoff.js';
18
19
  async function main() {
19
20
  const file = process.argv[2];
20
21
  if (!file)
21
22
  throw new Error('payload path missing');
22
23
  const payload = JSON.parse(await readFile(file, 'utf8'));
23
24
  const { identity, request, operationId, marker, threadId } = payload;
24
- const journalDir = path.join(payload.home, '.ai4ai', 'codex', 'tui-restart');
25
+ const journalDir = path.join(payload.home, '.ai4ai', 'codex', 'tui-handoff');
25
26
  const journal = path.join(journalDir, `${operationId.replace(/[^A-Za-z0-9._-]/g, '_')}.json`);
26
27
  const writeJournal = async (value) => {
27
28
  await mkdir(journalDir, { recursive: true, mode: 0o700 });
@@ -37,48 +38,55 @@ async function main() {
37
38
  catch { /* the journal file remains the durable evidence */ }
38
39
  };
39
40
  const daemon = await CodexDaemon.connect(payload.socket);
40
- let newContextSeen = false;
41
- let turnDone = false;
42
- const deadline = Date.now() + payload.timeoutMs;
43
- daemon.onMessage(message => {
44
- try {
45
- const text = JSON.stringify(message);
46
- if (text.includes('new_context'))
47
- newContextSeen = true;
48
- if (message?.method === 'turn/completed' && message.params?.threadId === threadId)
49
- turnDone = true;
50
- }
51
- catch { /* tolerate unknown shapes */ }
52
- });
41
+ const transport = {
42
+ call: (method, params, timeoutMs) => daemon.call(method, params, timeoutMs),
43
+ onMessage: listener => daemon.onMessage(listener),
44
+ };
53
45
  try {
54
- await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.3' } }, 10000);
55
- await daemon.call('thread/resume', { threadId }, 10000);
56
- // Wait for the model to call the native `new_context` tool and for the
57
- // source turn to finish. The successor turn must not start before the
58
- // reset is requested, or the material would land in the old context.
59
- while (Date.now() < deadline && !(newContextSeen && turnDone))
60
- await sleep(500);
61
- if (!newContextSeen) {
62
- await writeJournal({ format: 1, operationId, marker, phase: 'failed', mechanism: 'restart', reason: 'The model did not call the native new_context tool; the material was not delivered', successor: null });
63
- await complete(result({ operation: 'handoff', operationId }, 'failed', 'Codex restart needs the native new_context tool call; it was not observed, so the material was not delivered', {
64
- durable: true, state: 'failed', unavailable: ['handoff.restart'],
65
- error: { code: 'new-context-missing', message: 'new_context tool call not observed' },
46
+ await daemon.call('initialize', { clientInfo: { name: 'ai4ai', version: '0.0.6' } }, 10000);
47
+ const delivery = `AI4AI handoff delivery ${marker}. Adopt the caller-supplied task in this fresh context:\n${request.task ?? ''}\nNative system/security instructions remain authoritative.`;
48
+ const outcome = await applyRevertHandoff(transport, {
49
+ threadId,
50
+ deliveryText: delivery,
51
+ archiveDir: payload.archiveDir,
52
+ idleTimeoutMs: Math.min(payload.timeoutMs, 10 * 60 * 1000),
53
+ turnTimeoutMs: Math.min(payload.timeoutMs, 10 * 60 * 1000),
54
+ });
55
+ const source = { ...identity, session: threadId, generation: 'codex-thread' };
56
+ if (!outcome.ok) {
57
+ const status = outcome.code === 'codex-legacy-thread' ? 'unsupported' : 'failed';
58
+ await writeJournal({
59
+ format: 2, operationId, marker, phase: status, mechanism: 'restart', threadId,
60
+ proofMechanism: 'surface-replacement', archive: outcome.archive ?? null,
61
+ reason: outcome.reason, error: outcome.code ?? null,
62
+ });
63
+ await complete(result({ operation: 'handoff', operationId }, status, outcome.reason, {
64
+ durable: true, ...(status === 'failed' ? { state: 'failed' } : {}),
65
+ unavailable: [outcome.code === 'codex-legacy-thread' ? 'handoff.thread' : 'handoff.restart'],
66
+ error: { code: outcome.code ?? 'codex-handoff-failed', message: outcome.reason },
67
+ ...(outcome.archive?.path ? { notices: [{ code: 'handoff-archive', impact: 'none', action_required: false, message: `Pre-handoff records: ${outcome.archive.path}` }] } : {}),
66
68
  }));
67
69
  return;
68
70
  }
69
- const text = `AI4AI handoff delivery ${marker}. Adopt the caller-supplied task in this fresh context:\n${request.task ?? ''}\nNative system/security instructions remain authoritative.`;
70
- const turn = await daemon.call('turn/start', { threadId, input: [{ type: 'text', text }] }, Math.min(payload.timeoutMs, 120000));
71
- const successorTurnId = turn?.turn?.id;
72
- const successor = { ...identity, session: threadId, generation: marker, agent: 'main' };
71
+ const generation = outcome.successorTurnId ?? 'codex-revert';
72
+ const proof = sameSessionProof(source, generation, 'surface-replacement', `codex-app-server:thread/${threadId}/revert+turn/${generation}`);
73
+ const phase = outcome.completed ? 'completed' : 'applied';
73
74
  await writeJournal({
74
- format: 1, operationId, marker, phase: 'completed', mechanism: 'restart',
75
- nativeEvidence: 'codex-new-context+app-server-turn', successor,
76
- successorTurnId,
77
- reason: 'Native new_context reset the context in the same thread; the material was started as the next turn',
75
+ format: 2, operationId, marker, phase, mechanism: 'restart', threadId,
76
+ proofMechanism: 'surface-replacement', successor: proof.successor, proof,
77
+ successorTurnId: generation, archive: outcome.archive ?? null, reason: outcome.reason,
78
78
  });
79
- await complete(result({ operation: 'handoff', operationId }, 'completed', 'Codex new_context reset the context in the same thread; the task material was delivered as the next turn', {
80
- durable: true, state: 'completed', handoff: { phase: 'completed' }, sessionId: threadId,
81
- proof: { source: identity, successor, mechanism: 'new-session', nativeEvidence: 'codex-new-context+app-server-turn' },
79
+ await complete(result({ operation: 'handoff', operationId }, phase, outcome.reason, {
80
+ durable: true,
81
+ state: outcome.completed ? 'completed' : 'running',
82
+ handoff: { phase },
83
+ sessionId: threadId,
84
+ proof,
85
+ ...(outcome.archive?.path
86
+ ? { notices: [{ code: 'handoff-archive', impact: 'none', action_required: false, message: `Pre-handoff records: ${outcome.archive.path}` }] }
87
+ : outcome.archive?.notice
88
+ ? { notices: [{ code: 'handoff-archive-skipped', impact: 'none', action_required: false, message: outcome.archive.notice }] }
89
+ : {}),
82
90
  }));
83
91
  }
84
92
  finally {
@@ -90,14 +98,17 @@ main().catch(async (error) => {
90
98
  const file = process.argv[2];
91
99
  if (file) {
92
100
  const payload = JSON.parse(await readFile(file, 'utf8'));
93
- const journalDir = path.join(payload.home, '.ai4ai', 'codex', 'tui-restart');
101
+ const journalDir = path.join(payload.home, '.ai4ai', 'codex', 'tui-handoff');
94
102
  await mkdir(journalDir, { recursive: true, mode: 0o700 });
95
- await writeFile(path.join(journalDir, `${payload.operationId}.json`), JSON.stringify({
96
- format: 1, operationId: payload.operationId, phase: 'failed', mechanism: 'restart', reason: String(error?.message ?? error),
103
+ await writeFile(path.join(journalDir, `${payload.operationId.replace(/[^A-Za-z0-9._-]/g, '_')}.json`), JSON.stringify({
104
+ format: 2, operationId: payload.operationId, phase: 'failed', mechanism: 'restart',
105
+ proofMechanism: 'surface-replacement', threadId: payload.threadId,
106
+ reason: String(error?.message ?? error),
97
107
  }, null, 2) + '\n');
98
108
  const store = await Ai4aiStore.open(payload.home).catch(() => undefined);
99
- await store?.completePending(payload.identity, payload.operationId, result({ operation: 'handoff', operationId: payload.operationId }, 'failed', 'Codex daemon restart failed: ' + String(error?.message ?? error), {
109
+ await store?.completePending(payload.identity, payload.operationId, result({ operation: 'handoff', operationId: payload.operationId }, 'failed', 'Codex daemon handoff failed: ' + String(error?.message ?? error), {
100
110
  durable: true, state: 'failed', unavailable: ['handoff.restart'],
111
+ error: { code: 'codex-handoff-failed', message: String(error?.message ?? error) },
101
112
  }));
102
113
  }
103
114
  }
@@ -11,7 +11,6 @@ export interface DeclarationInput {
11
11
  modelOverride?: Availability;
12
12
  reasoningEffortOverride?: Availability;
13
13
  crossSurface?: Availability;
14
- tmuxFallback?: 'off' | 'experimental';
15
14
  };
16
15
  spawn?: {
17
16
  availability?: Availability;
@@ -27,7 +27,6 @@ export function declaration(input) {
27
27
  modelOverride: handoff.modelOverride ?? 'unsupported',
28
28
  reasoningEffortOverride: handoff.reasoningEffortOverride ?? 'unsupported',
29
29
  crossSurface: handoff.crossSurface ?? 'unsupported',
30
- tmuxFallback: handoff.tmuxFallback ?? 'off',
31
30
  },
32
31
  spawn: {
33
32
  availability: spawn.availability ?? 'not-tested',