ccdeck 3.53.3 → 3.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +63 -7
  2. package/THIRD_PARTY_NOTICES.md +31 -1
  3. package/bin/cli/tui.js +433 -11
  4. package/dist/web/assets/{BrowserWatchModal-CJ0CW4Go.js → BrowserWatchModal-DKvBSlGT.js} +1 -1
  5. package/dist/web/assets/{IntegrationModal-DlJzBN8b.js → IntegrationModal-D3NLczRe.js} +1 -1
  6. package/dist/web/assets/{RadioPanel-CHl3s3OH.js → RadioPanel-dCIMGTd9.js} +1 -1
  7. package/dist/web/assets/{TrafficRadar-Cw3i0Hux.js → TrafficRadar-CMbwnKe7.js} +1 -1
  8. package/dist/web/assets/{UsageHistoryModal-CiB5-CTH.js → UsageHistoryModal-DkGBQaM4.js} +1 -1
  9. package/dist/web/assets/{app-xTrs4aEH.css → app-BIrh5Q0W.css} +1 -1
  10. package/dist/web/assets/{app-2vj7uk2U.js → app-l0spNrc0.js} +93 -93
  11. package/dist/web/assets/{index-D1YZbdq3.js → index-inV7HzhI.js} +1 -1
  12. package/dist/web/index.html +3 -3
  13. package/node_modules/ws/LICENSE +20 -0
  14. package/node_modules/ws/README.md +540 -0
  15. package/node_modules/ws/browser.js +8 -0
  16. package/node_modules/ws/index.js +22 -0
  17. package/node_modules/ws/lib/buffer-util.js +142 -0
  18. package/node_modules/ws/lib/constants.js +19 -0
  19. package/node_modules/ws/lib/event-target.js +292 -0
  20. package/node_modules/ws/lib/extension.js +203 -0
  21. package/node_modules/ws/lib/limiter.js +55 -0
  22. package/node_modules/ws/lib/permessage-deflate.js +530 -0
  23. package/node_modules/ws/lib/receiver.js +743 -0
  24. package/node_modules/ws/lib/sender.js +610 -0
  25. package/node_modules/ws/lib/stream.js +161 -0
  26. package/node_modules/ws/lib/subprotocol.js +62 -0
  27. package/node_modules/ws/lib/validation.js +152 -0
  28. package/node_modules/ws/lib/websocket-server.js +562 -0
  29. package/node_modules/ws/lib/websocket.js +1426 -0
  30. package/node_modules/ws/package.json +74 -0
  31. package/node_modules/ws/wrapper.mjs +21 -0
  32. package/package.json +5 -3
  33. package/release-notes.json +71 -0
  34. package/src/server/account-engine.mjs +87 -0
  35. package/src/server/account-notify.mjs +81 -16
  36. package/src/server/account-routes.mjs +49 -3
  37. package/src/server/account-watch.mjs +21 -0
  38. package/src/server/codex-auto.mjs +163 -54
  39. package/src/server/codex-engine-adapter.mjs +272 -0
  40. package/src/server/codex-engine-bridge.mjs +47 -0
  41. package/src/server/codex-engine-config.mjs +42 -0
  42. package/src/server/codex-engine-rpc.mjs +88 -0
  43. package/src/server/codex-handoff.mjs +20 -0
  44. package/src/server/codex-interactive-engine.mjs +335 -0
  45. package/src/server/codex-lan-identity.mjs +61 -0
  46. package/src/server/codex-live-checkpoint.mjs +55 -0
  47. package/src/server/codex-live-credentials.mjs +214 -0
  48. package/src/server/codex-live-engine.mjs +577 -0
  49. package/src/server/codex-live-handoff.mjs +300 -0
  50. package/src/server/codex-live-lease.mjs +64 -0
  51. package/src/server/codex-live-rpc.mjs +158 -0
  52. package/src/server/codex-profiles.mjs +34 -4
  53. package/src/server/codex-projects.mjs +308 -0
  54. package/src/server/codex-quota.mjs +36 -2
  55. package/src/server/codex-selection.mjs +78 -9
  56. package/src/server/codex-share.mjs +238 -0
  57. package/src/server/codex-terminal-runner.mjs +38 -1
  58. package/src/server/codex-terminal.mjs +15 -3
  59. package/src/server/codex-usage.mjs +69 -0
  60. package/src/server/codex-watch.mjs +3 -1
  61. package/src/server/codex-windows-private.mjs +96 -0
  62. package/src/server/codex-windows-private.ps1 +140 -0
  63. package/src/server/codex-windows-proxy.mjs +53 -0
  64. package/src/server/index.mjs +12 -4
  65. package/src/server/lan-codex-store.mjs +170 -0
  66. package/src/server/lan-codex.mjs +103 -0
  67. package/src/server/lan-deck.mjs +5 -0
  68. package/src/server/lan-engine.mjs +34 -6
  69. package/src/server/lan-manifest.mjs +16 -2
  70. package/src/server/lan-serve.mjs +16 -6
  71. package/src/server/login-service.mjs +2 -0
  72. package/src/server/pinned-build.mjs +5 -0
  73. package/src/server/request-gates.mjs +3 -0
  74. package/src/server/tui-codex.mjs +229 -0
  75. package/src/server/tui-lan.mjs +684 -0
  76. package/src/server/tui-machine.mjs +492 -0
  77. package/src/server/tui-network.mjs +730 -0
  78. package/src/server/tui-view.mjs +735 -60
