toolroll 0.9.115 → 0.9.117

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 (145) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +43 -26
  3. package/dist/acp-agents.js +14 -1
  4. package/dist/acp-client.js +19 -1
  5. package/dist/agent-change-check.js +60 -0
  6. package/dist/agent-change-schema.js +19 -0
  7. package/dist/agent-detect.js +11 -1
  8. package/dist/agent-fence.js +39 -10
  9. package/dist/agent-network-request.js +108 -0
  10. package/dist/agent-requests.js +105 -0
  11. package/dist/approval-summary.js +3 -3
  12. package/dist/backup.js +17 -1
  13. package/dist/batch-checks.js +81 -18
  14. package/dist/browser/terminal.js +41 -41
  15. package/dist/browser/workspace.css +2 -2
  16. package/dist/browser/workspace.js +36 -36
  17. package/dist/builder.js +3 -1
  18. package/dist/candidate-materialize.js +119 -0
  19. package/dist/central-enrollment-contract.js +156 -0
  20. package/dist/central-recovery-stage.js +329 -0
  21. package/dist/chat-actions.js +101 -2
  22. package/dist/chat-channel.js +40 -0
  23. package/dist/check-only-standing.js +13 -0
  24. package/dist/check-only.js +25 -13
  25. package/dist/check-recovery-hold.js +199 -0
  26. package/dist/check-recovery-index-schema.js +3 -0
  27. package/dist/check-screenshots.js +83 -0
  28. package/dist/cli.js +125 -6
  29. package/dist/codex-limits.js +4 -0
  30. package/dist/connect-cli.js +257 -11
  31. package/dist/contracts/chat-actions.js +4 -0
  32. package/dist/contracts/console-api.js +15 -4
  33. package/dist/contracts/engine-api.js +344 -2
  34. package/dist/contracts/lead-tools.js +56 -2
  35. package/dist/contracts/provider.js +1 -1
  36. package/dist/contracts/route.js +1 -1
  37. package/dist/contracts/terminal-connection.js +50 -0
  38. package/dist/converse.js +80 -4
  39. package/dist/device-pair.js +280 -0
  40. package/dist/direct-chat-artifacts.js +347 -0
  41. package/dist/direct-chat-catalog.js +311 -0
  42. package/dist/direct-chat-fence.js +96 -0
  43. package/dist/direct-chat-git.js +343 -0
  44. package/dist/direct-chat-laptop.js +19 -0
  45. package/dist/direct-chat-schema.js +181 -0
  46. package/dist/direct-chat-ship.js +861 -0
  47. package/dist/direct-chat-workspace.js +389 -0
  48. package/dist/direct-chat.js +2107 -0
  49. package/dist/doctor.js +1 -1
  50. package/dist/easy-start.js +18 -0
  51. package/dist/egress.js +25 -4
  52. package/dist/engine-chat.js +454 -0
  53. package/dist/engine-reads.js +141 -13
  54. package/dist/exec.js +4 -3
  55. package/dist/flexible-agents.js +8 -16
  56. package/dist/flexible-authority-end.js +2 -0
  57. package/dist/flexible-interactive-schema.js +133 -0
  58. package/dist/flexible-interactive.js +94 -0
  59. package/dist/flexible-session.js +117 -49
  60. package/dist/flexible-ship.js +87 -7
  61. package/dist/flexible-sign-in.js +10 -0
  62. package/dist/flexible-start.js +21 -3
  63. package/dist/flexible-thread.js +2 -3
  64. package/dist/flexible-turns.js +26 -5
  65. package/dist/flexible.js +13 -0
  66. package/dist/flow-triggers.js +13 -4
  67. package/dist/flows-ui.js +54 -20
  68. package/dist/handoff-cli.js +630 -0
  69. package/dist/invoke.js +55 -13
  70. package/dist/lead-contract.js +5 -4
  71. package/dist/lead-doors.js +80 -1
  72. package/dist/lead-progress.js +9 -0
  73. package/dist/lead-tools.js +682 -10
  74. package/dist/lead.js +37 -9
  75. package/dist/live-bus.js +11 -0
  76. package/dist/live-terminal.js +132 -12
  77. package/dist/local-handoff.js +363 -0
  78. package/dist/local-owner-acts.js +264 -2
  79. package/dist/local-owner.js +16 -1
  80. package/dist/multiplayer-handoff.js +528 -0
  81. package/dist/multiplayer-presence.js +471 -0
  82. package/dist/names.js +17 -4
  83. package/dist/needs-you.js +10 -0
  84. package/dist/operate.js +280 -19
  85. package/dist/policy.js +2 -2
  86. package/dist/project-delete-ui.js +18 -11
  87. package/dist/project-delete.js +65 -4
  88. package/dist/project-tools.js +1 -1
  89. package/dist/prompt.js +1 -1
  90. package/dist/provider-connection.js +2 -0
  91. package/dist/provider-home.js +251 -8
  92. package/dist/provider.js +3 -2
  93. package/dist/publish.js +119 -64
  94. package/dist/pull-request-flow.js +35 -14
  95. package/dist/read-executor-worker.js +1 -1
  96. package/dist/read-executor.js +95 -1
  97. package/dist/restore-retirement.js +152 -0
  98. package/dist/result-follow-ups.js +116 -37
  99. package/dist/route-change.js +44 -4
  100. package/dist/scope.js +62 -5
  101. package/dist/serve.js +49 -5
  102. package/dist/server/chat.js +94 -13
  103. package/dist/server/console.css +9 -9
  104. package/dist/server/direct-chat.js +583 -0
  105. package/dist/server/engine-api.js +219 -21
  106. package/dist/server/flows.js +47 -13
  107. package/dist/server/found-repos.js +25 -0
  108. package/dist/server/guards.js +20 -6
  109. package/dist/server/live.js +81 -23
  110. package/dist/server/pages.js +67 -13
  111. package/dist/server/people-tokens.js +47 -6
  112. package/dist/server/remote.js +29 -0
  113. package/dist/server/render-results.js +6 -2
  114. package/dist/server/render-settings.js +4 -2
  115. package/dist/server/render-tasks.js +18 -17
  116. package/dist/server/route-table.js +69 -2
  117. package/dist/server/settings.js +22 -7
  118. package/dist/server/task-views.js +15 -3
  119. package/dist/server/tasks.js +39 -2
  120. package/dist/server/terminals.js +185 -11
  121. package/dist/settings-proofs.js +1 -1
  122. package/dist/spend-report.js +2 -2
  123. package/dist/spend.js +3 -3
  124. package/dist/store.js +600 -59
  125. package/dist/subagent-admin.js +23 -10
  126. package/dist/subagent-backup-schema.js +36 -0
  127. package/dist/subagent-backup.js +92 -0
  128. package/dist/subagent-week.js +2 -2
  129. package/dist/subagent-work.js +70 -47
  130. package/dist/subagents-ui.js +6 -2
  131. package/dist/subagents.js +5 -2
  132. package/dist/subscription-chat.js +36 -5
  133. package/dist/subscription-usage.js +233 -0
  134. package/dist/task-live.js +2 -1
  135. package/dist/teardown-git.js +34 -4
  136. package/dist/terminal-connection.js +159 -0
  137. package/dist/terminal-safety.js +114 -0
  138. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  139. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  140. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  141. package/dist/tui/linux-x64/toolroll-tui +0 -0
  142. package/dist/tui-contract.js +1 -1
  143. package/dist/tui-launch.js +32 -1
  144. package/dist/workspace-identity-schema.js +21 -0
  145. package/package.json +4 -2
