@reasontrail/cli 0.1.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.
@@ -0,0 +1,520 @@
1
+ import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { basename, join, resolve } from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+
6
+ /**
7
+ * Deterministic Codex Local Session Reader and Synchronizer.
8
+ *
9
+ * Reads JSONL session rollouts from ~/.codex/sessions/ without depending
10
+ * on Codex voluntarily invoking ReasonTrail MCP tools.
11
+ * Enforces a strict project-scoped privacy boundary: only sessions inside
12
+ * bound ReasonTrail Git repositories are synced.
13
+ */
14
+
15
+ export function defaultCodexHome() {
16
+ return process.env.CODEX_HOME || join(homedir(), ".codex");
17
+ }
18
+
19
+ export async function readSessionIndex(codexHome = defaultCodexHome()) {
20
+ const indexPath = join(codexHome, "session_index.jsonl");
21
+ const threadNames = {};
22
+ try {
23
+ const raw = await readFile(indexPath, "utf8");
24
+ for (const line of raw.split("\n")) {
25
+ const trimmed = line.trim();
26
+ if (!trimmed) continue;
27
+ try {
28
+ const item = JSON.parse(trimmed);
29
+ if (item.id && item.thread_name) {
30
+ threadNames[item.id] = item.thread_name;
31
+ }
32
+ } catch {}
33
+ }
34
+ } catch {}
35
+ return threadNames;
36
+ }
37
+
38
+ export async function findJsonlFiles(dir) {
39
+ let files = [];
40
+ try {
41
+ const entries = await readdir(dir, { withFileTypes: true });
42
+ for (const entry of entries) {
43
+ const full = join(dir, entry.name);
44
+ if (entry.isDirectory()) {
45
+ files = files.concat(await findJsonlFiles(full));
46
+ } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
47
+ files.push(full);
48
+ }
49
+ }
50
+ } catch {}
51
+ return files;
52
+ }
53
+
54
+ function cleanUserContent(text) {
55
+ if (typeof text !== "string") return "";
56
+ let cleaned = text.trim();
57
+ // Strip out leading/trailing plugin recommendations block injected by Codex
58
+ cleaned = cleaned.replace(/<recommended_plugins>[\s\S]*?<\/recommended_plugins>/gi, "").trim();
59
+ // Repository/environment injections provide context, not user-authored dialogue.
60
+ cleaned = cleaned.replace(/^# AGENTS\.md instructions for [^\n]+\s*<INSTRUCTIONS>[\s\S]*?<\/INSTRUCTIONS>/i, "").trim();
61
+ cleaned = cleaned.replace(/<environment_context>[\s\S]*?<\/environment_context>/gi, "").trim();
62
+ // Strip out developer collaboration/multi-agent wrappers if injected into user turn
63
+ cleaned = cleaned.replace(/<collaboration_mode>[\s\S]*?<\/collaboration_mode>/gi, "").trim();
64
+ cleaned = cleaned.replace(/<multi_agent_mode>[\s\S]*?<\/multi_agent_mode>/gi, "").trim();
65
+ return cleaned;
66
+ }
67
+
68
+ function isSystemOnlyText(text) {
69
+ if (!text) return true;
70
+ const trimmed = text.trim();
71
+ if (/^<recommended_plugins>/i.test(trimmed) && trimmed.endsWith("</recommended_plugins>")) return true;
72
+ if (/^<collaboration_mode>/i.test(trimmed)) return true;
73
+ if (/^<multi_agent_mode>/i.test(trimmed)) return true;
74
+ return false;
75
+ }
76
+
77
+ function isVisibleAssistant(item) {
78
+ // Current rollouts use phase; legacy rollouts may omit both fields.
79
+ const visible = new Set(["commentary", "final", "final_answer"]);
80
+ return [item.channel, item.phase].every((value) => value == null || visible.has(value));
81
+ }
82
+
83
+ function ownedSession(records, filePath) {
84
+ const filenameId = basename(filePath).match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i)?.[1];
85
+ const metadata = records.filter(({ data }) => data.type === "session_meta")
86
+ .map(({ data, line }) => ({
87
+ id: data.payload?.id || data.payload?.session_id,
88
+ parentId: data.payload?.source?.subagent?.thread_spawn?.parent_thread_id || null,
89
+ source: data.payload?.id ? "session_meta.id" : "session_meta.session_id",
90
+ cwd: data.payload?.cwd,
91
+ line,
92
+ })).filter((entry) => typeof entry.id === "string" && entry.id);
93
+ const identities = new Set(metadata.map((entry) => entry.id));
94
+ let own = filenameId ? metadata.find((entry) => entry.id === filenameId) : null;
95
+ if (!own && filenameId && metadata.length) {
96
+ return { error: "session_identity_filename_mismatch" };
97
+ }
98
+ if (!own && identities.size === 1) own = metadata[0];
99
+ if (!own && identities.size > 1) {
100
+ // A child can include several ancestors; only one leaf is authoritative.
101
+ const parents = new Set(metadata.map((entry) => entry.parentId).filter(Boolean));
102
+ const leaves = [...identities].filter((id) => !parents.has(id));
103
+ if (leaves.length === 1) own = metadata.find((entry) => entry.id === leaves[0]);
104
+ else return { error: "ambiguous_session_identity" };
105
+ }
106
+ const eventId = records.find(({ data }) => data.type === "event_msg" && data.payload?.thread_id)?.data.payload.thread_id;
107
+ const threadId = own?.id || filenameId || eventId || basename(filePath).replace(/\.jsonl$/, "");
108
+ let historyStartLine = own?.line || 1;
109
+ if (identities.size > 1) {
110
+ const settings = records.find(({ data }) => data.type === "event_msg"
111
+ && data.payload?.type === "thread_settings_applied" && data.payload.thread_id === threadId);
112
+ const lastInheritedMetadata = Math.max(...metadata.filter((entry) => entry.id !== threadId).map((entry) => entry.line));
113
+ if (settings && settings.line > lastInheritedMetadata) historyStartLine = settings.line;
114
+ else if (own.line > lastInheritedMetadata) historyStartLine = own.line;
115
+ else return { error: "ambiguous_inherited_history_boundary", threadId };
116
+ }
117
+ return {
118
+ threadId,
119
+ parentThreadId: own?.parentId || null,
120
+ identitySource: own?.source || (filenameId ? "filename" : eventId ? "event_msg.thread_id" : "filename_basename"),
121
+ historyStartLine,
122
+ cwd: own?.cwd || null,
123
+ };
124
+ }
125
+
126
+ export async function parseCodexSessionFile(filePath, threadNames = {}) {
127
+ let raw;
128
+ try {
129
+ raw = await readFile(filePath, "utf8");
130
+ } catch (err) {
131
+ return { error: err.message, filePath };
132
+ }
133
+
134
+ const lines = raw.split("\n");
135
+ const records = [];
136
+ for (let i = 0; i < lines.length; i++) {
137
+ try {
138
+ const data = JSON.parse(lines[i]);
139
+ if (data && typeof data === "object") records.push({ data, line: i + 1 });
140
+ } catch {}
141
+ }
142
+ const identity = ownedSession(records, filePath);
143
+ if (identity.error) return { ...identity, filePath };
144
+ const { threadId, parentThreadId, identitySource, historyStartLine } = identity;
145
+ let cwd = identity.cwd;
146
+ let excludedInheritedTurnCount = 0;
147
+ let startTs = null;
148
+ let endTs = null;
149
+ let usageExceeded = false;
150
+ let usageExceededMessage = null;
151
+ let rawTurns = [];
152
+
153
+ for (const { data: d, line } of records) {
154
+ const foreignThread = d.type === "event_msg" && d.payload?.thread_id && d.payload.thread_id !== threadId;
155
+ if (line < historyStartLine || foreignThread) {
156
+ if ((d.type === "response_item" && d.payload?.type === "message" && ["user", "assistant"].includes(d.payload.role))
157
+ || (d.type === "event_msg" && d.payload?.type === "item_completed" && ["UserMessage", "AgentMessage"].includes(d.payload?.item?.type))) {
158
+ excludedInheritedTurnCount++;
159
+ }
160
+ continue;
161
+ }
162
+ if (!startTs && d.timestamp) startTs = d.timestamp;
163
+ if (d.timestamp) endTs = d.timestamp;
164
+ if (!cwd && d.type === "turn_context" && d.payload?.cwd) cwd = d.payload.cwd;
165
+
166
+ // Only structured runtime error events establish a quota interruption.
167
+ // Messages and tool output may quote error names while discussing code.
168
+ const runtimeError = d.type === "event_msg"
169
+ ? d.payload?.error ?? (d.payload?.type === "error" ? d.payload : null)
170
+ : null;
171
+ if (runtimeError?.codex_error_info === "usage_limit_exceeded") {
172
+ usageExceeded = true;
173
+ usageExceededMessage = typeof runtimeError.message === "string"
174
+ ? runtimeError.message : "Codex usage limit reached.";
175
+ }
176
+
177
+ // Format A: response_item with payload.type === "message"
178
+ if (d.type === "response_item" && d.payload?.type === "message") {
179
+ const role = d.payload.role;
180
+ const id = d.payload.id || d.payload.internal_chat_message_metadata_passthrough?.turn_id || `msg_${line - 1}`;
181
+ const contents = Array.isArray(d.payload.content) ? d.payload.content : [];
182
+ const textParts = contents.map((c) => (typeof c === "string" ? c : c?.text || "")).filter(Boolean);
183
+ const text = textParts.join("\n").trim();
184
+ if (text && (role === "user" || (role === "assistant" && isVisibleAssistant(d.payload)))) {
185
+ const cleaned = role === "user" ? cleanUserContent(text) : text;
186
+ if (cleaned && !isSystemOnlyText(cleaned)) {
187
+ rawTurns.push({
188
+ id,
189
+ sourceLine: line,
190
+ role,
191
+ content: cleaned,
192
+ timestamp: d.timestamp || endTs || new Date().toISOString(),
193
+ });
194
+ }
195
+ }
196
+ }
197
+
198
+ // Format B: event_msg with payload.type === "item_completed"
199
+ if (d.type === "event_msg" && d.payload?.type === "item_completed" && d.payload?.item) {
200
+ const item = d.payload.item;
201
+ const itemType = item.type;
202
+ const id = item.id || `item_${line - 1}`;
203
+ let role = null;
204
+ if (itemType === "UserMessage") role = "user";
205
+ else if (itemType === "AgentMessage") role = "assistant";
206
+
207
+ if (role && (role === "user" || isVisibleAssistant(item))) {
208
+ const contents = Array.isArray(item.content) ? item.content : [];
209
+ const textParts = contents.map((c) => (typeof c === "string" ? c : c?.text || "")).filter(Boolean);
210
+ const text = textParts.join("\n").trim();
211
+ if (text) {
212
+ const cleaned = role === "user" ? cleanUserContent(text) : text;
213
+ if (cleaned && !isSystemOnlyText(cleaned)) {
214
+ rawTurns.push({
215
+ id,
216
+ sourceLine: line,
217
+ role,
218
+ content: cleaned,
219
+ timestamp: d.timestamp || endTs || new Date().toISOString(),
220
+ });
221
+ }
222
+ }
223
+ }
224
+ }
225
+ }
226
+
227
+ // Deduplicate consecutive identical turns (or duplicate turn IDs)
228
+ const turns = [];
229
+ const seenIds = new Set();
230
+ for (let i = 0; i < rawTurns.length; i++) {
231
+ const t = rawTurns[i];
232
+ if (seenIds.has(t.id)) continue;
233
+ seenIds.add(t.id);
234
+ if (turns.length > 0) {
235
+ const prev = turns[turns.length - 1];
236
+ if (prev.role === t.role && prev.content.trim() === t.content.trim()) {
237
+ continue;
238
+ }
239
+ }
240
+ turns.push({
241
+ messageId: `codex:${threadId}:${turns.length}`,
242
+ nativeMessageId: t.id,
243
+ sourceLine: t.sourceLine,
244
+ role: t.role,
245
+ content: t.content,
246
+ sequence: turns.length,
247
+ timestamp: t.timestamp,
248
+ });
249
+ }
250
+
251
+ // Derive title
252
+ let title = threadNames[threadId] || null;
253
+ if (!title) {
254
+ // Find first substantive user prompt (skipping AGENTS.md injection if present)
255
+ const substantiveUser = turns.filter((t) => t.role === "user").find((t) => !t.content.startsWith("# AGENTS.md instructions for"));
256
+ const firstUser = substantiveUser || turns.find((t) => t.role === "user");
257
+ if (firstUser) {
258
+ const firstLine = firstUser.content.split("\n")[0].trim().replace(/^#+\s*/, "");
259
+ title = firstLine.length > 120 ? `${firstLine.slice(0, 119)}…` : firstLine;
260
+ }
261
+ }
262
+ if (!title) {
263
+ title = `Codex session ${threadId.slice(0, 8)}`;
264
+ }
265
+
266
+ return {
267
+ filePath,
268
+ threadId,
269
+ parentThreadId,
270
+ identitySource,
271
+ historyStartLine,
272
+ excludedInheritedTurnCount,
273
+ title,
274
+ cwd: cwd ? resolve(cwd) : null,
275
+ startedAt: startTs,
276
+ updatedAt: endTs,
277
+ turns,
278
+ turnCount: turns.length,
279
+ userTurnCount: turns.filter((t) => t.role === "user").length,
280
+ assistantTurnCount: turns.filter((t) => t.role === "assistant").length,
281
+ usageExceeded,
282
+ usageExceededMessage,
283
+ interrupted: usageExceeded,
284
+ interruptionReason: usageExceeded ? "usage_limit_exceeded" : null,
285
+ };
286
+ }
287
+
288
+ export function gitRootFor(cwd) {
289
+ if (!cwd) return null;
290
+ const res = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8" });
291
+ return res.status === 0 ? resolve(res.stdout.trim()) : null;
292
+ }
293
+
294
+ export async function discoverAndMapCodexSessions(options = {}) {
295
+ const codexHome = options.codexHome || defaultCodexHome();
296
+ const sessionsDir = join(codexHome, "sessions");
297
+ const threadNames = await readSessionIndex(codexHome);
298
+ const files = await findJsonlFiles(sessionsDir);
299
+
300
+ const gitCache = {};
301
+ const resolveGit = (dir) => {
302
+ if (!dir) return null;
303
+ if (gitCache[dir] !== undefined) return gitCache[dir];
304
+ const root = gitRootFor(dir);
305
+ gitCache[dir] = root;
306
+ return root;
307
+ };
308
+
309
+ const bindings = options.bindings || {};
310
+ const sessions = [];
311
+ const parseFailures = [];
312
+
313
+ for (const file of files) {
314
+ const parsed = await parseCodexSessionFile(file, threadNames);
315
+ if (parsed.error) {
316
+ parseFailures.push({ filePath: file, reason: parsed.error });
317
+ continue;
318
+ }
319
+
320
+ // Filter by --since if requested
321
+ if (options.since) {
322
+ const sinceDate = new Date(options.since);
323
+ if (!isNaN(sinceDate.getTime()) && parsed.updatedAt) {
324
+ if (new Date(parsed.updatedAt).getTime() < sinceDate.getTime()) {
325
+ continue;
326
+ }
327
+ }
328
+ }
329
+
330
+ // Filter by --session if requested
331
+ if (options.session && parsed.threadId !== options.session) {
332
+ continue;
333
+ }
334
+
335
+ const gitRoot = resolveGit(parsed.cwd);
336
+ const binding = gitRoot ? bindings[gitRoot] : null;
337
+ const projectSlug = binding?.projectSlug || null;
338
+
339
+ // Filter by --project if requested
340
+ if (options.project && projectSlug !== options.project) {
341
+ continue;
342
+ }
343
+
344
+ const mapped = Boolean(projectSlug);
345
+ sessions.push({
346
+ ...parsed,
347
+ gitRoot,
348
+ projectSlug,
349
+ mapped,
350
+ skipReason: mapped ? null : "unmapped_workspace",
351
+ });
352
+ }
353
+
354
+ // Deduplicate / consolidate by threadId
355
+ const byThread = new Map();
356
+ for (const s of sessions) {
357
+ const existing = byThread.get(s.threadId);
358
+ if (!existing) {
359
+ byThread.set(s.threadId, s);
360
+ } else {
361
+ // Choose the more complete session (more turns or newer update)
362
+ if (s.turnCount > existing.turnCount || new Date(s.updatedAt || 0) > new Date(existing.updatedAt || 0)) {
363
+ byThread.set(s.threadId, s);
364
+ }
365
+ }
366
+ }
367
+ const resultSessions = Array.from(byThread.values());
368
+
369
+ // Sort chronologically
370
+ resultSessions.sort((a, b) => new Date(a.updatedAt || 0).getTime() - new Date(b.updatedAt || 0).getTime());
371
+
372
+ // Preserve the array API while making rejected ambiguous files inspectable.
373
+ Object.defineProperty(resultSessions, "parseFailures", { value: parseFailures });
374
+ return resultSessions;
375
+ }
376
+
377
+ export async function readSyncState(configDir) {
378
+ const statePath = join(configDir, "connectors", "codex", "sync-state.json");
379
+ try {
380
+ return JSON.parse(await readFile(statePath, "utf8"));
381
+ } catch {
382
+ return { sessions: {}, lastSyncAt: null };
383
+ }
384
+ }
385
+
386
+ export async function saveSyncState(configDir, state) {
387
+ const dir = join(configDir, "connectors", "codex");
388
+ await mkdir(dir, { recursive: true, mode: 0o700 });
389
+ const statePath = join(dir, "sync-state.json");
390
+ await writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
391
+ }
392
+
393
+ export async function syncCodex(client, tools, configDir, config, options = {}) {
394
+ const bindings = config.bindings || {};
395
+ const sessions = await discoverAndMapCodexSessions({
396
+ codexHome: options.codexHome || defaultCodexHome(),
397
+ bindings,
398
+ since: options.since,
399
+ session: options.session,
400
+ project: options.project,
401
+ });
402
+
403
+ const state = await readSyncState(configDir);
404
+ const syncState = state.sessions || {};
405
+
406
+ let discovered = sessions.length;
407
+ let mapped = 0;
408
+ let alreadySynchronized = 0;
409
+ let eligibleForImport = 0;
410
+ let skippedUnmapped = 0;
411
+
412
+ const eligibleSessions = [];
413
+
414
+ for (const s of sessions) {
415
+ if (!s.mapped) {
416
+ skippedUnmapped++;
417
+ continue;
418
+ }
419
+ mapped++;
420
+
421
+ const prevSync = syncState[s.threadId];
422
+ const isUpToDate = prevSync && prevSync.turnCount === s.turnCount && prevSync.interrupted === s.interrupted;
423
+ if (isUpToDate && !options.force) {
424
+ alreadySynchronized++;
425
+ } else {
426
+ eligibleForImport++;
427
+ eligibleSessions.push({
428
+ session: s,
429
+ prevSync: prevSync || null,
430
+ deltaTurns: prevSync ? s.turns.slice(prevSync.turnCount || 0) : s.turns,
431
+ });
432
+ }
433
+ }
434
+
435
+ const dryRun = Boolean(options.dryRun || options.dry_run);
436
+
437
+ if (dryRun) {
438
+ return {
439
+ dry_run: true,
440
+ sessions_discovered: discovered,
441
+ sessions_mapped: mapped,
442
+ already_synchronized: alreadySynchronized,
443
+ eligible_for_import: eligibleForImport,
444
+ skipped_unmapped: skippedUnmapped,
445
+ parse_failures: sessions.parseFailures.length,
446
+ parse_failure_details: sessions.parseFailures.slice(0, 20),
447
+ eligible_sessions: eligibleSessions.map((e) => ({
448
+ threadId: e.session.threadId,
449
+ title: e.session.title,
450
+ projectSlug: e.session.projectSlug,
451
+ turnCount: e.session.turnCount,
452
+ interrupted: e.session.interrupted,
453
+ interruptionReason: e.session.interruptionReason,
454
+ updatedAt: e.session.updatedAt,
455
+ })),
456
+ };
457
+ }
458
+
459
+ // Live Sync
460
+ let importedCount = 0;
461
+ const now = new Date().toISOString();
462
+
463
+ for (const item of eligibleSessions) {
464
+ const s = item.session;
465
+ const clientConversationId = `codex:${s.threadId}`;
466
+ const project = { projectSlug: s.projectSlug };
467
+
468
+ // 1. Begin task (idempotent: opens/reuses the conversation)
469
+ const firstUser = s.turns.find((t) => t.role === "user");
470
+ await client.call("begin_task", {
471
+ clientConversationId,
472
+ taskTitle: s.title,
473
+ ...(firstUser ? { userRequest: firstUser.content, messageId: firstUser.messageId } : {}),
474
+ timestamp: s.startedAt || s.updatedAt || now,
475
+ ...project,
476
+ });
477
+
478
+ // 2. Sync turns delta
479
+ if (item.deltaTurns.length > 0) {
480
+ await client.call("sync_conversation_delta", {
481
+ clientConversationId,
482
+ turns: item.deltaTurns,
483
+ ...project,
484
+ });
485
+ }
486
+
487
+ // Interruption status is preserved on the synced conversation itself. Do
488
+ // not create a second generic Brain update: that produced noisy "Finding
489
+ // reported by reasontrail-cli" Inbox/review items for ordinary plan drift.
490
+ syncState[s.threadId] = {
491
+ title: s.title,
492
+ projectSlug: s.projectSlug,
493
+ turnCount: s.turnCount,
494
+ interrupted: s.interrupted,
495
+ lastSyncAt: now,
496
+ updatedAt: s.updatedAt,
497
+ };
498
+ state.sessions = syncState;
499
+ state.lastSyncAt = now;
500
+ await saveSyncState(configDir, state);
501
+ importedCount++;
502
+ }
503
+
504
+ if (eligibleSessions.length === 0) {
505
+ state.sessions = syncState;
506
+ }
507
+
508
+ return {
509
+ synchronized: true,
510
+ sessions_discovered: discovered,
511
+ sessions_mapped: mapped,
512
+ imported: importedCount,
513
+ already_synchronized: alreadySynchronized,
514
+ skipped_unmapped: skippedUnmapped,
515
+ interrupted_sessions: eligibleSessions.filter((item) => item.session.interrupted).length,
516
+ parse_failures: sessions.parseFailures.length,
517
+ parse_failure_details: sessions.parseFailures.slice(0, 20),
518
+ last_sync_at: now,
519
+ };
520
+ }
@@ -0,0 +1,60 @@
1
+ /** Browser-approved setup grant exchange; never emits bearer credentials. */
2
+ export async function deviceLogin(endpoint, {
3
+ machineName, version, fetchImpl = fetch, sleep = ms => new Promise(resolve => setTimeout(resolve, ms)),
4
+ announce = () => {}, now = Date.now, install = async token => token, rollback = async () => {},
5
+ } = {}) {
6
+ const origin = new URL(endpoint).origin;
7
+ async function post(path, body, grant) {
8
+ let response, result;
9
+ try {
10
+ response = await fetchImpl(new URL(path, origin), {
11
+ method: "POST", redirect: "error", signal: AbortSignal.timeout(15000),
12
+ headers: { "Content-Type": "application/json", ...(grant ? { Authorization: `Bearer ${grant}` } : {}) },
13
+ body: JSON.stringify(body ?? {}),
14
+ });
15
+ result = await response.json();
16
+ } catch { throw new Error('Device authorization could not reach the server. Start a new login.'); }
17
+ if (!response.ok || !result?.data) throw new Error(`Device authorization failed (${response.status}). Start a new login.`);
18
+ return result.data;
19
+ }
20
+ const started = now();
21
+ const challenge = await post('/api/setup/v1/challenges', { machineName: machineName || 'ReasonTrail CLI', clientVersion: version, requestedClients: ['reasontrail-cli'], requestedProfile: 'READ_CAPTURE' });
22
+ let verification;
23
+ try { verification = new URL(challenge.verificationUriComplete); } catch { throw new Error('Device authorization returned an invalid destination.'); }
24
+ if (verification.origin !== origin || verification.username || verification.password || verification.pathname !== '/device'
25
+ || typeof challenge.challengeSecret !== 'string' || !challenge.challengeSecret || challenge.challengeSecret.length > 512
26
+ || typeof challenge.userCode !== 'string' || !/^[A-Z0-9-]{4,32}$/.test(challenge.userCode)
27
+ || verification.searchParams.get('code') !== challenge.userCode || verification.hash
28
+ || [...verification.searchParams.keys()].some(key => key !== 'code')) throw new Error('Device authorization returned an invalid destination.');
29
+ const advertisedDeadline = Date.parse(challenge.expiresAt);
30
+ const deadline = Math.min(advertisedDeadline, started + 10 * 60_000);
31
+ if (!Number.isFinite(deadline) || deadline <= now()) throw new Error('Device authorization expired.');
32
+ announce({ verificationUri: verification.toString(), userCode: challenge.userCode });
33
+ const advertisedInterval = Number(challenge.pollIntervalSeconds);
34
+ const interval = Number.isFinite(advertisedInterval) ? Math.max(1000, Math.min(10000, advertisedInterval * 1000)) : 5000;
35
+ // A second bound protects against clock rollback and malformed/mock clocks.
36
+ const maxPolls = Math.ceil(10 * 60_000 / interval);
37
+ for (let polls = 0; polls < maxPolls && now() < deadline; polls++) {
38
+ await sleep(Math.min(interval, deadline - now()));
39
+ if (now() >= deadline) break;
40
+ const result = await post('/api/setup/v1/challenges/poll', { challengeSecret: challenge.challengeSecret });
41
+ if (result.status === 'PENDING') continue;
42
+ if (result.status !== 'APPROVED' || typeof result.grant !== 'string' || !result.grant || !Array.isArray(result.clients) || !result.clients.includes('reasontrail-cli')) throw new Error('Device authorization was denied, expired, or did not approve this client.');
43
+ let installing = false;
44
+ try {
45
+ const credential = await post('/api/setup/v1/credentials', { client: 'reasontrail-cli' }, result.grant);
46
+ if (typeof credential.token !== 'string' || !credential.token.startsWith('rtmcp_')) throw new Error('Credential was already delivered or invalid.');
47
+ installing = true;
48
+ const installed = await install(credential.token);
49
+ // Destroy the cleanup grant only after validation and durable installation.
50
+ await post('/api/setup/v1/complete', {}, result.grant);
51
+ return installed;
52
+ } catch {
53
+ let revoked = false, restored = !installing;
54
+ try { await post('/api/setup/v1/abort', {}, result.grant); revoked = true; } catch {}
55
+ if (installing) { try { await rollback(); restored = true; } catch {} }
56
+ throw new Error(`Device login could not be installed. ${revoked ? 'The issued device credential was revoked.' : 'Revocation could not be confirmed; revoke this device in Settings.'}${restored ? '' : ' The local credential store also needs repair.'} Start a new login.`);
57
+ }
58
+ }
59
+ throw new Error('Device authorization expired. Start a new login.');
60
+ }