@@ -0,0 +1,300 @@
1
+ // Quiesce model responses before native auth invalidates their network permits.
2
+ // Never answer approvals, widen permissions, or resume a naturally finished turn.
3
+ import { randomUUID } from 'node:crypto';
4
+ import { liveError } from './codex-live-rpc.mjs';
5
+
6
+ const passive = new Set(['userMessage', 'hookPrompt', 'agentMessage', 'functionCallOutput', 'plan', 'reasoning']);
7
+ const terminal = new Set(['completed', 'failed', 'declined']);
8
+ const tool = item => !passive.has(item.type);
9
+ const completed = item => item.status !== 'inProgress' && (terminal.has(item.status)
10
+ || Number.isFinite(item.completedAtMs) && item.completedAtMs > 0);
11
+ const v2Child = thread => thread.canAcceptDirectInput === false && !!thread.parentThreadId
12
+ && thread.source?.subAgent?.thread_spawn?.parent_thread_id === thread.parentThreadId
13
+ && typeof thread.source.subAgent.thread_spawn.agent_path === 'string'
14
+ && thread.source.subAgent.thread_spawn.agent_path.startsWith('/root/');
15
+ function ancestors(thread, known) {
16
+ const seen = new Set([thread.id]), parents = [];
17
+ for (let id = thread.parentThreadId; id; id = known.get(id)?.parentThreadId) {
18
+ if (seen.has(id) || !known.has(id)) throw liveError('native_activity_unknown');
19
+ seen.add(id); parents.push(id);
20
+ }
21
+ return parents;
22
+ }
23
+ // Waiting for a known descendant has no side effect. Spawn/input/close and
24
+ // every real tool must finish before we pause any member of the family.
25
+ const childWait = (item, thread, known) => item.type === 'collabAgentToolCall'
26
+ && item.tool === 'wait' && item.status === 'inProgress' && item.senderThreadId === thread.id
27
+ && Array.isArray(item.receiverThreadIds) && (item.receiverThreadIds.length > 0
28
+ ? item.receiverThreadIds.every(id => known.has(id) && ancestors(known.get(id), known).includes(thread.id))
29
+ : [...known.values()].some(t => v2Child(t) && ancestors(t, known).includes(thread.id)));
30
+ const safe = (turn, thread, known) => turn?.itemsView === 'full' && Array.isArray(turn?.items)
31
+ && (turn.items.some(i => i.type === 'userMessage') || v2Child(thread))
32
+ && turn.items.every(i => passive.has(i.type) || completed(i) || childWait(i, thread, known));
33
+ const inputIds = turn => turn.items.filter(i => i.type === 'userMessage').map(i => i.id);
34
+ const sameInputs = (a, b) => JSON.stringify(inputIds(a)) === JSON.stringify(inputIds(b));
35
+ const retained = new WeakMap();
36
+
37
+ /** Keep this connection's observations attached until a cooperative handoff
38
+ * finishes. Native idle unloading otherwise loses direct-input capabilities
39
+ * between a completed checkpoint and its continuation. Never starts a turn.
40
+ */
41
+ export async function retainCodexLiveHandoff(rpc, entries) {
42
+ const counts = retained.get(rpc) ?? new Map(); retained.set(rpc, counts);
43
+ const held = [];
44
+ let released = false;
45
+ const release = async () => {
46
+ if (released) return;
47
+ released = true;
48
+ for (const id of held.reverse()) {
49
+ const count = (counts.get(id) ?? 1) - 1;
50
+ if (count) counts.set(id, count);
51
+ else { counts.delete(id); await rpc.request('thread/unsubscribe', { threadId: id }).catch(() => {}); }
52
+ }
53
+ if (!counts.size) retained.delete(rpc);
54
+ };
55
+ try {
56
+ for (const entry of entries) {
57
+ const valid = t => t?.id === entry.threadId && (t.parentThreadId ?? null) === (entry.parentThreadId ?? null)
58
+ && ['active', 'idle'].includes(t.status?.type);
59
+ if (!valid((await rpc.request('thread/read', { threadId: entry.threadId, includeTurns: false }))?.thread)) throw liveError('native_activity_changed');
60
+ held.push(entry.threadId); counts.set(entry.threadId, (counts.get(entry.threadId) ?? 0) + 1);
61
+ const t = (await rpc.request('thread/resume', { threadId: entry.threadId, excludeTurns: true }))?.thread;
62
+ if (!valid(t)) throw liveError('native_activity_changed');
63
+ }
64
+ return release;
65
+ } catch (error) { await release(); throw error; }
66
+ }
67
+
68
+ async function latest(rpc, threadId) {
69
+ const page = await rpc.request('thread/turns/list', { threadId, limit: 1, sortDirection: 'desc', itemsView: 'full' });
70
+ if (!Array.isArray(page?.data)) throw liveError('native_activity_unknown');
71
+ return page.data[0] ?? null;
72
+ }
73
+ async function liveLatest(rpc, thread) {
74
+ if (thread.historyMode !== 'paginated') return latest(rpc, thread.id);
75
+ // Stored paginated history omits tool-start events. Native resume composes a
76
+ // live snapshot in its listener before subscribing this connection. Request
77
+ // one full turn, apply no settings, ignore replayed requests, then detach.
78
+ try {
79
+ const result = await rpc.request('thread/resume', { threadId: thread.id, excludeTurns: true,
80
+ initialTurnsPage: { limit: 1, sortDirection: 'desc', itemsView: 'full' } });
81
+ const page = result?.initialTurnsPage;
82
+ if (!Array.isArray(page?.data)) throw liveError('native_activity_unknown');
83
+ return page.data[0] ?? null;
84
+ } finally {
85
+ if (!retained.get(rpc)?.has(thread.id)) await rpc.request('thread/unsubscribe', { threadId: thread.id }).catch(() => {});
86
+ }
87
+ }
88
+ export const readCodexLiveTurn = (rpc, thread) => thread.status?.type === 'active' ? liveLatest(rpc, thread) : latest(rpc, thread.id);
89
+ async function snapshot(rpc) {
90
+ const page = await rpc.request('thread/loaded/list', { limit: 65 });
91
+ if (!Array.isArray(page?.data) || page.data.length > 64 || page.nextCursor) throw liveError('native_activity_unknown');
92
+ const threads = [], known = new Map();
93
+ for (const id of page.data) {
94
+ if (typeof id !== 'string') throw liveError('native_activity_unknown');
95
+ const result = await rpc.request('thread/read', { threadId: id, includeTurns: false });
96
+ const t = result?.thread;
97
+ if (!t || t.id !== id || !['idle', 'systemError', 'active', 'notLoaded'].includes(t.status?.type)) throw liveError('native_activity_unknown');
98
+ known.set(id, t);
99
+ // Ephemeral native jobs have no stored turn-history API. Never interrupt
100
+ // them or attempt to reconstruct their history; wait until twice idle.
101
+ if (t.ephemeral === true) {
102
+ if (t.status.type === 'idle') {
103
+ const again = (await rpc.request('thread/read', { threadId: id, includeTurns: false }))?.thread;
104
+ if (again?.id !== id) throw liveError('native_activity_unknown');
105
+ if (again.ephemeral === true && again.status?.type === 'idle') continue;
106
+ }
107
+ threads.push({ id, active: false, turn: null }); continue;
108
+ }
109
+ let turn;
110
+ try { turn = t.status.type === 'active' ? await liveLatest(rpc, t) : await latest(rpc, id); }
111
+ catch (error) {
112
+ // A newly opened blank native conversation has no stored turn page yet.
113
+ // Only this exact native error and a second idle observation establish
114
+ // that it has no work to hand off. Other rejected reads still fail closed.
115
+ if (t.status.type !== 'idle' || error.code !== 'native_thread_not_materialized') throw error;
116
+ const again = (await rpc.request('thread/read', { threadId: id, includeTurns: false }))?.thread;
117
+ if (again?.id !== id) throw liveError('native_activity_unknown');
118
+ if (again.status?.type === 'idle') continue;
119
+ threads.push({ id, active: false, turn: null });
120
+ continue;
121
+ }
122
+ if (t.status.type === 'active' || turn?.status === 'inProgress' || turn?.items?.some(i => i.status === 'inProgress')) threads.push({ id,
123
+ active: t.status.type === 'active',
124
+ thread: t, flags: t.status.activeFlags, turn });
125
+ }
126
+ return { threads, known };
127
+ }
128
+
129
+ /** A waiting result sends no interrupt and no authentication mutation. */
130
+ export async function prepareCodexLiveHandoff(rpc, options = {}) {
131
+ const isCurrent = options.isCurrent ?? (() => true);
132
+ const paused = [];
133
+ const { threads: initial, known } = await snapshot(rpc);
134
+ const routes = new Map();
135
+ for (const t of initial) {
136
+ if (!t.thread || !v2Child(t.thread)) continue;
137
+ const owner = ancestors(t.thread, known).map(id => initial.find(p => p.id === id))
138
+ .find(p => p?.thread.canAcceptDirectInput === true);
139
+ if (owner && (owner.turn?.rootTurnId ?? owner.turn?.id) === (t.turn?.rootTurnId ?? t.turn?.id)) routes.set(t.id, owner.id);
140
+ }
141
+ for (const t of known.values()) {
142
+ if (!v2Child(t)) continue;
143
+ const owner = ancestors(t, known).find(id => initial.some(p => p.id === id && p.thread?.canAcceptDirectInput === true));
144
+ // Even an idle V2 child identifies a parent whose current internal send or
145
+ // followup may be absent from the item feed. Wait for inspectable active
146
+ // child work (then checkpoint it), or for the parent to finish naturally.
147
+ if (owner && ![...routes.values()].includes(owner)) return { waiting: true, paused };
148
+ }
149
+ const cooperative = new Set([...routes.keys(), ...routes.values()]);
150
+ if (initial.some(t => !t.active || t.thread?.canAcceptDirectInput === false && !routes.has(t.id)
151
+ || t.thread?.parentThreadId && t.thread.canAcceptDirectInput !== true && !routes.has(t.id)
152
+ || !Array.isArray(t.flags) || t.flags.length || t.turn?.status !== 'inProgress'
153
+ || (cooperative.has(t.id) ? t.turn.itemsView !== 'full' || !Array.isArray(t.turn.items)
154
+ || !routes.has(t.id) && !t.turn.items.some(i => i.type === 'userMessage') : !safe(t.turn, t.thread, known)))) {
155
+ return { waiting: true, paused };
156
+ }
157
+ // Stop parents first so a child's interruption cannot complete a live wait
158
+ // and let its parent launch more work. Resume in the opposite order below.
159
+ initial.sort((a, b) => ancestors(a.thread, known).length - ancestors(b.thread, known).length);
160
+ if (routes.size) {
161
+ // V2's send/followup handlers do not expose every tool-start item. Never
162
+ // interrupt that family based on an empty snapshot: ask its owner to drain
163
+ // tools and collect terminal checkpoints through normal agent messaging.
164
+ const owners = new Set(routes.values()), markers = new Map([...owners].map(id => [id, randomUUID()]));
165
+ return { waiting: true, paused, checkpoint: initial.filter(t => routes.has(t.id) || owners.has(t.id)).map(t => ({
166
+ threadId: t.id, turnId: t.turn.id, rootTurnId: t.turn.rootTurnId ?? t.turn.id, inputIds: inputIds(t.turn), messageId: randomUUID(),
167
+ checkpointId: markers.get(routes.get(t.id) ?? t.id),
168
+ ...(t.thread.parentThreadId ? { parentThreadId: t.thread.parentThreadId } : {}),
169
+ ...(routes.has(t.id) ? { resumeViaThreadId: routes.get(t.id) } : {}),
170
+ })) };
171
+ }
172
+ try {
173
+ for (const observed of initial) {
174
+ if (!isCurrent()) throw liveError('native_switch_superseded');
175
+ const now = (await rpc.request('thread/read', { threadId: observed.id, includeTurns: false }))?.thread;
176
+ if (now?.status?.type !== 'active') continue;
177
+ const turn = await liveLatest(rpc, now);
178
+ if (turn?.id !== observed.turn.id || now.status.activeFlags?.length || now.canAcceptDirectInput === false && !routes.has(observed.id)
179
+ || (now.parentThreadId ?? null) !== (observed.thread.parentThreadId ?? null)
180
+ || now.parentThreadId && now.canAcceptDirectInput !== true && !routes.has(observed.id)
181
+ || routes.has(observed.id) && !v2Child(now)
182
+ || !safe(turn, now, known) || !sameInputs(observed.turn, turn)) throw liveError('native_activity_changed');
183
+ const entry = { threadId: observed.id, turnId: turn.id, rootTurnId: turn.rootTurnId ?? turn.id, messageId: randomUUID(), inputIds: inputIds(turn),
184
+ ...(now.parentThreadId ? { parentThreadId: now.parentThreadId } : {}),
185
+ ...(routes.has(observed.id) ? { resumeViaThreadId: routes.get(observed.id) } : {}) };
186
+ await options.beforeInterrupt?.(entry);
187
+ // Native acknowledges terminal completion; verify whether it interrupted
188
+ // or finished naturally. Never use an empty ID or change configuration.
189
+ await rpc.request('turn/interrupt', { threadId: observed.id, turnId: turn.id });
190
+ const after = await latest(rpc, observed.id);
191
+ if (after?.id === turn.id && after.status === 'completed') { await options.afterInterrupt?.(entry, 'skipped'); continue; }
192
+ if (after?.id !== turn.id || after.status !== 'interrupted') throw liveError('native_interrupt_unconfirmed');
193
+ if (!sameInputs(turn, after)) throw liveError('native_activity_changed');
194
+ const previous = new Set(turn.items.map(i => i.id));
195
+ if (after.items.some(i => tool(i) && !previous.has(i.id) && !completed(i))) throw liveError('native_tool_interrupted');
196
+ paused.push(entry);
197
+ await options.afterInterrupt?.(entry, 'paused');
198
+ }
199
+ await assertCodexLiveQuiet(rpc);
200
+ return { waiting: false, paused };
201
+ } catch (error) {
202
+ // Preserve exact interrupted IDs for recovery, never include thread text.
203
+ error.handoff = { waiting: false, paused };
204
+ throw error;
205
+ }
206
+ }
207
+
208
+ export async function assertCodexLiveQuiet(rpc) {
209
+ if ((await snapshot(rpc)).threads.length) throw liveError('native_activity_changed');
210
+ }
211
+
212
+ /** Mark a send durably before submitting. An uncertain send is never replayed. */
213
+ export async function continueCodexLiveHandoff(rpc, handoff, options = {}) {
214
+ let resumed = 0;
215
+ const delegated = [], owners = new Set();
216
+ for (const entry of [...handoff?.paused ?? []].reverse()) {
217
+ if (entry.sent) continue;
218
+ if (options.isCurrent && !options.isCurrent()) throw liveError('native_switch_superseded');
219
+ const t = (await rpc.request('thread/read', { threadId: entry.threadId, includeTurns: false }))?.thread;
220
+ // A closed/unloaded child has no direct-input capability. Leave it alone
221
+ // before inspecting history, and allow the remaining family to continue.
222
+ if (t?.status?.type !== 'idle') {
223
+ if (entry.resumeViaThreadId && t?.status?.type === 'notLoaded') throw liveError('native_continue_unconfirmed');
224
+ await options.onSkip?.(entry); continue;
225
+ }
226
+ if (entry.resumeViaThreadId ? !v2Child(t) || t.parentThreadId !== entry.parentThreadId
227
+ : t?.canAcceptDirectInput === false || entry.parentThreadId
228
+ && (t?.canAcceptDirectInput !== true || t.parentThreadId !== entry.parentThreadId)) throw liveError('native_activity_changed');
229
+ const turn = await latest(rpc, entry.threadId);
230
+ // New input, natural completion, archival or a different turn wins over us.
231
+ const checkpoint = entry.checkpointReady && turn?.status === 'completed'
232
+ && turn.items?.some(i => i.type === 'agentMessage' && i.text?.includes('CCDECK_CHECKPOINT_' + entry.checkpointId));
233
+ if (turn?.id !== entry.turnId || (!checkpoint && turn.status !== 'interrupted')
234
+ || JSON.stringify(inputIds(turn)) !== JSON.stringify(entry.inputIds)) {
235
+ await options.onSkip?.(entry); continue;
236
+ }
237
+ if (entry.resumeViaThreadId) {
238
+ await options.onDelegate?.(entry);
239
+ entry.sent = true; delegated.push(entry); continue;
240
+ }
241
+ await options.beforeSend?.(entry);
242
+ // Journal/authentication callbacks may wait on disk or native RPC. A user
243
+ // can close the conversation or submit new work during that wait.
244
+ if (options.isCurrent && !options.isCurrent()) throw liveError('native_switch_superseded');
245
+ const current = (await rpc.request('thread/read', { threadId: entry.threadId, includeTurns: false }))?.thread;
246
+ if (current?.status?.type !== 'idle') { await options.onSkip?.(entry); continue; }
247
+ if (current.id !== entry.threadId || current.canAcceptDirectInput === false
248
+ || (current.parentThreadId ?? null) !== (t.parentThreadId ?? null)) throw liveError('native_activity_changed');
249
+ const finalTurn = await latest(rpc, entry.threadId);
250
+ const finalCheckpoint = entry.checkpointReady && finalTurn?.status === 'completed'
251
+ && finalTurn.items?.some(i => i.type === 'agentMessage' && i.text?.includes('CCDECK_CHECKPOINT_' + entry.checkpointId));
252
+ if (finalTurn?.id !== entry.turnId || (!finalCheckpoint && finalTurn.status !== 'interrupted')
253
+ || JSON.stringify(inputIds(finalTurn)) !== JSON.stringify(entry.inputIds)) {
254
+ await options.onSkip?.(entry); continue;
255
+ }
256
+ if (options.isCurrent && !options.isCurrent()) throw liveError('native_switch_superseded');
257
+ entry.sent = true;
258
+ const children = delegated.filter(e => e.resumeViaThreadId === entry.threadId);
259
+ const continuation = 'Continue the interrupted task, honoring the latest user instructions already in this conversation. Do not repeat completed tools or actions. If the user cancelled or asked to stop, remain stopped.';
260
+ const resumeTask = entry.checkpointReady ? 'The ccdeck account change is complete. Resume the original assignment from the checkpoint; the temporary checkpoint request is finished. ' + continuation : continuation;
261
+ const text = children.length ? resumeTask + '\n\nThe account handoff paused these existing subagents (deepest first): '
262
+ + JSON.stringify(children.map(e => e.threadId)) + '. Before continuing your own work, inspect their current status with list_agents. '
263
+ + (entry.checkpointReady ? 'These listed agents ended temporary checkpoints; their original assignments are unfinished. Their native status may be completed: that checkpoint still needs continuation. For each that has not already resumed or been closed, '
264
+ : 'For each listed agent that is still interrupted, ')
265
+ + 'use the native followup_task tool exactly once, targeting that SAME existing agent ID, '
266
+ + 'with this message: ' + JSON.stringify(resumeTask) + '. Resume in the listed order. Keep their existing assignments, history and parent relationships. '
267
+ + 'Do not spawn replacements, reopen closed agents, repeat completed work, or send followups to agents already running. '
268
+ + (entry.checkpointReady ? 'A completed temporary checkpoint is not a finished original assignment. ' : 'Do not restart completed agents. ')
269
+ + 'Then continue the original task and wait for the same agents as needed.' : resumeTask;
270
+ const result = await rpc.request('turn/start', { threadId: entry.threadId,
271
+ rootTurnId: entry.rootTurnId, clientUserMessageId: entry.messageId,
272
+ input: [{ type: 'text', text }] });
273
+ if (!result?.turn?.id) throw liveError('native_continue_unconfirmed');
274
+ resumed++;
275
+ await options.afterSend?.(entry, result.turn.id);
276
+ owners.add(entry.threadId);
277
+ }
278
+ if (delegated.some(e => !owners.has(e.resumeViaThreadId))) throw liveError('native_continue_unconfirmed');
279
+ return { resumed, ...(delegated.length ? { delegated } : {}) };
280
+ }
281
+
282
+ /** Observe the parent's native followups; never submit or retry child input. */
283
+ export async function confirmCodexLiveChildren(rpc, entries, options = {}) {
284
+ const pending = [];
285
+ for (const entry of entries) {
286
+ const t = (await rpc.request('thread/read', { threadId: entry.threadId, includeTurns: false }))?.thread;
287
+ if (!t || t.parentThreadId !== entry.parentThreadId) throw liveError('native_activity_changed');
288
+ // Eviction and closure both appear unloaded here. Only the owning parent
289
+ // can distinguish them; do not claim that an unobserved child resumed.
290
+ if (t.status?.type === 'notLoaded') { pending.push(entry); continue; }
291
+ const turn = t.status?.type === 'active' ? await liveLatest(rpc, t) : await latest(rpc, entry.threadId);
292
+ if (turn?.id === entry.turnId && (turn.status === 'interrupted' || entry.checkpointReady && turn.status === 'completed'
293
+ && turn.items?.some(i => i.type === 'agentMessage' && i.text?.includes('CCDECK_CHECKPOINT_' + entry.checkpointId)))) { pending.push(entry); continue; }
294
+ if (turn?.id !== entry.turnId && turn.rootTurnId === entry.rootTurnId && ['inProgress', 'completed'].includes(turn.status)) {
295
+ await options.onConfirmed?.(entry, turn.id); continue;
296
+ }
297
+ throw liveError('native_activity_changed');
298
+ }
299
+ return { pending };
300
+ }
@@ -0,0 +1,64 @@
1
+ // One host controls a daemon's externally managed authentication. The recovery
2
+ // mutex follows the same immutable-lock pattern as the account registry.
3
+ import { createServer } from 'node:net';
4
+ import { tmpdir } from 'node:os';
5
+ import { createHash, randomUUID } from 'node:crypto';
6
+ import { link, lstat, mkdir, open, readFile, unlink } from 'node:fs/promises';
7
+ import { join } from 'node:path';
8
+ import { liveError } from './codex-live-rpc.mjs';
9
+ import { ensureWindowsPrivateDirectory, holdWindowsPrivatePath } from './codex-windows-private.mjs';
10
+ const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code !== 'ESRCH'; } };
11
+ async function record(file, options) {
12
+ let guard;
13
+ try {
14
+ const windows = (options.platform ?? process.platform) === 'win32';
15
+ if (windows) guard = await holdWindowsPrivatePath(file, { ...options.windowsPrivate, kind: 'file' });
16
+ const info = await lstat(file);
17
+ if (!info.isFile() || !windows && info.uid !== process.getuid?.() || info.size > 4096) return null;
18
+ const value = JSON.parse(await readFile(file, 'utf8'));
19
+ const after = await lstat(file);
20
+ if (guard && !guard.valid() || info.ino !== after.ino || info.dev !== after.dev || info.ctimeMs !== after.ctimeMs || info.size !== after.size) return null;
21
+ return Number.isInteger(value.pid) && value.pid > 0 && typeof value.nonce === 'string' ? { ...value, ino: info.ino, dev: info.dev } : null;
22
+ } catch { return null; }
23
+ finally { await guard?.release(); }
24
+ }
25
+ const same = (a, b) => a && b && a.pid === b.pid && a.nonce === b.nonce && a.ino === b.ino && a.dev === b.dev;
26
+ export async function acquireCodexLiveLease(home, options = {}) {
27
+ const key = createHash('sha256').update(home).digest('hex');
28
+ const windows = (options.platform ?? process.platform) === 'win32';
29
+ let dir = options.leaseDirectory ?? join(tmpdir(), `ccdeck-native-auth-${process.getuid?.() ?? 'user'}`), guard;
30
+ if (windows) {
31
+ try {
32
+ dir = await ensureWindowsPrivateDirectory(dir, options.windowsPrivate);
33
+ guard = await holdWindowsPrivatePath(dir, options.windowsPrivate);
34
+ } catch { throw liveError('untrusted_control_directory'); }
35
+ } else {
36
+ await mkdir(dir, { recursive: true, mode: 0o700 });
37
+ const info = await lstat(dir);
38
+ if (!info.isDirectory() || info.uid !== process.getuid?.() || info.mode & 0o077) throw liveError('untrusted_control_directory');
39
+ }
40
+ const file = join(dir, `${key}.lock`), nonce = randomUUID(), staged = `${file}.${nonce}.tmp`;
41
+ try {
42
+ const handle = await open(staged, 'wx', 0o600);
43
+ try { await handle.writeFile(JSON.stringify({ pid: process.pid, nonce })); await handle.sync(); }
44
+ finally { await handle.close(); }
45
+ try { await link(staged, file); }
46
+ catch (e) {
47
+ if (e.code !== 'EEXIST') throw liveError('native_control_unavailable');
48
+ const observed = await record(file, options);
49
+ if (observed && !alive(observed.pid)) {
50
+ const mutex = createServer(s => s.destroy());
51
+ const locked = await new Promise(resolve => { mutex.once('error', () => resolve(false)); mutex.listen({ host: '127.0.0.1', port: 49152 + parseInt(key.slice(0, 4), 16) % 16384, exclusive: true }, () => resolve(true)); });
52
+ if (locked) {
53
+ try { const current = await record(file, options); if (same(observed, current) && !alive(current.pid)) await unlink(file); }
54
+ finally { await new Promise(resolve => mutex.close(resolve)); }
55
+ }
56
+ }
57
+ try { await link(staged, file); } catch { throw liveError('native_control_busy'); }
58
+ }
59
+ return {
60
+ async valid() { const r = await record(file, options); return r?.pid === process.pid && r.nonce === nonce; },
61
+ async release() { const r = await record(file, options); if (r?.pid === process.pid && r.nonce === nonce) await unlink(file).catch(() => {}); },
62
+ };
63
+ } finally { await unlink(staged).catch(() => {}); await guard?.release(); }
64
+ }
@@ -0,0 +1,158 @@
1
+ // A control connection to the user's existing daemon. Closing it never stops
2
+ // that daemon or takes ownership of its conversations.
3
+ import { execFile } from 'node:child_process';
4
+ import { promisify } from 'node:util';
5
+ import { lstat, realpath } from 'node:fs/promises';
6
+ import { dirname, isAbsolute, join, resolve, win32 } from 'node:path';
7
+ import { randomUUID } from 'node:crypto';
8
+ import WebSocket from 'ws';
9
+ import { pathLookup, spawnSpec } from './exec-spec.mjs';
10
+ import { inspectWindowsPrivateSocket, holdWindowsPrivatePath } from './codex-windows-private.mjs';
11
+ import { createCodexWindowsProxy } from './codex-windows-proxy.mjs';
12
+ import { RUNNING_VERSION } from './running-version.mjs';
13
+
14
+ export const liveError = code => Object.assign(new Error(code), { code });
15
+ const runFile = promisify(execFile);
16
+ const unmaterializedHistory = /^thread [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} is not materialized yet; thread\/turns\/list is unavailable before first user message$/i;
17
+ function rejection(method, error) {
18
+ if (method === 'thread/turns/list' && error?.code === -32600 && unmaterializedHistory.test(error.message ?? '')) return liveError('native_thread_not_materialized');
19
+ return liveError(error?.code === -32601 ? 'unsupported_protocol' : 'native_request_rejected');
20
+ }
21
+
22
+ async function inspectPosixSocket(socketPath, uid = process.getuid?.()) {
23
+ try {
24
+ // Work with the resolved endpoint, never a newly substituted path alias.
25
+ if (uid == null || await realpath(socketPath) !== socketPath) throw liveError('untrusted_native_socket');
26
+ const info = await lstat(socketPath);
27
+ if (!info.isSocket() || info.uid !== uid) throw liveError('untrusted_native_socket');
28
+ const ancestors = [];
29
+ for (let path = dirname(socketPath);; path = dirname(path)) {
30
+ const directory = await lstat(path);
31
+ if (!directory.isDirectory() || directory.uid !== uid && directory.uid !== 0) throw liveError('untrusted_native_socket');
32
+ ancestors.push(directory);
33
+ if (dirname(path) === path) break;
34
+ }
35
+ let privateTraversal = false;
36
+ for (const directory of ancestors.reverse()) {
37
+ // A writable ancestor could replace even a private descendant. Sticky
38
+ // shared directories (such as /tmp) protect our owner/root-owned entries.
39
+ if (!privateTraversal && directory.mode & 0o022 && !(directory.mode & 0o1000)) throw liveError('untrusted_native_socket');
40
+ if (directory.uid === uid && !(directory.mode & 0o011)) privateTraversal = true;
41
+ }
42
+ // Socket chmod alone does not prevent connections on all supported Unix
43
+ // systems. Require an owner-private traversal barrier somewhere in the
44
+ // actual path; a permissive socket/parent below that barrier is legitimate.
45
+ if (!privateTraversal) throw liveError('untrusted_native_socket');
46
+ return { generation: `${info.dev}:${info.ino}:${info.ctimeMs}` };
47
+ } catch { throw liveError('untrusted_native_socket'); }
48
+ }
49
+
50
+ export async function resolveCodexLiveEndpoint(home, options = {}) {
51
+ const platform = options.platform ?? process.platform, windows = platform === 'win32';
52
+ let canonical, advertised;
53
+ try { canonical = await realpath(home); advertised = join(canonical, 'app-server-control', 'app-server-control.sock'); if (!windows) await lstat(advertised); }
54
+ catch { throw liveError('native_not_running'); }
55
+ const executable = options.executable ?? pathLookup('codex', platform, { pathEnv: (options.env ?? process.env).PATH ?? (options.env ?? process.env).Path ?? '' });
56
+ if (!executable) throw liveError('cli_unavailable');
57
+ const env = { ...(options.env ?? process.env), CODEX_HOME: canonical };
58
+ for (const key of Object.keys(env)) if (/^(OPENAI_API_KEY|CODEX_API_KEY)$/i.test(key)) delete env[key];
59
+ let result;
60
+ try {
61
+ const spec = spawnSpec(executable, ['app-server', 'daemon', 'version'], platform);
62
+ const output = await (options.execFile ?? runFile)(spec.file, spec.args, { ...spec.opts, env, timeout: 5000, maxBuffer: 256 * 1024, windowsHide: true });
63
+ result = JSON.parse(output.stdout);
64
+ } catch { throw liveError('native_unavailable'); }
65
+ const equalPath = windows ? (a, b) => win32.toNamespacedPath(a).toLowerCase() === win32.toNamespacedPath(b).toLowerCase() : (a, b) => resolve(a) === b;
66
+ if (result.status !== 'running' || !(windows ? win32.isAbsolute : isAbsolute)(result.socketPath ?? '') || !equalPath(result.socketPath, advertised)) throw liveError('native_not_running');
67
+ const version = String(result.appServerVersion ?? result.managedCodexVersion ?? '');
68
+ const v = version.match(/^(\d+)\.(\d+)\.(\d+)(?:$|[-+])/);
69
+ if (!v || Number(v[1]) === 0 && Number(v[2]) < 166) throw liveError('unsupported_version');
70
+ let socketPath;
71
+ if (windows) {
72
+ try {
73
+ const captured = await inspectWindowsPrivateSocket(advertised, { ...options.windowsPrivate, platform });
74
+ return { home: canonical, socketPath: captured.path, version, generation: captured.generation, executable, transport: 'windows-proxy' };
75
+ } catch { throw liveError('untrusted_native_socket'); }
76
+ }
77
+ try { socketPath = await realpath(advertised); }
78
+ catch { throw liveError('native_not_running'); }
79
+ const captured = await inspectPosixSocket(socketPath, options.uid);
80
+ return { home: canonical, socketPath, version, generation: captured.generation, executable };
81
+ }
82
+
83
+ export async function connectCodexLiveRpc(endpoint, options = {}) {
84
+ const windows = endpoint.transport === 'windows-proxy';
85
+ let guard, proxy;
86
+ if (windows) {
87
+ try {
88
+ guard = await holdWindowsPrivatePath(endpoint.socketPath, { ...options.windowsPrivate, kind: 'socket' });
89
+ if (win32.toNamespacedPath(guard.path).toLowerCase() !== win32.toNamespacedPath(endpoint.socketPath).toLowerCase()) throw liveError('untrusted_native_socket');
90
+ if (guard.generation !== endpoint.generation) throw liveError('native_endpoint_changed');
91
+ } catch (error) { await guard?.release(); throw error.code === 'native_endpoint_changed' ? error : liveError('untrusted_native_socket'); }
92
+ } else {
93
+ const before = await inspectPosixSocket(endpoint.socketPath);
94
+ if (before.generation !== endpoint.generation) throw liveError('native_endpoint_changed');
95
+ }
96
+ let ws;
97
+ try {
98
+ ws = new WebSocket(windows ? 'ws://localhost/' : `ws+unix://${endpoint.socketPath}:/`, {
99
+ handshakeTimeout: 5000, maxPayload: 64 * 1024 * 1024, perMessageDeflate: false,
100
+ ...(windows ? { createConnection: () => { proxy = createCodexWindowsProxy(endpoint, options); return proxy; } } : {}),
101
+ });
102
+ } catch { await guard?.release(); proxy?.destroy(); throw liveError('native_connection_failed'); }
103
+ const pending = new Map(), prefix = `ccdeck-live-${randomUUID()}-`;
104
+ let serial = 0, closing = false;
105
+ const rejectPending = () => {
106
+ for (const p of pending.values()) { clearTimeout(p.timer); p.reject(liveError('native_disconnected')); }
107
+ pending.clear();
108
+ };
109
+ ws.on('error', () => {});
110
+ ws.on('close', () => { rejectPending(); if (!closing) options.onClose?.(); });
111
+ const send = message => {
112
+ if (ws.readyState !== WebSocket.OPEN || ws.bufferedAmount > 1024 * 1024) throw liveError('native_disconnected');
113
+ ws.send(JSON.stringify(message));
114
+ };
115
+ ws.on('message', (raw, binary) => {
116
+ if (binary) { ws.close(1003); return; }
117
+ let m;
118
+ try { m = JSON.parse(raw.toString()); } catch { ws.close(1007); return; }
119
+ if (!m || typeof m !== 'object' || Array.isArray(m)) { ws.close(1007); return; }
120
+ const p = !m.method && pending.get(m.id);
121
+ if (p) {
122
+ pending.delete(m.id); clearTimeout(p.timer);
123
+ if (m.error) p.reject(rejection(p.method, m.error));
124
+ else p.resolve(m.result);
125
+ } else if (m.method && m.id !== undefined) {
126
+ // Unrelated approval/tool requests must remain with their own client.
127
+ Promise.resolve().then(() => options.onRequest?.(m)).catch(() => {});
128
+ } else if (m.method) options.onNotification?.(m);
129
+ });
130
+ const rpc = {
131
+ send,
132
+ request(method, params) {
133
+ if (pending.size >= 32) return Promise.reject(liveError('native_busy'));
134
+ const id = prefix + (++serial);
135
+ return new Promise((resolveCall, reject) => {
136
+ // The Windows raw proxy and a busy native daemon can exceed seven
137
+ // seconds even for a history read. Keep a bounded wait, without replay.
138
+ const timer = setTimeout(() => { pending.delete(id); reject(liveError('native_request_timeout')); }, options.deadlineMs ?? (windows ? 30000 : 7000));
139
+ pending.set(id, { method, resolve: resolveCall, reject, timer });
140
+ try { send({ id, method, ...(params === undefined ? {} : { params }) }); }
141
+ catch (e) { pending.delete(id); clearTimeout(timer); reject(e); }
142
+ });
143
+ },
144
+ close() { closing = true; rejectPending(); ws.close(); const timer = setTimeout(() => { ws.terminate(); proxy?.destroy(); }, 500); timer.unref(); },
145
+ };
146
+ try {
147
+ await new Promise((ready, reject) => { ws.once('open', ready); ws.once('error', () => reject(liveError('native_connection_failed'))); });
148
+ const after = windows ? await inspectWindowsPrivateSocket(endpoint.socketPath, options.windowsPrivate) : await inspectPosixSocket(endpoint.socketPath);
149
+ if (after.generation !== endpoint.generation) throw liveError('native_endpoint_changed');
150
+ if (guard && !guard.valid()) throw liveError('untrusted_native_socket');
151
+ // The version this deck runs, not the one this line was written in: the
152
+ // daemon logs it, and a fixed number told it 3.53.1 long after.
153
+ await rpc.request('initialize', { clientInfo: { name: 'ccdeck', title: 'ccdeck', version: RUNNING_VERSION ?? '0.0.0' }, capabilities: { experimentalApi: true } });
154
+ send({ method: 'initialized', params: {} });
155
+ return rpc;
156
+ } catch (error) { rpc.close(); throw error; }
157
+ finally { await guard?.release(); }
158
+ }
@@ -9,6 +9,7 @@ import { createHash } from 'node:crypto';
9
9
  import { readCodexSelection, codexProfileId, codexSelectionError, moveCodexLogin } from './codex-selection.mjs';