@@ -0,0 +1,347 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { appendFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
3
+ import { basename, extname, isAbsolute, join, relative } from "node:path";
4
+ import { assertManagedClonePath } from "./direct-chat-git.js";
5
+ export const MAX_ARTIFACT_BYTES = 10 * 1024 * 1024;
6
+ export const MAX_ARTIFACTS_PER_TURN = 20;
7
+ export const ALLOWED_IMAGE_MIMES = Object.freeze({
8
+ "image/png": ".png",
9
+ "image/jpeg": ".jpg",
10
+ "image/webp": ".webp",
11
+ "image/gif": ".gif",
12
+ });
13
+ export const ALLOWED_ATTACHMENT_TEXT_MIMES = Object.freeze({
14
+ "text/plain": ".txt",
15
+ "text/markdown": ".md",
16
+ "application/json": ".json",
17
+ });
18
+ const IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".webp", ".gif"]);
19
+ const SKIPPED_SCAN_DIRS = new Set([
20
+ ".git",
21
+ "node_modules",
22
+ ".toolroll-attachments",
23
+ ".next",
24
+ ".turbo",
25
+ ".venv",
26
+ "venv",
27
+ "dist",
28
+ "build",
29
+ "target",
30
+ ]);
31
+ export function detectSafeImageMime(bytes) {
32
+ if (bytes.length >= 8
33
+ && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47
34
+ && bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a) {
35
+ return "image/png";
36
+ }
37
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
38
+ return "image/jpeg";
39
+ }
40
+ if (bytes.length >= 6
41
+ && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38
42
+ && (bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
43
+ return "image/gif";
44
+ }
45
+ if (bytes.length >= 12
46
+ && bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46
47
+ && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) {
48
+ return "image/webp";
49
+ }
50
+ return null;
51
+ }
52
+ export function sanitizeArtifactFilename(raw, fallbackExt) {
53
+ const base = basename(raw.replace(/\\/g, "/"))
54
+ .replace(/[^A-Za-z0-9._-]/g, "_")
55
+ .replace(/^\.+/, "")
56
+ .slice(0, 96);
57
+ if (base === "")
58
+ return `artifact${fallbackExt}`;
59
+ return extname(base) === "" ? `${base}${fallbackExt}` : base;
60
+ }
61
+ function ensureAttachmentsExcludedFromGit(clonePath, gitDir) {
62
+ const targetGitDir = gitDir && existsSync(gitDir) ? gitDir : join(clonePath, ".git");
63
+ const excludePath = join(targetGitDir, "info", "exclude");
64
+ try {
65
+ mkdirSync(join(targetGitDir, "info"), { recursive: true });
66
+ const existing = existsSync(excludePath) ? readFileSync(excludePath, "utf8") : "";
67
+ if (!existing.split(/\r?\n/).includes(".toolroll-attachments/")) {
68
+ const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
69
+ appendFileSync(excludePath, `${prefix}.toolroll-attachments/\n`, "utf8");
70
+ }
71
+ }
72
+ catch {
73
+ }
74
+ }
75
+ export function saveDirectChatArtifact(store, input) {
76
+ if (input.bytes.length === 0) {
77
+ return { ok: false, status: 400, error: "Empty artifact or attachment." };
78
+ }
79
+ if (input.bytes.length > MAX_ARTIFACT_BYTES) {
80
+ return { ok: false, status: 413, error: "Attachment exceeds the 10 MB limit." };
81
+ }
82
+ let resolvedMime = detectSafeImageMime(input.bytes);
83
+ if (resolvedMime === null && input.kind === "attachment") {
84
+ const requested = (input.mimeType ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
85
+ if (requested in ALLOWED_ATTACHMENT_TEXT_MIMES) {
86
+ if (input.bytes.includes(0)) {
87
+ return { ok: false, status: 400, error: "Text attachments cannot contain binary NUL bytes." };
88
+ }
89
+ resolvedMime = requested;
90
+ }
91
+ }
92
+ if (resolvedMime === null) {
93
+ return { ok: false, status: 415, error: "Unsupported file type. Allowed: PNG, JPEG, WebP, GIF (and plain text, Markdown, JSON for attachments)." };
94
+ }
95
+ if (input.turnId !== null) {
96
+ const countRow = store.handle
97
+ .prepare("SELECT COUNT(*) AS n FROM direct_chat_artifact WHERE turn_id = ?")
98
+ .get(input.turnId);
99
+ if (Number(countRow?.["n"] ?? 0) >= MAX_ARTIFACTS_PER_TURN) {
100
+ return { ok: false, status: 429, error: "Artifact cap reached for this turn." };
101
+ }
102
+ }
103
+ const ext = resolvedMime in ALLOWED_IMAGE_MIMES
104
+ ? ALLOWED_IMAGE_MIMES[resolvedMime]
105
+ : ALLOWED_ATTACHMENT_TEXT_MIMES[resolvedMime];
106
+ const id = randomBytes(16).toString("hex");
107
+ const safeName = sanitizeArtifactFilename(input.filename, ext);
108
+ const sha256 = createHash("sha256").update(input.bytes).digest("hex");
109
+ const subdir = input.kind === "attachment" ? "attachments" : "artifacts";
110
+ const storageRel = join(subdir, input.threadId, `${id}${ext}`);
111
+ const storageAbs = join(input.stateRoot, "direct-chat", storageRel);
112
+ mkdirSync(join(input.stateRoot, "direct-chat", subdir, input.threadId), { recursive: true, mode: 0o700 });
113
+ writeFileSync(storageAbs, input.bytes, { mode: 0o600 });
114
+ let cloneRelativePath = null;
115
+ if (input.kind === "attachment" && input.clonePath) {
116
+ const managed = assertManagedClonePath(input.stateRoot, input.clonePath);
117
+ if (!managed.ok) {
118
+ return { ok: false, status: 409, error: managed.error };
119
+ }
120
+ ensureAttachmentsExcludedFromGit(managed.realClone, input.gitDir);
121
+ const attDir = join(managed.realClone, ".toolroll-attachments");
122
+ mkdirSync(attDir, { recursive: true, mode: 0o700 });
123
+ const cloneFilename = `${id.slice(0, 8)}-${safeName}`;
124
+ writeFileSync(join(attDir, cloneFilename), input.bytes, { mode: 0o600 });
125
+ cloneRelativePath = `.toolroll-attachments/${cloneFilename}`;
126
+ }
127
+ const createdAt = (input.now ?? new Date()).toISOString();
128
+ store.handle.prepare(`
129
+ INSERT INTO direct_chat_artifact (
130
+ id, thread_id, turn_id, kind, filename, mime_type, byte_size, sha256, storage_path, source_path, created_at
131
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
132
+ `).run(id, input.threadId, input.turnId, input.kind, safeName, resolvedMime, input.bytes.length, sha256, storageRel, input.sourcePath ?? cloneRelativePath, createdAt);
133
+ return {
134
+ ok: true,
135
+ cloneRelativePath,
136
+ artifact: {
137
+ id,
138
+ threadId: input.threadId,
139
+ turnId: input.turnId,
140
+ kind: input.kind,
141
+ filename: safeName,
142
+ mimeType: resolvedMime,
143
+ byteSize: input.bytes.length,
144
+ sha256,
145
+ storagePath: storageRel,
146
+ sourcePath: input.sourcePath ?? cloneRelativePath,
147
+ createdAt,
148
+ },
149
+ };
150
+ }
151
+ export function listArtifactsForThread(store, threadId) {
152
+ const rows = store.handle
153
+ .prepare("SELECT * FROM direct_chat_artifact WHERE thread_id = ? ORDER BY created_at ASC")
154
+ .all(threadId);
155
+ return rows.map(mapArtifactRow);
156
+ }
157
+ export function getDirectChatArtifact(store, stateRoot, threadId, artifactId) {
158
+ if (!/^[0-9a-f]{32}$/.test(threadId) || !/^[0-9a-f]{32}$/.test(artifactId))
159
+ return null;
160
+ const raw = store.handle
161
+ .prepare("SELECT * FROM direct_chat_artifact WHERE id = ? AND thread_id = ?")
162
+ .get(artifactId, threadId);
163
+ if (!raw)
164
+ return null;
165
+ const row = mapArtifactRow(raw);
166
+ const root = join(stateRoot, "direct-chat");
167
+ const abs = join(root, row.storagePath);
168
+ try {
169
+ const realRoot = realpathSync(root);
170
+ const realFile = realpathSync(abs);
171
+ const rel = relative(realRoot, realFile);
172
+ if (rel === ".." || rel.startsWith(`..${"/"}`) || isAbsolute(rel))
173
+ return null;
174
+ return { row, bytes: readFileSync(realFile) };
175
+ }
176
+ catch {
177
+ return null;
178
+ }
179
+ }
180
+ function mapArtifactRow(raw) {
181
+ return {
182
+ id: String(raw["id"]),
183
+ threadId: String(raw["thread_id"]),
184
+ turnId: typeof raw["turn_id"] === "string" ? raw["turn_id"] : null,
185
+ kind: raw["kind"] === "attachment" ? "attachment" : "output",
186
+ filename: String(raw["filename"]),
187
+ mimeType: String(raw["mime_type"]),
188
+ byteSize: Number(raw["byte_size"]),
189
+ sha256: String(raw["sha256"]),
190
+ storagePath: String(raw["storage_path"]),
191
+ sourcePath: typeof raw["source_path"] === "string" ? raw["source_path"] : null,
192
+ createdAt: String(raw["created_at"]),
193
+ };
194
+ }
195
+ export function snapshotWorkspaceImages(clonePath, maxFiles = 20_000) {
196
+ const snap = new Map();
197
+ if (!existsSync(clonePath))
198
+ return snap;
199
+ let rootReal;
200
+ try {
201
+ rootReal = realpathSync(clonePath);
202
+ }
203
+ catch {
204
+ return snap;
205
+ }
206
+ let visited = 0;
207
+ const stack = [rootReal];
208
+ while (stack.length > 0 && visited < maxFiles) {
209
+ const dir = stack.pop();
210
+ let entries;
211
+ try {
212
+ entries = readdirSync(dir);
213
+ }
214
+ catch {
215
+ continue;
216
+ }
217
+ for (const name of entries) {
218
+ visited += 1;
219
+ if (visited > maxFiles)
220
+ break;
221
+ if (SKIPPED_SCAN_DIRS.has(name))
222
+ continue;
223
+ const full = join(dir, name);
224
+ let st;
225
+ try {
226
+ st = lstatSync(full);
227
+ }
228
+ catch {
229
+ continue;
230
+ }
231
+ if (st.isSymbolicLink())
232
+ continue;
233
+ if (st.isDirectory()) {
234
+ stack.push(full);
235
+ }
236
+ else if (st.isFile() && IMAGE_EXTENSIONS.has(extname(name).toLowerCase()) && st.size > 0 && st.size <= MAX_ARTIFACT_BYTES) {
237
+ const rel = relative(rootReal, full).replace(/\\/g, "/");
238
+ snap.set(rel, { size: st.size, mtimeMs: st.mtimeMs });
239
+ }
240
+ }
241
+ }
242
+ return snap;
243
+ }
244
+ export function captureNewWorkspaceArtifacts(store, input) {
245
+ const after = snapshotWorkspaceImages(input.clonePath);
246
+ const captured = [];
247
+ let rootReal;
248
+ try {
249
+ rootReal = realpathSync(input.clonePath);
250
+ }
251
+ catch {
252
+ return captured;
253
+ }
254
+ for (const [relPath, meta] of after) {
255
+ if (captured.length >= MAX_ARTIFACTS_PER_TURN)
256
+ break;
257
+ if (input.before !== undefined) {
258
+ const prev = input.before.get(relPath);
259
+ if (prev && prev.size === meta.size && prev.mtimeMs === meta.mtimeMs)
260
+ continue;
261
+ }
262
+ else if (input.sinceMs !== undefined) {
263
+ if (meta.mtimeMs < input.sinceMs)
264
+ continue;
265
+ }
266
+ else {
267
+ continue;
268
+ }
269
+ const full = join(rootReal, relPath);
270
+ try {
271
+ const st = lstatSync(full);
272
+ if (!st.isFile() || st.isSymbolicLink() || st.size > MAX_ARTIFACT_BYTES)
273
+ continue;
274
+ const bytes = readFileSync(full);
275
+ if (detectSafeImageMime(bytes) === null)
276
+ continue;
277
+ const saved = saveDirectChatArtifact(store, {
278
+ stateRoot: input.stateRoot,
279
+ threadId: input.threadId,
280
+ turnId: input.turnId,
281
+ kind: "output",
282
+ filename: basename(relPath),
283
+ bytes,
284
+ sourcePath: relPath,
285
+ now: input.now,
286
+ });
287
+ if (saved.ok)
288
+ captured.push(saved.artifact);
289
+ }
290
+ catch {
291
+ continue;
292
+ }
293
+ }
294
+ return captured;
295
+ }
296
+ export function extractBase64ImagesFromLine(line, _provider) {
297
+ const trimmed = line.trim();
298
+ if (trimmed === "" || !trimmed.includes("base64"))
299
+ return [];
300
+ let parsed;
301
+ try {
302
+ parsed = JSON.parse(trimmed);
303
+ }
304
+ catch {
305
+ return [];
306
+ }
307
+ const out = [];
308
+ const walk = (node, depth) => {
309
+ if (depth > 8 || out.length >= MAX_ARTIFACTS_PER_TURN || !node || typeof node !== "object")
310
+ return;
311
+ if (Array.isArray(node)) {
312
+ for (const item of node)
313
+ walk(item, depth + 1);
314
+ return;
315
+ }
316
+ const obj = node;
317
+ if (obj["type"] === "image" && obj["source"] && typeof obj["source"] === "object") {
318
+ const src = obj["source"];
319
+ if (src["type"] === "base64" && typeof src["data"] === "string" && src["data"].length > 16) {
320
+ try {
321
+ const bytes = Buffer.from(src["data"], "base64");
322
+ const mime = detectSafeImageMime(bytes);
323
+ if (mime !== null && bytes.length <= MAX_ARTIFACT_BYTES) {
324
+ const ext = ALLOWED_IMAGE_MIMES[mime];
325
+ out.push({ filename: `tool-capture-${out.length + 1}${ext}`, bytes });
326
+ }
327
+ }
328
+ catch {
329
+ }
330
+ }
331
+ return;
332
+ }
333
+ for (const val of Object.values(obj))
334
+ walk(val, depth + 1);
335
+ };
336
+ walk(parsed, 0);
337
+ return out;
338
+ }
339
+ export function imageContentHeaders(row) {
340
+ return {
341
+ "content-type": row.mimeType,
342
+ "content-disposition": `inline; filename="${row.filename.replace(/"/g, "")}"`,
343
+ "x-content-type-options": "nosniff",
344
+ "cache-control": "no-store",
345
+ "content-security-policy": "sandbox; default-src 'none'; img-src 'self'",
346
+ };
347
+ }
@@ -0,0 +1,311 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync, lstatSync, readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ export const DIRECT_CHAT_EFFORTS = Object.freeze(["low", "medium", "high", "xhigh", "max", "ultra"]);
6
+ const CLAUDE_EFFORTS = ["low", "medium", "high", "xhigh", "max"];
7
+ const CODEX_DEFAULT_EFFORTS = ["low", "medium", "high", "xhigh", "max"];
8
+ const GEMINI_DEFAULT_EFFORTS = ["low", "medium", "high", "xhigh"];
9
+ export function normalizeDirectChatEffort(raw, provider) {
10
+ if (typeof raw !== "string")
11
+ return null;
12
+ const lower = raw.trim().toLowerCase();
13
+ if (!DIRECT_CHAT_EFFORTS.includes(lower))
14
+ return null;
15
+ const effort = lower;
16
+ if (provider === "claude" && effort === "ultra")
17
+ return "max";
18
+ if (provider === "gemini" && effort === "ultra")
19
+ return "max";
20
+ return effort;
21
+ }
22
+ function prettyCodexLabel(slug, displayName) {
23
+ if (typeof displayName === "string" && displayName.trim() !== "") {
24
+ const trimmed = displayName.trim();
25
+ if (/[A-Z]/.test(trimmed))
26
+ return trimmed.slice(0, 80);
27
+ }
28
+ return slug
29
+ .split("-")
30
+ .map(part => {
31
+ if (part.toLowerCase() === "gpt")
32
+ return "GPT";
33
+ if (/^[0-9]/.test(part))
34
+ return part;
35
+ return part.charAt(0).toUpperCase() + part.slice(1);
36
+ })
37
+ .join(" ")
38
+ .replace(/^GPT /, "GPT-");
39
+ }
40
+ function prettyClaudeLabel(id) {
41
+ switch (id) {
42
+ case "opus": return "Claude Opus 5.5";
43
+ case "sonnet": return "Claude Sonnet 5.5";
44
+ case "haiku": return "Claude Haiku 5.5";
45
+ case "fable": return "Claude Fable";
46
+ default:
47
+ return id
48
+ .replace(/^claude-/, "Claude ")
49
+ .replace(/-([0-9]+)-([0-9]+)$/, " $1.$2")
50
+ .replace(/-/g, " ")
51
+ .replace(/\b[a-z]/g, c => c.toUpperCase());
52
+ }
53
+ }
54
+ export function readCodexSubscriptionModels(homeDir = homedir()) {
55
+ const path = join(homeDir, ".codex", "models_cache.json");
56
+ try {
57
+ if (!existsSync(path))
58
+ return [];
59
+ if (lstatSync(path).size >= 2_000_000)
60
+ return [];
61
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
62
+ const rawModels = Array.isArray(parsed)
63
+ ? parsed
64
+ : (parsed && typeof parsed === "object" && Array.isArray(parsed["models"])
65
+ ? parsed["models"]
66
+ : []);
67
+ const out = [];
68
+ const seen = new Set();
69
+ for (const raw of rawModels) {
70
+ if (!raw || typeof raw !== "object")
71
+ continue;
72
+ const entry = raw;
73
+ const slug = typeof entry["slug"] === "string" ? entry["slug"].trim() : "";
74
+ if (slug === "" || seen.has(slug))
75
+ continue;
76
+ if (slug === "codex-auto-review" || entry["visibility"] === "hide")
77
+ continue;
78
+ seen.add(slug);
79
+ const rawLevels = Array.isArray(entry["supported_reasoning_levels"])
80
+ ? entry["supported_reasoning_levels"]
81
+ : [];
82
+ const efforts = [];
83
+ for (const lvl of rawLevels) {
84
+ const eff = typeof lvl === "string"
85
+ ? lvl
86
+ : (lvl && typeof lvl === "object" && typeof lvl["effort"] === "string"
87
+ ? String(lvl["effort"])
88
+ : "");
89
+ const norm = normalizeDirectChatEffort(eff, "codex");
90
+ if (norm && !efforts.includes(norm))
91
+ efforts.push(norm);
92
+ }
93
+ const effectiveEfforts = efforts.length > 0 ? efforts : [...CODEX_DEFAULT_EFFORTS];
94
+ const rawDefault = normalizeDirectChatEffort(typeof entry["default_reasoning_level"] === "string" ? entry["default_reasoning_level"] : null, "codex");
95
+ const defaultEffort = (rawDefault && effectiveEfforts.includes(rawDefault))
96
+ ? rawDefault
97
+ : (effectiveEfforts.includes("high") ? "high" : effectiveEfforts[0] ?? null);
98
+ const ctxRaw = entry["context_window"];
99
+ const contextWindow = typeof ctxRaw === "number" && Number.isFinite(ctxRaw) && ctxRaw > 0
100
+ ? Math.round(ctxRaw)
101
+ : null;
102
+ const displayName = typeof entry["display_name"] === "string" ? entry["display_name"] : undefined;
103
+ out.push({
104
+ slug,
105
+ label: prettyCodexLabel(slug, displayName),
106
+ efforts: effectiveEfforts,
107
+ defaultEffort,
108
+ contextWindow,
109
+ });
110
+ if (out.length >= 24)
111
+ break;
112
+ }
113
+ return out;
114
+ }
115
+ catch {
116
+ return [];
117
+ }
118
+ }
119
+ const AGY_EFFORT_ORDER = ["low", "medium", "high", "xhigh", "max"];
120
+ export function parseAgyModelsOutput(stdout) {
121
+ const variantMap = new Map();
122
+ const grouped = new Map();
123
+ const order = [];
124
+ for (const rawLine of stdout.split(/\r?\n/)) {
125
+ const line = rawLine.trim();
126
+ if (line === "" || line.toLowerCase().startsWith("fetching "))
127
+ continue;
128
+ const parts = line.split(/\t+/);
129
+ const rawId = (parts[0] ?? "").trim();
130
+ const rawLabel = (parts[1] ?? "").trim();
131
+ if (rawId === "" || /\s/.test(rawId))
132
+ continue;
133
+ if (rawId.startsWith("claude-"))
134
+ continue;
135
+ const suffixMatch = /^(.+)-(low|medium|high|xhigh|max)$/.exec(rawId);
136
+ if (suffixMatch) {
137
+ const baseId = suffixMatch[1];
138
+ const eff = suffixMatch[2];
139
+ variantMap.set(`${baseId}:${eff}`, rawId);
140
+ const cleanLabel = (rawLabel !== "" ? rawLabel : baseId)
141
+ .replace(/\s*\((?:Low|Medium|High|XHigh|Max)\)\s*$/i, "")
142
+ .trim();
143
+ let entry = grouped.get(baseId);
144
+ if (!entry) {
145
+ entry = {
146
+ id: baseId,
147
+ label: cleanLabel || baseId,
148
+ efforts: [],
149
+ contextWindow: baseId.startsWith("gemini-") ? 1_000_000 : null,
150
+ };
151
+ grouped.set(baseId, entry);
152
+ order.push(baseId);
153
+ }
154
+ if (!entry.efforts.includes(eff))
155
+ entry.efforts.push(eff);
156
+ }
157
+ else {
158
+ if (!grouped.has(rawId)) {
159
+ grouped.set(rawId, {
160
+ id: rawId,
161
+ label: rawLabel || rawId,
162
+ efforts: [...GEMINI_DEFAULT_EFFORTS],
163
+ contextWindow: rawId.startsWith("gemini-") ? 1_000_000 : null,
164
+ });
165
+ order.push(rawId);
166
+ }
167
+ }
168
+ }
169
+ const models = order.map(id => {
170
+ const g = grouped.get(id);
171
+ const sortedEfforts = [...g.efforts].sort((a, b) => AGY_EFFORT_ORDER.indexOf(a) - AGY_EFFORT_ORDER.indexOf(b));
172
+ const defaultEffort = sortedEfforts.includes("high") ? "high" : (sortedEfforts[0] ?? null);
173
+ return {
174
+ provider: "gemini",
175
+ id: g.id,
176
+ label: g.label,
177
+ efforts: sortedEfforts,
178
+ defaultEffort,
179
+ contextWindow: g.contextWindow,
180
+ };
181
+ });
182
+ return { models, variantMap };
183
+ }
184
+ let cachedAgy = null;
185
+ let agyFetchInFlight = false;
186
+ const AGY_CACHE_TTL_MS = 10 * 60 * 1_000;
187
+ function locateAgyBinary(homeDir = homedir()) {
188
+ for (const candidate of [`${homeDir}/.local/bin/agy`, `${homeDir}/.gemini/bin/agy`, "/opt/homebrew/bin/agy", "/usr/local/bin/agy"]) {
189
+ if (existsSync(candidate))
190
+ return candidate;
191
+ }
192
+ return null;
193
+ }
194
+ export function warmAgyCatalog(homeDir = homedir()) {
195
+ if (agyFetchInFlight)
196
+ return;
197
+ if (cachedAgy !== null && Date.now() - cachedAgy.fetchedAt < AGY_CACHE_TTL_MS)
198
+ return;
199
+ const bin = locateAgyBinary(homeDir);
200
+ if (bin === null)
201
+ return;
202
+ agyFetchInFlight = true;
203
+ execFile(bin, ["models"], { timeout: 6_000, maxBuffer: 256 * 1024 }, (err, stdout) => {
204
+ agyFetchInFlight = false;
205
+ if (err || typeof stdout !== "string" || stdout.trim() === "")
206
+ return;
207
+ const parsed = parseAgyModelsOutput(stdout);
208
+ if (parsed.models.length > 0) {
209
+ cachedAgy = { fetchedAt: Date.now(), parsed };
210
+ }
211
+ });
212
+ }
213
+ export function resolveAgyModelForEffort(modelId, effort) {
214
+ const trimmed = modelId.trim();
215
+ if (trimmed === "")
216
+ return trimmed;
217
+ const eff = effort ?? "high";
218
+ const baseMatch = /^(.+)-(low|medium|high|xhigh|max)$/.exec(trimmed);
219
+ const baseId = baseMatch ? baseMatch[1] : trimmed;
220
+ const variant = cachedAgy?.parsed.variantMap.get(`${baseId}:${eff}`);
221
+ if (variant)
222
+ return variant;
223
+ if (baseId === "gemini-4-neon" || baseId === "gemini-4-hydrogen") {
224
+ const allowed = eff === "max" ? "xhigh" : eff;
225
+ return `${baseId}-${allowed}`;
226
+ }
227
+ if (baseId === "gemini-4-carbon" || baseId === "gemini-4-argon" || baseId === "gemini-3.8-flash") {
228
+ const allowed = (eff === "xhigh" || eff === "max") ? "high" : eff;
229
+ return `${baseId}-${allowed}`;
230
+ }
231
+ return trimmed;
232
+ }
233
+ export function listDirectChatSubscriptionModels(store, homeDir = homedir()) {
234
+ warmAgyCatalog(homeDir);
235
+ const claudeModels = [
236
+ { provider: "claude", id: "opus", label: "Claude Opus 5.5", efforts: [...CLAUDE_EFFORTS], defaultEffort: "high", contextWindow: 1_000_000 },
237
+ { provider: "claude", id: "sonnet", label: "Claude Sonnet 5.5", efforts: [...CLAUDE_EFFORTS], defaultEffort: "high", contextWindow: 1_000_000 },
238
+ { provider: "claude", id: "haiku", label: "Claude Haiku 5.5", efforts: ["low", "medium", "high"], defaultEffort: "medium", contextWindow: 200_000 },
239
+ { provider: "claude", id: "fable", label: "Claude Fable", efforts: [...CLAUDE_EFFORTS], defaultEffort: "high", contextWindow: 1_000_000 },
240
+ ];
241
+ if (store) {
242
+ try {
243
+ const rows = store.handle
244
+ .prepare(`SELECT id, name, context FROM model_seen WHERE source = 'claude' ORDER BY last_seen_at DESC LIMIT 12`)
245
+ .all();
246
+ const seenClaude = new Set(["opus", "sonnet", "haiku", "fable", "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5"]);
247
+ for (const row of rows) {
248
+ if (!row.id || seenClaude.has(row.id))
249
+ continue;
250
+ seenClaude.add(row.id);
251
+ claudeModels.push({
252
+ provider: "claude",
253
+ id: row.id,
254
+ label: row.name && row.name.trim() !== "" ? row.name.trim() : prettyClaudeLabel(row.id),
255
+ efforts: [...CLAUDE_EFFORTS],
256
+ defaultEffort: "high",
257
+ contextWindow: typeof row.context === "number" && row.context > 0 ? row.context : 200_000,
258
+ });
259
+ }
260
+ }
261
+ catch {
262
+ }
263
+ }
264
+ const codexCache = readCodexSubscriptionModels(homeDir);
265
+ const codexModels = codexCache.length > 0
266
+ ? codexCache.map(one => ({
267
+ provider: "codex",
268
+ id: one.slug,
269
+ label: one.label,
270
+ efforts: one.efforts,
271
+ defaultEffort: one.defaultEffort,
272
+ contextWindow: one.contextWindow,
273
+ }))
274
+ : [
275
+ { provider: "codex", id: "gpt-6.2-sol", label: "GPT-6.2 Sol", efforts: [...CODEX_DEFAULT_EFFORTS, "ultra"], defaultEffort: "high", contextWindow: 500_000 },
276
+ { provider: "codex", id: "gpt-6.2-astra", label: "GPT-6.2 Astra", efforts: [...CODEX_DEFAULT_EFFORTS, "ultra"], defaultEffort: "high", contextWindow: 272_000 },
277
+ { provider: "codex", id: "gpt-6-astra", label: "GPT-6 Astra", efforts: [...CODEX_DEFAULT_EFFORTS, "ultra"], defaultEffort: "high", contextWindow: 272_000 },
278
+ { provider: "codex", id: "gpt-6-sol", label: "GPT-6 Sol", efforts: [...CODEX_DEFAULT_EFFORTS, "ultra"], defaultEffort: "high", contextWindow: 272_000 },
279
+ { provider: "codex", id: "gpt-6-luna", label: "GPT-6 Luna", efforts: [...CODEX_DEFAULT_EFFORTS], defaultEffort: "high", contextWindow: 272_000 },
280
+ ];
281
+ const geminiModels = cachedAgy && cachedAgy.parsed.models.length > 0
282
+ ? cachedAgy.parsed.models
283
+ : [
284
+ { provider: "gemini", id: "gemini-4-neon", label: "Gemini 4 Neon", efforts: ["low", "medium", "high", "xhigh"], defaultEffort: "high", contextWindow: 1_000_000 },
285
+ { provider: "gemini", id: "gemini-4-carbon", label: "Gemini 4 Carbon", efforts: ["low", "medium", "high"], defaultEffort: "high", contextWindow: 1_000_000 },
286
+ { provider: "gemini", id: "gemini-4-argon", label: "Gemini 4 Argon", efforts: ["low", "medium", "high"], defaultEffort: "high", contextWindow: 1_000_000 },
287
+ { provider: "gemini", id: "gemini-4-hydrogen", label: "Gemini 4 Hydrogen", efforts: ["low", "medium", "high", "xhigh"], defaultEffort: "high", contextWindow: 1_000_000 },
288
+ { provider: "gemini", id: "gemini-3.8-flash", label: "Gemini 3.8 Flash", efforts: ["low", "medium", "high"], defaultEffort: "high", contextWindow: 1_000_000 },
289
+ ];
290
+ return [...claudeModels, ...codexModels, ...geminiModels];
291
+ }
292
+ export function defaultContextWindowFor(provider, modelId, homeDir = homedir()) {
293
+ const lower = modelId.trim().toLowerCase();
294
+ if (provider === "claude") {
295
+ if (lower.includes("haiku"))
296
+ return 200_000;
297
+ return 1_000_000;
298
+ }
299
+ if (provider === "codex") {
300
+ const fromCache = readCodexSubscriptionModels(homeDir).find(m => m.slug.toLowerCase() === lower);
301
+ if (fromCache?.contextWindow)
302
+ return fromCache.contextWindow;
303
+ if (lower.includes("6.2-sol") || lower.includes("6.1-sol") || lower.includes("6.1-terra"))
304
+ return 500_000;
305
+ return 272_000;
306
+ }
307
+ if (provider === "gemini") {
308
+ return 1_000_000;
309
+ }
310
+ return null;
311
+ }