10
10
  import { usesNativeCodexAccount } from './codex-auth.mjs';
11
11
  import { readNativeCodexAccount } from './codex-native-account.mjs';
12
+ import { codexLoginOf } from './codex-lan-identity.mjs';
12
13
  export { configuredCodexHomes } from './codex-selection.mjs';
13
14
 
14
15
  /** Resolve each explicitly trusted home once before scanning rollout trees.
@@ -28,6 +29,29 @@ export async function codexProfileSessionDirs(options = {}) {
28
29
  return result;
29
30
  }
30
31
 
32
+ /** The claims of an auth.json's id_token, or {} when it has none that decode. */
33
+ function idTokenClaims(auth) {
34
+ try { return JSON.parse(Buffer.from(auth?.tokens?.id_token?.split('.')[1] ?? '', 'base64url').toString()) ?? {}; }
35
+ catch { return {}; }
36
+ }
37
+
38
+ /** The ChatGPT account id a parsed auth.json is signed in to, or null. The one
39
+ * rule the profile roster and the Projects report both read it by: the stored
40
+ * `account_id`, else the id_token's own claim. It is the value a rollout's
41
+ * `creator_account_id` carries, so it stays on the server: callers compare it
42
+ * and never send it. */
43
+ export function codexAccountIdOf(auth, claims = idTokenClaims(auth)) {
44
+ const account = auth?.tokens?.account_id ?? claims['https://api.openai.com/auth']?.chatgpt_account_id;
45
+ return typeof account === 'string' && account !== '' ? account : null;
46
+ }
47
+
48
+ /** The account id a Codex home is signed in to right now, or null when it has no
49
+ * readable login. */
50
+ export async function readCodexHomeAccountId(home) {
51
+ try { return codexAccountIdOf(JSON.parse(await readFile(join(home, 'auth.json'), 'utf8'))); }
52
+ catch { return null; }
53
+ }
54
+
31
55
  /** The ID identifies a home, never an OAuth token or an email address. */
32
56
  export async function discoverCodexProfiles(options = {}) {
33
57
  const selection = options.selection ?? await readCodexSelection(options);
@@ -44,16 +68,21 @@ export async function discoverCodexProfiles(options = {}) {
44
68
  try { await access(join(directory, 'auth.json')); installed = true; } catch { /* No login yet. */ }
45
69
  const credentialVersion = await credentialFileVersion(directory);
46
70
  let identity = null;
71
+ /** How Local network names this login, the key and the email it is offered
72
+ * under — the server's own (see codex-lan-identity.mjs), so a tick in the
73
+ * share dialog is the key the manifest is built from. No token. */
74
+ let lan = null;
47
75
  try {
48
76
  const auth = JSON.parse(await readFile(join(directory, 'auth.json'), 'utf8'));
49
- let claims = {};
50
- try { claims = JSON.parse(Buffer.from(auth.tokens?.id_token?.split('.')[1] ?? '', 'base64url').toString()); } catch { /* Account ID may still be available. */ }
77
+ const login = codexLoginOf(auth);
78
+ if (login) lan = { key: login.key, email: login.email };
79
+ const claims = idTokenClaims(auth);
51
80
  const email = typeof claims.email === 'string' ? claims.email.replace(/[\x00-\x1f\x7f]/g, '').slice(0, 254) : null;
52
- const account = auth.tokens?.account_id ?? claims['https://api.openai.com/auth']?.chatgpt_account_id;
81
+ const account = codexAccountIdOf(auth, claims);
53
82
  const workspace = typeof account === 'string' ? createHash('sha256').update(account).digest('hex').slice(0, 8) : null;
54
83
  identity = email ? `${email}${workspace ? ` · ${workspace}` : ''}` : workspace ? `Account ${workspace}` : null;
55
84
  } catch { /* Missing or malformed login metadata uses the profile label. */ }
56
- if (await credentialFileVersion(directory) !== credentialVersion) identity = null;
85
+ if (await credentialFileVersion(directory) !== credentialVersion) { identity = null; lan = null; }
57
86
  const id = selection.profiles?.find(p => p.home === directory)?.id ?? await codexProfileId(directory);
58
87
  const managedEntry = selection.managedProfiles?.find(p => p.id === id);
59
88
  const managedLabel = selection.profileLabels?.find(p => p.id === id)?.label ?? managedEntry?.label ?? null;
@@ -74,6 +103,7 @@ export async function discoverCodexProfiles(options = {}) {
74
103
  available,
75
104
  ...(native ? { signedIn: native.ok && native.signedIn, authSource: 'native', metadataUnavailable: !native.ok, metadataReason: native.reason ?? null } : {}),
76
105
  signedInFilePresent: installed, // file presence is NOT authentication validity
106
+ ...(lan ? { lan } : {}),
77
107
  });
78
108
  // The file's workspace goes in too: one address on one plan can be two
79
109
  // workspaces, and Codex's own answer does not always tell them apart.