@r-33/r33-claude 0.0.0-stage → 0.7.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,3851 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/main/main.ts
4
+ import { realpathSync as realpathSync3 } from "node:fs";
5
+ import { pathToFileURL } from "node:url";
6
+
7
+ // src/cli/key-command/key-command.ts
8
+ var keyCommand = (args) => {
9
+ const [first, second] = args;
10
+ if (first === "current") return { kind: "current" };
11
+ if (first === "list") return { kind: "list" };
12
+ if (first === "use") {
13
+ return second === void 0 ? { kind: "use" } : { kind: "use", selector: second };
14
+ }
15
+ return { kind: "unknown" };
16
+ };
17
+
18
+ // src/cli/model-command/model-command.ts
19
+ var modelCommand = (args) => {
20
+ const [first, second] = args;
21
+ if (first === "list") return { kind: "list" };
22
+ if (first === "check") {
23
+ return second === void 0 ? { kind: "check" } : { kind: "check", model: second };
24
+ }
25
+ return { kind: "unknown" };
26
+ };
27
+
28
+ // src/keys/active-key-path/active-key-path.ts
29
+ import { homedir } from "node:os";
30
+ import { join } from "node:path";
31
+ var activeKeyPath = () => join(homedir(), ".config", "r33-claude", "active-key");
32
+
33
+ // src/keys/default-key-expiry/default-key-expiry.ts
34
+ var KEY_TTL_MS = 365 * 24 * 60 * 60 * 1e3;
35
+ var defaultKeyExpiry = (now = /* @__PURE__ */ new Date()) => new Date(now.getTime() + KEY_TTL_MS).toISOString();
36
+
37
+ // src/keys/load-saved-keys/load-saved-keys.ts
38
+ import { existsSync, readFileSync } from "node:fs";
39
+ import { homedir as homedir3 } from "node:os";
40
+ import { join as join3 } from "node:path";
41
+
42
+ // src/keys/parse-store/parse-store.ts
43
+ var parseStore = (raw) => {
44
+ try {
45
+ const data = JSON.parse(raw);
46
+ if (data === null || typeof data !== "object") return [];
47
+ const keys = data["keys"];
48
+ if (!Array.isArray(keys)) return [];
49
+ return keys.filter(
50
+ (entry) => entry !== null && typeof entry === "object" && typeof entry["key"] === "string" && entry["key"].startsWith("sk-")
51
+ );
52
+ } catch {
53
+ return [];
54
+ }
55
+ };
56
+
57
+ // src/keys/store-path/store-path.ts
58
+ import { homedir as homedir2 } from "node:os";
59
+ import { join as join2 } from "node:path";
60
+ var storePath = () => join2(homedir2(), ".config", "r33-claude", "keys.json");
61
+
62
+ // src/keys/load-saved-keys/load-saved-keys.ts
63
+ var loadSavedKeys = () => {
64
+ const file = storePath();
65
+ if (existsSync(file)) return parseStore(readFileSync(file, "utf8"));
66
+ const legacy = join3(
67
+ homedir3(),
68
+ ".config",
69
+ "route33-claude-setup",
70
+ "keys.json"
71
+ );
72
+ if (existsSync(legacy)) return parseStore(readFileSync(legacy, "utf8"));
73
+ return [];
74
+ };
75
+
76
+ // src/keys/find-saved-key/find-saved-key.ts
77
+ var findSavedKey = (selector) => {
78
+ const trimmed = selector.trim();
79
+ if (trimmed === "") return null;
80
+ const keys = loadSavedKeys();
81
+ const byName = keys.find((entry) => entry.name === trimmed);
82
+ if (byName !== void 0) return byName;
83
+ const byId = keys.find((entry) => entry.id === trimmed);
84
+ return byId ?? null;
85
+ };
86
+
87
+ // src/keys/mask-key/mask-key.ts
88
+ var maskKey = (key) => {
89
+ if (typeof key !== "string" || key.length < 10) return "(unreadable key)";
90
+ return `${key.slice(0, 6)}\u2026${key.slice(-4)}`;
91
+ };
92
+
93
+ // src/keys/read-active-key/read-active-key.ts
94
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
95
+ var readActiveKey = () => {
96
+ const file = activeKeyPath();
97
+ if (!existsSync2(file)) return null;
98
+ const selector = readFileSync2(file, "utf8").trim();
99
+ return selector === "" ? null : selector;
100
+ };
101
+
102
+ // src/keys/save-key/save-key.ts
103
+ import { mkdirSync, writeFileSync } from "node:fs";
104
+ import { dirname } from "node:path";
105
+ var saveKey = (key, name) => {
106
+ const keys = loadSavedKeys();
107
+ if (keys.some((entry) => entry.key === key)) return "duplicate";
108
+ const nextKeys = [
109
+ ...keys,
110
+ {
111
+ id: `k_${String(keys.length + 1)}`,
112
+ key,
113
+ ...name !== void 0 && name !== "" ? { name } : {},
114
+ addedAt: (/* @__PURE__ */ new Date()).toISOString()
115
+ }
116
+ ];
117
+ try {
118
+ const file = storePath();
119
+ mkdirSync(dirname(file), { recursive: true, mode: 448 });
120
+ writeFileSync(file, `${JSON.stringify({ keys: nextKeys }, null, 2)}
121
+ `, {
122
+ mode: 384
123
+ });
124
+ return "saved";
125
+ } catch {
126
+ return "failed";
127
+ }
128
+ };
129
+
130
+ // src/keys/write-active-key/write-active-key.ts
131
+ import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
132
+ import { dirname as dirname2 } from "node:path";
133
+ var writeActiveKey = (selector) => {
134
+ const file = activeKeyPath();
135
+ mkdirSync2(dirname2(file), { recursive: true, mode: 448 });
136
+ writeFileSync2(file, `${selector}
137
+ `, { mode: 384 });
138
+ };
139
+
140
+ // src/cli/key-current/key-current.ts
141
+ var keyCurrent = () => {
142
+ const selector = readActiveKey();
143
+ if (selector === null) {
144
+ return {
145
+ error: "No active key \u2014 switch one first: r33-claude key use <name>"
146
+ };
147
+ }
148
+ const entry = findSavedKey(selector);
149
+ if (entry === null) {
150
+ return {
151
+ error: `Active key "${selector}" is not in the local store \u2014 switch one first: r33-claude key use <name>`
152
+ };
153
+ }
154
+ return { key: entry.key };
155
+ };
156
+
157
+ // src/cli/key-list/key-list.ts
158
+ var keyList = () => {
159
+ const selector = readActiveKey();
160
+ return loadSavedKeys().map((entry) => ({
161
+ name: entry.name ?? entry.id,
162
+ masked: maskKey(entry.key),
163
+ active: (entry.name ?? entry.id) === selector || entry.id === selector
164
+ }));
165
+ };
166
+
167
+ // src/settings/read-settings/read-settings.ts
168
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
169
+
170
+ // src/settings/settings-path/settings-path.ts
171
+ import { homedir as homedir4 } from "node:os";
172
+ import { join as join4 } from "node:path";
173
+ var settingsPath = () => join4(homedir4(), ".claude", "settings.json");
174
+
175
+ // src/settings/read-settings/read-settings.ts
176
+ var readSettings = () => {
177
+ const file = settingsPath();
178
+ if (!existsSync3(file)) return { settings: {}, existed: false, broken: false };
179
+ try {
180
+ const parsed = JSON.parse(readFileSync3(file, "utf8"));
181
+ const isSettingsObject = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed);
182
+ return {
183
+ settings: isSettingsObject ? parsed : {},
184
+ existed: true,
185
+ broken: !isSettingsObject
186
+ };
187
+ } catch {
188
+ return { settings: {}, existed: true, broken: true };
189
+ }
190
+ };
191
+
192
+ // src/settings/write-route33-settings/write-route33-settings.ts
193
+ import {
194
+ chmodSync,
195
+ copyFileSync,
196
+ existsSync as existsSync4,
197
+ mkdirSync as mkdirSync3,
198
+ writeFileSync as writeFileSync3
199
+ } from "node:fs";
200
+ import { homedir as homedir5 } from "node:os";
201
+ import { join as join5 } from "node:path";
202
+ var WIZARD_OWNED_ENV_PATTERN = /^(ANTHROPIC_|MAX_THINKING_TOKENS$|CLAUDE_CODE_API_KEY_HELPER_TTL_MS$)/;
203
+ var writeRoute33Settings = (env, options) => {
204
+ const { settings: settings2, broken } = readSettings();
205
+ const file = settingsPath();
206
+ let backup = null;
207
+ if (existsSync4(file)) {
208
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[T:.]/g, "-").slice(0, 19);
209
+ backup = join5(homedir5(), ".claude", `settings.backup-${stamp}.json`);
210
+ copyFileSync(file, backup);
211
+ chmodSync(backup, 384);
212
+ }
213
+ const existingEnv = settings2["env"] !== null && typeof settings2["env"] === "object" && !Array.isArray(settings2["env"]) ? settings2["env"] : {};
214
+ const mergedEnv = {};
215
+ for (const [envKey, value] of Object.entries(existingEnv)) {
216
+ if (!WIZARD_OWNED_ENV_PATTERN.test(envKey)) mergedEnv[envKey] = value;
217
+ }
218
+ for (const [envKey, value] of Object.entries(env)) mergedEnv[envKey] = value;
219
+ const next = { ...settings2, env: mergedEnv };
220
+ if (options?.apiKeyHelper === void 0) {
221
+ delete next["apiKeyHelper"];
222
+ } else {
223
+ next["apiKeyHelper"] = options.apiKeyHelper;
224
+ }
225
+ mkdirSync3(join5(homedir5(), ".claude"), { recursive: true });
226
+ writeFileSync3(settingsPath(), `${JSON.stringify(next, null, 2)}
227
+ `, {
228
+ mode: 384
229
+ });
230
+ chmodSync(settingsPath(), 384);
231
+ return { backup, broken };
232
+ };
233
+
234
+ // src/cli/key-use-audit/key-use-audit.ts
235
+ var keyUseAudit = () => {
236
+ const warnings = [];
237
+ const { settings: settings2 } = readSettings();
238
+ const env = settings2["env"];
239
+ const envRecord = env !== null && typeof env === "object" && !Array.isArray(env) ? env : {};
240
+ if (typeof envRecord["ANTHROPIC_AUTH_TOKEN"] === "string") {
241
+ warnings.push(
242
+ "Claude Code settings carry a static ANTHROPIC_AUTH_TOKEN, which beats the apiKeyHelper \u2014 this switch has no effect until the wizard reruns in switchable mode."
243
+ );
244
+ }
245
+ if (typeof settings2["apiKeyHelper"] !== "string") {
246
+ warnings.push(
247
+ "Claude Code settings have no apiKeyHelper \u2014 this switch has no effect until the wizard reruns in switchable mode."
248
+ );
249
+ }
250
+ return warnings;
251
+ };
252
+
253
+ // src/cli/saved-keys-hint/saved-keys-hint.ts
254
+ var savedKeysHint = () => {
255
+ const lines = loadSavedKeys().map(
256
+ (entry) => ` ${entry.name ?? entry.id} ${maskKey(entry.key)}`
257
+ );
258
+ return lines.length === 0 ? "No keys are saved yet \u2014 run the wizard to add one." : `Saved keys:
259
+ ${lines.join("\n")}`;
260
+ };
261
+
262
+ // src/cli/key-use/key-use.ts
263
+ var keyUse = (selector) => {
264
+ const trimmed = selector?.trim() ?? "";
265
+ if (trimmed === "") {
266
+ return {
267
+ ok: false,
268
+ message: `Switch which key? r33-claude key use <name>
269
+ ${savedKeysHint()}`
270
+ };
271
+ }
272
+ const entry = findSavedKey(trimmed);
273
+ if (entry === null) {
274
+ return {
275
+ ok: false,
276
+ message: `No saved key matches "${trimmed}".
277
+ ${savedKeysHint()}`
278
+ };
279
+ }
280
+ writeActiveKey(entry.name ?? entry.id);
281
+ const confirmed = `Active key: ${entry.name ?? entry.id} ${maskKey(entry.key)}`;
282
+ const warnings = keyUseAudit();
283
+ return {
284
+ ok: true,
285
+ message: warnings.length === 0 ? confirmed : `${confirmed}
286
+ ${warnings.join("\n")}`
287
+ };
288
+ };
289
+
290
+ // src/cli/run-key-command/run-key-command.ts
291
+ var KEY_USAGE = [
292
+ "usage: r33-claude key <subcommand>",
293
+ "",
294
+ " current print the active key's material (the apiKeyHelper command)",
295
+ " list list the saved keys, marking the active one",
296
+ " use <name> switch the active key"
297
+ ].join("\n");
298
+ var runKeyCommand = (command) => {
299
+ if (command.kind === "current") {
300
+ const result = keyCurrent();
301
+ if ("error" in result) {
302
+ console.error(result.error);
303
+ return 1;
304
+ }
305
+ console.log(result.key);
306
+ return 0;
307
+ }
308
+ if (command.kind === "list") {
309
+ for (const row of keyList()) {
310
+ console.log(
311
+ `${row.active ? "\u25CF" : "\u25CB"} ${row.name} ${row.masked}${row.active ? " (active)" : ""}`
312
+ );
313
+ }
314
+ return 0;
315
+ }
316
+ if (command.kind === "use") {
317
+ const result = keyUse(command.selector);
318
+ if (result.ok) {
319
+ console.log(result.message);
320
+ return 0;
321
+ }
322
+ console.error(result.message);
323
+ return 1;
324
+ }
325
+ console.error(KEY_USAGE);
326
+ return 1;
327
+ };
328
+
329
+ // src/cli/current-claude-key/current-claude-key.ts
330
+ var currentClaudeKey = () => {
331
+ const { settings: settings2 } = readSettings();
332
+ const env = settings2["env"];
333
+ if (env === null || typeof env !== "object" || Array.isArray(env))
334
+ return null;
335
+ const token = env["ANTHROPIC_AUTH_TOKEN"];
336
+ return typeof token === "string" && token.startsWith("sk-") ? token : null;
337
+ };
338
+
339
+ // src/cli/resolve-command-key/resolve-command-key.ts
340
+ var resolveCommandKey = () => {
341
+ const selector = readActiveKey();
342
+ if (selector !== null) {
343
+ const entry = findSavedKey(selector);
344
+ if (entry !== null) return { key: entry.key };
345
+ }
346
+ const current = currentClaudeKey();
347
+ if (current !== null) return { key: current };
348
+ return {
349
+ error: "No Route 33 key available \u2014 run the wizard (r33-claude) and sign in first."
350
+ };
351
+ };
352
+
353
+ // src/api/claude-thinking-mode/claude-thinking-mode.ts
354
+ var CLAUDE_4X_PATTERN = /^anthropic\/claude-(haiku|sonnet|opus)-4-5$/;
355
+ var claudeThinkingMode = (model) => CLAUDE_4X_PATTERN.test(model) ? "budget" : "adaptive";
356
+
357
+ // src/constants/constants/constants.ts
358
+ var R33_BASE_URL = "https://api.route33.ai";
359
+ var FALLBACK_MODELS = [
360
+ "anthropic/claude-fable-5",
361
+ "anthropic/claude-fable-5-1",
362
+ "anthropic/claude-haiku-4-5",
363
+ "anthropic/claude-opus-4-8",
364
+ "anthropic/claude-opus-5",
365
+ "anthropic/claude-opus-5-5",
366
+ "anthropic/claude-sonnet-5",
367
+ "anthropic/claude-sonnet-5-5",
368
+ "deepseek/deepseek-v4-flash-0731",
369
+ "deepseek/deepseek-v4-pro-0813",
370
+ "deepseek/deepseek-v4.1-flash",
371
+ "google/gemma-4-31b-it",
372
+ "google/gemini-3.1-pro-preview",
373
+ "google/gemini-3.5-flash",
374
+ "minimax/minimax-m3",
375
+ "moonshotai/kimi-k2.7-code",
376
+ "moonshotai/kimi-k3",
377
+ "nvidia/nemotron-3-ultra",
378
+ "openai/gpt-5.4",
379
+ "openai/gpt-5.4-mini",
380
+ "openai/gpt-5.4-nano",
381
+ "openai/gpt-5.5",
382
+ "openai/gpt-5.6-luna",
383
+ "openai/gpt-5.6-sol",
384
+ "openai/gpt-5.6-terra",
385
+ "openai/gpt-6-astra",
386
+ "openai/gpt-6-luna",
387
+ "openai/gpt-6-sol",
388
+ "openai/gpt-6.1-sol",
389
+ "z-ai/glm-4.7-flash",
390
+ "z-ai/glm-5.3",
391
+ "z-ai/glm-5.3-flash"
392
+ ];
393
+
394
+ // src/constants/is-embedding-model/is-embedding-model.ts
395
+ var EMBEDDING_PATTERN = /embed|bge/i;
396
+ var isEmbeddingModel = (id) => EMBEDDING_PATTERN.test(id);
397
+
398
+ // src/constants/filter-chat-models/filter-chat-models.ts
399
+ var filterChatModels = (models) => models.filter((id) => !isEmbeddingModel(id)).sort((a2, b) => a2.localeCompare(b));
400
+
401
+ // src/constants/model-slots/model-slots.ts
402
+ var MODEL_SLOTS = [
403
+ {
404
+ envKey: "ANTHROPIC_MODEL",
405
+ label: "Default model",
406
+ hint: "what new sessions start with (/model \u2192 Default)",
407
+ preferences: [
408
+ "anthropic/claude-sonnet-5-5",
409
+ "anthropic/claude-sonnet-5",
410
+ "anthropic/claude-opus-5-5",
411
+ "anthropic/claude-fable-5-1",
412
+ "anthropic/claude-haiku-4-5"
413
+ ]
414
+ },
415
+ {
416
+ envKey: "ANTHROPIC_DEFAULT_OPUS_MODEL",
417
+ label: "Opus pick",
418
+ hint: "used when you switch to Opus in /model",
419
+ preferences: [
420
+ "anthropic/claude-opus-5-5",
421
+ "anthropic/claude-opus-5",
422
+ "anthropic/claude-fable-5-1",
423
+ "anthropic/claude-opus-4-8"
424
+ ]
425
+ },
426
+ {
427
+ envKey: "ANTHROPIC_DEFAULT_SONNET_MODEL",
428
+ label: "Sonnet pick",
429
+ hint: "used when you switch to Sonnet in /model",
430
+ preferences: [
431
+ "anthropic/claude-sonnet-5-5",
432
+ "anthropic/claude-sonnet-5",
433
+ "anthropic/claude-haiku-4-5"
434
+ ]
435
+ },
436
+ {
437
+ envKey: "ANTHROPIC_DEFAULT_HAIKU_MODEL",
438
+ label: "Haiku pick",
439
+ hint: "used when you switch to Haiku in /model",
440
+ preferences: [
441
+ "anthropic/claude-haiku-4-5",
442
+ "z-ai/glm-5.3-flash",
443
+ "openai/gpt-5.4-nano"
444
+ ]
445
+ },
446
+ {
447
+ envKey: "ANTHROPIC_SMALL_FAST_MODEL",
448
+ label: "Background fast model",
449
+ hint: "titles, summaries and other background work",
450
+ preferences: [
451
+ "z-ai/glm-5.3-flash",
452
+ "anthropic/claude-haiku-4-5",
453
+ "openai/gpt-5.4-nano"
454
+ ]
455
+ }
456
+ ];
457
+
458
+ // src/api/list-models/list-models.ts
459
+ var REQUEST_TIMEOUT_MS = 3e4;
460
+ var listModels = async (key) => {
461
+ const response = await fetch(`${R33_BASE_URL}/v1/models`, {
462
+ headers: { authorization: `Bearer ${key}` },
463
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
464
+ });
465
+ if (!response.ok) {
466
+ throw new Error(
467
+ `HTTP ${String(response.status)} from GET ${R33_BASE_URL}/v1/models`
468
+ );
469
+ }
470
+ const body = await response.json();
471
+ const record = body;
472
+ let entries = [];
473
+ if (Array.isArray(record["data"])) {
474
+ entries = record["data"];
475
+ } else if (Array.isArray(record["models"])) {
476
+ entries = record["models"];
477
+ }
478
+ return entries.map((entry) => {
479
+ const r2 = entry;
480
+ return {
481
+ id: r2["id"] ?? r2["name"],
482
+ endpoints: Array.isArray(r2["endpoints"]) ? r2["endpoints"] : null
483
+ };
484
+ }).filter((entry) => typeof entry.id === "string");
485
+ };
486
+
487
+ // src/api/claude-shaped-body/claude-shaped-body.ts
488
+ var claudeShapedBody = (model, thinkingMode) => {
489
+ const body = {
490
+ model,
491
+ max_tokens: 2048,
492
+ stream: false,
493
+ system: [
494
+ {
495
+ type: "text",
496
+ text: "You are a connectivity probe for a setup wizard. Be terse.",
497
+ cache_control: { type: "ephemeral" }
498
+ }
499
+ ],
500
+ tools: [
501
+ {
502
+ name: "probe_noop",
503
+ description: "Probe tool; never called.",
504
+ input_schema: {
505
+ type: "object",
506
+ properties: {},
507
+ additionalProperties: false
508
+ }
509
+ }
510
+ ],
511
+ metadata: { user_id: "r33-claude-probe" },
512
+ messages: [
513
+ {
514
+ role: "user",
515
+ content: [{ type: "text", text: "Reply with exactly: ok" }]
516
+ }
517
+ ]
518
+ };
519
+ if (thinkingMode === "budget") {
520
+ body["thinking"] = {
521
+ type: "enabled",
522
+ budget_tokens: 1024,
523
+ display: "omitted"
524
+ };
525
+ body["context_management"] = {
526
+ edits: [{ type: "clear_thinking_20251015", keep: "all" }]
527
+ };
528
+ } else if (thinkingMode === "adaptive") {
529
+ body["thinking"] = { type: "adaptive", display: "omitted" };
530
+ body["context_management"] = {
531
+ edits: [{ type: "clear_thinking_20251015", keep: "all" }]
532
+ };
533
+ body["output_config"] = { effort: "high" };
534
+ }
535
+ return body;
536
+ };
537
+
538
+ // src/api/error-detail/error-detail.ts
539
+ var errorDetail = (body) => {
540
+ if (body === null || typeof body !== "object") return "";
541
+ const errorField = body["error"];
542
+ if (typeof errorField === "string") return errorField;
543
+ if (errorField !== null && typeof errorField === "object") {
544
+ const message = errorField["message"];
545
+ if (typeof message === "string") return message;
546
+ }
547
+ return "";
548
+ };
549
+
550
+ // src/api/probe-model/probe-model.ts
551
+ var REQUEST_TIMEOUT_MS2 = 3e4;
552
+ var CLAUDE_BETA_HEADER = "claude-code-20250219,interleaved-thinking-2025-05-14,context-management-2025-06-27,mid-conversation-tool-changes-2026-07-01,inline-tools-2026-09-15,advisor-tool-2026-03-01,thinking-token-count-2026-05-13,advanced-tool-use-2025-11-20,effort-2025-11-24";
553
+ var probeModel = async (key, model, options) => {
554
+ const thinkingOff = options?.thinkingOff ?? false;
555
+ const thinkingMode = thinkingOff ? "off" : claudeThinkingMode(model);
556
+ const response = await fetch(`${R33_BASE_URL}/v1/messages?beta=true`, {
557
+ method: "POST",
558
+ headers: {
559
+ "content-type": "application/json",
560
+ "anthropic-version": "2023-06-01",
561
+ "anthropic-beta": CLAUDE_BETA_HEADER,
562
+ authorization: `Bearer ${key}`
563
+ },
564
+ body: JSON.stringify(claudeShapedBody(model, thinkingMode)),
565
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
566
+ });
567
+ let detail = "";
568
+ try {
569
+ detail = errorDetail(await response.json());
570
+ } catch {
571
+ }
572
+ return { ok: response.ok, status: response.status, detail };
573
+ };
574
+
575
+ // src/cli/verify-model/verify-model.ts
576
+ var verifyModel = async (key, model) => {
577
+ try {
578
+ const probe = await probeModel(key, model);
579
+ if (probe.ok) return { outcome: "ok" };
580
+ if (probe.status === 400) {
581
+ try {
582
+ const fallback = await probeModel(key, model, { thinkingOff: true });
583
+ if (fallback.ok) return { outcome: "needs-thinking-off" };
584
+ } catch {
585
+ }
586
+ }
587
+ return { outcome: "rejected", status: probe.status, detail: probe.detail };
588
+ } catch {
589
+ return { outcome: "unverified", detail: "network error" };
590
+ }
591
+ };
592
+
593
+ // src/cli/model-check/model-check.ts
594
+ var modelCheck = async (model) => {
595
+ const resolved = resolveCommandKey();
596
+ if ("error" in resolved) return { error: resolved.error };
597
+ const outcome = await verifyModel(resolved.key, model);
598
+ if (outcome.outcome === "ok") return { verdict: "ok" };
599
+ if (outcome.outcome === "needs-thinking-off")
600
+ return { verdict: "needs-thinking-off" };
601
+ if (outcome.outcome === "rejected")
602
+ return { verdict: "rejected", detail: outcome.detail };
603
+ return { verdict: "unverified", detail: outcome.detail };
604
+ };
605
+
606
+ // src/cli/model-list/model-list.ts
607
+ var modelList = async () => {
608
+ const resolved = resolveCommandKey();
609
+ if ("error" in resolved) return { error: resolved.error };
610
+ try {
611
+ const entries = await listModels(resolved.key);
612
+ const messagesCapable = entries.filter(
613
+ (entry) => !entry.endpoints || entry.endpoints.includes("messages")
614
+ ).map((entry) => entry.id);
615
+ return { models: filterChatModels(messagesCapable) };
616
+ } catch (error) {
617
+ return { error: `catalog fetch failed: ${error.message}` };
618
+ }
619
+ };
620
+
621
+ // src/cli/run-model-command/run-model-command.ts
622
+ var MODEL_USAGE = [
623
+ "usage: r33-claude model <subcommand>",
624
+ "",
625
+ " list list the chat-capable models in the live catalog",
626
+ " check <id> verify a model answers Claude-Code-shaped requests"
627
+ ].join("\n");
628
+ var runModelCommand = async (command) => {
629
+ if (command.kind === "list") {
630
+ const result = await modelList();
631
+ if ("error" in result) {
632
+ console.error(result.error);
633
+ return 1;
634
+ }
635
+ for (const model of result.models) console.log(model);
636
+ return 0;
637
+ }
638
+ if (command.kind === "check") {
639
+ if (command.model === void 0) {
640
+ console.error("usage: r33-claude model check <model-id>");
641
+ return 1;
642
+ }
643
+ const result = await modelCheck(command.model);
644
+ if ("error" in result) {
645
+ console.error(result.error);
646
+ return 1;
647
+ }
648
+ if (result.verdict === "ok" || result.verdict === "needs-thinking-off") {
649
+ console.log(result.verdict);
650
+ return 0;
651
+ }
652
+ console.error(`${result.verdict}: ${result.detail}`);
653
+ return 1;
654
+ }
655
+ console.error(MODEL_USAGE);
656
+ return 1;
657
+ };
658
+
659
+ // ../../node_modules/.pnpm/@clack+core@1.6.0/node_modules/@clack/core/dist/index.mjs
660
+ import { styleText } from "node:util";
661
+ import { stdout, stdin } from "node:process";
662
+ import * as f$1 from "node:readline";
663
+ import f__default from "node:readline";
664
+
665
+ // ../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/utils.js
666
+ var getCodePointsLength = /* @__PURE__ */ (() => {
667
+ const SURROGATE_PAIR_RE = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
668
+ return (input) => {
669
+ let surrogatePairsNr = 0;
670
+ SURROGATE_PAIR_RE.lastIndex = 0;
671
+ while (SURROGATE_PAIR_RE.test(input)) {
672
+ surrogatePairsNr += 1;
673
+ }
674
+ return input.length - surrogatePairsNr;
675
+ };
676
+ })();
677
+ var isFullWidth = (x) => {
678
+ return x === 12288 || x >= 65281 && x <= 65376 || x >= 65504 && x <= 65510;
679
+ };
680
+ var isWideNotCJKTNotEmoji = (x) => {
681
+ return x === 8987 || x === 9001 || x >= 12272 && x <= 12287 || x >= 12289 && x <= 12350 || x >= 12441 && x <= 12543 || x >= 12549 && x <= 12591 || x >= 12593 && x <= 12686 || x >= 12688 && x <= 12771 || x >= 12783 && x <= 12830 || x >= 12832 && x <= 12871 || x >= 12880 && x <= 19903 || x >= 65040 && x <= 65049 || x >= 65072 && x <= 65106 || x >= 65108 && x <= 65126 || x >= 65128 && x <= 65131 || x >= 127488 && x <= 127490 || x >= 127504 && x <= 127547 || x >= 127552 && x <= 127560 || x >= 131072 && x <= 196605 || x >= 196608 && x <= 262141;
682
+ };
683
+
684
+ // ../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/index.js
685
+ var ANSI_RE = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y;
686
+ var CONTROL_RE = /[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y;
687
+ var CJKT_WIDE_RE = /(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu;
688
+ var TAB_RE = /\t{1,1000}/y;
689
+ var EMOJI_RE = new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*", "yu");
690
+ var LATIN_RE = /(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y;
691
+ var MODIFIER_RE = new RegExp("\\p{M}+", "gu");
692
+ var NO_TRUNCATION = { limit: Infinity, ellipsis: "" };
693
+ var getStringTruncatedWidth = (input, truncationOptions = {}, widthOptions = {}) => {
694
+ const LIMIT = truncationOptions.limit ?? Infinity;
695
+ const ELLIPSIS = truncationOptions.ellipsis ?? "";
696
+ const ELLIPSIS_WIDTH = truncationOptions?.ellipsisWidth ?? (ELLIPSIS ? getStringTruncatedWidth(ELLIPSIS, NO_TRUNCATION, widthOptions).width : 0);
697
+ const ANSI_WIDTH = 0;
698
+ const CONTROL_WIDTH = widthOptions.controlWidth ?? 0;
699
+ const TAB_WIDTH = widthOptions.tabWidth ?? 8;
700
+ const EMOJI_WIDTH = widthOptions.emojiWidth ?? 2;
701
+ const FULL_WIDTH_WIDTH = 2;
702
+ const REGULAR_WIDTH = widthOptions.regularWidth ?? 1;
703
+ const WIDE_WIDTH = widthOptions.wideWidth ?? FULL_WIDTH_WIDTH;
704
+ const PARSE_BLOCKS = [
705
+ [LATIN_RE, REGULAR_WIDTH],
706
+ [ANSI_RE, ANSI_WIDTH],
707
+ [CONTROL_RE, CONTROL_WIDTH],
708
+ [TAB_RE, TAB_WIDTH],
709
+ [EMOJI_RE, EMOJI_WIDTH],
710
+ [CJKT_WIDE_RE, WIDE_WIDTH]
711
+ ];
712
+ let indexPrev = 0;
713
+ let index = 0;
714
+ let length = input.length;
715
+ let lengthExtra = 0;
716
+ let truncationEnabled = false;
717
+ let truncationIndex = length;
718
+ let truncationLimit = Math.max(0, LIMIT - ELLIPSIS_WIDTH);
719
+ let unmatchedStart = 0;
720
+ let unmatchedEnd = 0;
721
+ let width = 0;
722
+ let widthExtra = 0;
723
+ outer: while (true) {
724
+ if (unmatchedEnd > unmatchedStart || index >= length && index > indexPrev) {
725
+ const unmatched = input.slice(unmatchedStart, unmatchedEnd) || input.slice(indexPrev, index);
726
+ lengthExtra = 0;
727
+ for (const char of unmatched.replaceAll(MODIFIER_RE, "")) {
728
+ const codePoint = char.codePointAt(0) || 0;
729
+ if (isFullWidth(codePoint)) {
730
+ widthExtra = FULL_WIDTH_WIDTH;
731
+ } else if (isWideNotCJKTNotEmoji(codePoint)) {
732
+ widthExtra = WIDE_WIDTH;
733
+ } else {
734
+ widthExtra = REGULAR_WIDTH;
735
+ }
736
+ if (width + widthExtra > truncationLimit) {
737
+ truncationIndex = Math.min(truncationIndex, Math.max(unmatchedStart, indexPrev) + lengthExtra);
738
+ }
739
+ if (width + widthExtra > LIMIT) {
740
+ truncationEnabled = true;
741
+ break outer;
742
+ }
743
+ lengthExtra += char.length;
744
+ width += widthExtra;
745
+ }
746
+ unmatchedStart = unmatchedEnd = 0;
747
+ }
748
+ if (index >= length) {
749
+ break outer;
750
+ }
751
+ for (let i2 = 0, l = PARSE_BLOCKS.length; i2 < l; i2++) {
752
+ const [BLOCK_RE, BLOCK_WIDTH] = PARSE_BLOCKS[i2];
753
+ BLOCK_RE.lastIndex = index;
754
+ if (BLOCK_RE.test(input)) {
755
+ lengthExtra = BLOCK_RE === CJKT_WIDE_RE ? getCodePointsLength(input.slice(index, BLOCK_RE.lastIndex)) : BLOCK_RE === EMOJI_RE ? 1 : BLOCK_RE.lastIndex - index;
756
+ widthExtra = lengthExtra * BLOCK_WIDTH;
757
+ if (width + widthExtra > truncationLimit) {
758
+ truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / BLOCK_WIDTH));
759
+ }
760
+ if (width + widthExtra > LIMIT) {
761
+ truncationEnabled = true;
762
+ break outer;
763
+ }
764
+ width += widthExtra;
765
+ unmatchedStart = indexPrev;
766
+ unmatchedEnd = index;
767
+ index = indexPrev = BLOCK_RE.lastIndex;
768
+ continue outer;
769
+ }
770
+ }
771
+ index += 1;
772
+ }
773
+ return {
774
+ width: truncationEnabled ? truncationLimit : width,
775
+ index: truncationEnabled ? truncationIndex : length,
776
+ truncated: truncationEnabled,
777
+ ellipsed: truncationEnabled && LIMIT >= ELLIPSIS_WIDTH
778
+ };
779
+ };
780
+ var dist_default = getStringTruncatedWidth;
781
+
782
+ // ../../node_modules/.pnpm/fast-string-width@3.0.2/node_modules/fast-string-width/dist/index.js
783
+ var NO_TRUNCATION2 = {
784
+ limit: Infinity,
785
+ ellipsis: "",
786
+ ellipsisWidth: 0
787
+ };
788
+ var fastStringWidth = (input, options = {}) => {
789
+ return dist_default(input, NO_TRUNCATION2, options).width;
790
+ };
791
+ var dist_default2 = fastStringWidth;
792
+
793
+ // ../../node_modules/.pnpm/fast-wrap-ansi@0.2.2/node_modules/fast-wrap-ansi/lib/main.js
794
+ var ESC = "\x1B";
795
+ var CSI = "\x9B";
796
+ var END_CODE = 39;
797
+ var ANSI_ESCAPE_BELL = "\x07";
798
+ var ANSI_CSI = "[";
799
+ var ANSI_OSC = "]";
800
+ var ANSI_SGR_TERMINATOR = "m";
801
+ var ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
802
+ var GROUP_REGEX = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`, "y");
803
+ var getClosingCode = (openingCode) => {
804
+ if (openingCode >= 30 && openingCode <= 37)
805
+ return 39;
806
+ if (openingCode >= 90 && openingCode <= 97)
807
+ return 39;
808
+ if (openingCode >= 40 && openingCode <= 47)
809
+ return 49;
810
+ if (openingCode >= 100 && openingCode <= 107)
811
+ return 49;
812
+ if (openingCode === 1 || openingCode === 2)
813
+ return 22;
814
+ if (openingCode === 3)
815
+ return 23;
816
+ if (openingCode === 4)
817
+ return 24;
818
+ if (openingCode === 7)
819
+ return 27;
820
+ if (openingCode === 8)
821
+ return 28;
822
+ if (openingCode === 9)
823
+ return 29;
824
+ if (openingCode === 0)
825
+ return 0;
826
+ return void 0;
827
+ };
828
+ var wrapAnsiCode = (code) => `${ESC}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
829
+ var wrapAnsiHyperlink = (url) => `${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;
830
+ var wrapWord = (rows, word, columns) => {
831
+ const characters = word[Symbol.iterator]();
832
+ let isInsideEscape = false;
833
+ let isInsideLinkEscape = false;
834
+ let lastRow = rows.at(-1);
835
+ let visible = lastRow === void 0 ? 0 : dist_default2(lastRow);
836
+ let currentCharacter = characters.next();
837
+ let nextCharacter = characters.next();
838
+ let rawCharacterIndex = 0;
839
+ while (!currentCharacter.done) {
840
+ const character = currentCharacter.value;
841
+ const characterLength = dist_default2(character);
842
+ if (visible + characterLength <= columns) {
843
+ rows[rows.length - 1] += character;
844
+ } else {
845
+ rows.push(character);
846
+ visible = 0;
847
+ }
848
+ if (character === ESC || character === CSI) {
849
+ isInsideEscape = true;
850
+ isInsideLinkEscape = word.startsWith(ANSI_ESCAPE_LINK, rawCharacterIndex + 1);
851
+ }
852
+ if (isInsideEscape) {
853
+ if (isInsideLinkEscape) {
854
+ if (character === ANSI_ESCAPE_BELL) {
855
+ isInsideEscape = false;
856
+ isInsideLinkEscape = false;
857
+ }
858
+ } else if (character === ANSI_SGR_TERMINATOR) {
859
+ isInsideEscape = false;
860
+ }
861
+ } else {
862
+ visible += characterLength;
863
+ if (visible === columns && !nextCharacter.done) {
864
+ rows.push("");
865
+ visible = 0;
866
+ }
867
+ }
868
+ currentCharacter = nextCharacter;
869
+ nextCharacter = characters.next();
870
+ rawCharacterIndex += character.length;
871
+ }
872
+ lastRow = rows.at(-1);
873
+ if (!visible && lastRow !== void 0 && lastRow.length && rows.length > 1) {
874
+ rows[rows.length - 2] += rows.pop();
875
+ }
876
+ };
877
+ var stringVisibleTrimSpacesRight = (string) => {
878
+ const words = string.split(" ");
879
+ let last = words.length;
880
+ while (last) {
881
+ if (dist_default2(words[last - 1])) {
882
+ break;
883
+ }
884
+ last--;
885
+ }
886
+ if (last === words.length) {
887
+ return string;
888
+ }
889
+ return words.slice(0, last).join(" ") + words.slice(last).join("");
890
+ };
891
+ var exec = (string, columns, options = {}) => {
892
+ if (options.trim !== false && string.trim() === "") {
893
+ return "";
894
+ }
895
+ let returnValue = "";
896
+ let escapeCode;
897
+ let escapeUrl;
898
+ const words = string.split(" ");
899
+ let rows = [""];
900
+ let rowLength = 0;
901
+ for (let index = 0; index < words.length; index++) {
902
+ const word = words[index];
903
+ if (options.trim !== false) {
904
+ const row = rows.at(-1) ?? "";
905
+ const trimmed = row.trimStart();
906
+ if (row.length !== trimmed.length) {
907
+ rows[rows.length - 1] = trimmed;
908
+ rowLength = dist_default2(trimmed);
909
+ }
910
+ }
911
+ if (index !== 0) {
912
+ if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
913
+ rows.push("");
914
+ rowLength = 0;
915
+ }
916
+ if (rowLength || options.trim === false) {
917
+ rows[rows.length - 1] += " ";
918
+ rowLength++;
919
+ }
920
+ }
921
+ const wordLength = dist_default2(word);
922
+ if (options.hard && wordLength > columns) {
923
+ const remainingColumns = columns - rowLength;
924
+ const breaksStartingThisLine = 1 + Math.floor((wordLength - remainingColumns - 1) / columns);
925
+ const breaksStartingNextLine = Math.floor((wordLength - 1) / columns);
926
+ if (breaksStartingNextLine < breaksStartingThisLine) {
927
+ rows.push("");
928
+ }
929
+ wrapWord(rows, word, columns);
930
+ rowLength = dist_default2(rows.at(-1) ?? "");
931
+ continue;
932
+ }
933
+ if (rowLength + wordLength > columns && rowLength && wordLength) {
934
+ if (options.wordWrap === false && rowLength < columns) {
935
+ wrapWord(rows, word, columns);
936
+ rowLength = dist_default2(rows.at(-1) ?? "");
937
+ continue;
938
+ }
939
+ rows.push("");
940
+ rowLength = 0;
941
+ }
942
+ if (rowLength + wordLength > columns && options.wordWrap === false) {
943
+ wrapWord(rows, word, columns);
944
+ rowLength = dist_default2(rows.at(-1) ?? "");
945
+ continue;
946
+ }
947
+ rows[rows.length - 1] += word;
948
+ rowLength += wordLength;
949
+ }
950
+ if (options.trim !== false) {
951
+ rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
952
+ }
953
+ const preString = rows.join("\n");
954
+ let inSurrogate = false;
955
+ for (let i2 = 0; i2 < preString.length; i2++) {
956
+ const character = preString[i2];
957
+ returnValue += character;
958
+ if (!inSurrogate) {
959
+ inSurrogate = character >= "\uD800" && character <= "\uDBFF";
960
+ if (inSurrogate) {
961
+ continue;
962
+ }
963
+ } else {
964
+ inSurrogate = false;
965
+ }
966
+ if (character === ESC || character === CSI) {
967
+ GROUP_REGEX.lastIndex = i2 + 1;
968
+ const groupsResult = GROUP_REGEX.exec(preString);
969
+ const groups = groupsResult?.groups;
970
+ if (groups?.code !== void 0) {
971
+ const code = Number.parseFloat(groups.code);
972
+ escapeCode = code === END_CODE ? void 0 : code;
973
+ } else if (groups?.uri !== void 0) {
974
+ escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
975
+ }
976
+ }
977
+ if (preString[i2 + 1] === "\n") {
978
+ if (escapeUrl) {
979
+ returnValue += wrapAnsiHyperlink("");
980
+ }
981
+ const closingCode = escapeCode ? getClosingCode(escapeCode) : void 0;
982
+ if (escapeCode && closingCode) {
983
+ returnValue += wrapAnsiCode(closingCode);
984
+ }
985
+ } else if (character === "\n") {
986
+ if (escapeCode && getClosingCode(escapeCode)) {
987
+ returnValue += wrapAnsiCode(escapeCode);
988
+ }
989
+ if (escapeUrl) {
990
+ returnValue += wrapAnsiHyperlink(escapeUrl);
991
+ }
992
+ }
993
+ }
994
+ return returnValue;
995
+ };
996
+ var CRLF_OR_LF = /\r?\n/;
997
+ function wrapAnsi(string, columns, options) {
998
+ return String(string).normalize().split(CRLF_OR_LF).map((line) => exec(line, columns, options)).join("\n");
999
+ }
1000
+
1001
+ // ../../node_modules/.pnpm/sisteransi@2.0.0/node_modules/sisteransi/dist/index.js
1002
+ var ESC2 = "\x1B";
1003
+ var CSI2 = `${ESC2}[`;
1004
+ var cursor = {
1005
+ to(x, y) {
1006
+ if (!y)
1007
+ return `${CSI2}${x + 1}G`;
1008
+ return `${CSI2}${y + 1};${x + 1}H`;
1009
+ },
1010
+ move(x, y) {
1011
+ let ret = "";
1012
+ if (x < 0)
1013
+ ret += `${CSI2}${-x}D`;
1014
+ else if (x > 0)
1015
+ ret += `${CSI2}${x}C`;
1016
+ if (y < 0)
1017
+ ret += `${CSI2}${-y}A`;
1018
+ else if (y > 0)
1019
+ ret += `${CSI2}${y}B`;
1020
+ return ret;
1021
+ },
1022
+ up: (count = 1) => `${CSI2}${count}A`,
1023
+ down: (count = 1) => `${CSI2}${count}B`,
1024
+ forward: (count = 1) => `${CSI2}${count}C`,
1025
+ backward: (count = 1) => `${CSI2}${count}D`,
1026
+ nextLine: (count = 1) => `${CSI2}E`.repeat(count),
1027
+ prevLine: (count = 1) => `${CSI2}F`.repeat(count),
1028
+ left: `${CSI2}G`,
1029
+ hide: `${CSI2}?25l`,
1030
+ show: `${CSI2}?25h`,
1031
+ save: `${ESC2}7`,
1032
+ restore: `${ESC2}8`
1033
+ };
1034
+ var erase = {
1035
+ screen: `${CSI2}2J`,
1036
+ up: (count = 1) => `${CSI2}1J`.repeat(count),
1037
+ down: (count = 1) => `${CSI2}J`.repeat(count),
1038
+ line: `${CSI2}2K`,
1039
+ lineEnd: `${CSI2}K`,
1040
+ lineStart: `${CSI2}1K`,
1041
+ lines(count) {
1042
+ let clear2 = "";
1043
+ for (let i2 = 0; i2 < count; i2++)
1044
+ clear2 += this.line + (i2 < count - 1 ? cursor.up() : "");
1045
+ if (count)
1046
+ clear2 += cursor.left;
1047
+ return clear2;
1048
+ }
1049
+ };
1050
+ var clear = {
1051
+ screen: `${ESC2}c`
1052
+ };
1053
+
1054
+ // ../../node_modules/.pnpm/@clack+core@1.6.0/node_modules/@clack/core/dist/index.mjs
1055
+ import { ReadStream } from "node:tty";
1056
+ function findCursor(o, s, l) {
1057
+ if (!l.some((r2) => !r2.disabled))
1058
+ return o;
1059
+ const t2 = o + s, n3 = Math.max(l.length - 1, 0), e = t2 < 0 ? n3 : t2 > n3 ? 0 : t2;
1060
+ return l[e]?.disabled ? findCursor(e, s < 0 ? -1 : 1, l) : e;
1061
+ }
1062
+ var a$1 = ["up", "down", "left", "right", "space", "enter", "cancel"];
1063
+ var t = [
1064
+ "January",
1065
+ "February",
1066
+ "March",
1067
+ "April",
1068
+ "May",
1069
+ "June",
1070
+ "July",
1071
+ "August",
1072
+ "September",
1073
+ "October",
1074
+ "November",
1075
+ "December"
1076
+ ];
1077
+ var settings = {
1078
+ actions: new Set(a$1),
1079
+ aliases: /* @__PURE__ */ new Map([
1080
+ // vim support
1081
+ ["k", "up"],
1082
+ ["j", "down"],
1083
+ ["h", "left"],
1084
+ ["l", "right"],
1085
+ ["", "cancel"],
1086
+ // opinionated defaults!
1087
+ ["escape", "cancel"]
1088
+ ]),
1089
+ messages: {
1090
+ cancel: "Canceled",
1091
+ error: "Something went wrong"
1092
+ },
1093
+ withGuide: true,
1094
+ accessible: void 0,
1095
+ date: {
1096
+ monthNames: [...t],
1097
+ messages: {
1098
+ required: "Please enter a valid date",
1099
+ invalidMonth: "There are only 12 months in a year",
1100
+ invalidDay: (n3, e) => `There are only ${n3} days in ${e}`,
1101
+ afterMin: (n3) => `Date must be on or after ${n3.toISOString().slice(0, 10)}`,
1102
+ beforeMax: (n3) => `Date must be on or before ${n3.toISOString().slice(0, 10)}`
1103
+ }
1104
+ }
1105
+ };
1106
+ function isAccessible(n3) {
1107
+ if (n3 !== void 0) return n3;
1108
+ if (settings.accessible !== void 0) return settings.accessible;
1109
+ const e = process.env.ACCESSIBLE;
1110
+ return e !== void 0 && e !== "" && e !== "0" && e !== "false";
1111
+ }
1112
+ function isActionKey(n3, e) {
1113
+ if (typeof n3 == "string")
1114
+ return settings.aliases.get(n3) === e;
1115
+ for (const s of n3)
1116
+ if (s !== void 0 && isActionKey(s, e))
1117
+ return true;
1118
+ return false;
1119
+ }
1120
+ function diffLines(i2, s) {
1121
+ if (i2 === s) return;
1122
+ const e = i2.split(`
1123
+ `), t2 = s.split(`
1124
+ `), r2 = Math.max(e.length, t2.length), f = [];
1125
+ for (let n3 = 0; n3 < r2; n3++)
1126
+ e[n3] !== t2[n3] && f.push(n3);
1127
+ return {
1128
+ lines: f,
1129
+ numLinesBefore: e.length,
1130
+ numLinesAfter: t2.length,
1131
+ numLines: r2
1132
+ };
1133
+ }
1134
+ var R = globalThis.process.platform.startsWith("win");
1135
+ var CANCEL_SYMBOL = /* @__PURE__ */ Symbol("clack:cancel");
1136
+ function isCancel(e) {
1137
+ return e === CANCEL_SYMBOL;
1138
+ }
1139
+ function setRawMode(e, r2) {
1140
+ const o = e;
1141
+ o.isTTY && o.setRawMode(r2);
1142
+ }
1143
+ function block({
1144
+ input: e = stdin,
1145
+ output: r2 = stdout,
1146
+ overwrite: o = true,
1147
+ hideCursor: n3 = true
1148
+ } = {}) {
1149
+ const s = f$1.createInterface({
1150
+ input: e,
1151
+ output: r2,
1152
+ prompt: "",
1153
+ tabSize: 1
1154
+ });
1155
+ f$1.emitKeypressEvents(e, s), e instanceof ReadStream && e.isTTY && e.setRawMode(true);
1156
+ const t2 = (l, { name: i2, sequence: p }) => {
1157
+ const w = String(l);
1158
+ if (isActionKey([w, i2, p], "cancel")) {
1159
+ n3 && r2.write(cursor.show), process.exit(0);
1160
+ return;
1161
+ }
1162
+ if (!o) return;
1163
+ const c3 = i2 === "return" ? 0 : -1, a2 = i2 === "return" ? -1 : 0;
1164
+ f$1.moveCursor(r2, c3, a2, () => {
1165
+ f$1.clearLine(r2, 1, () => {
1166
+ e.once("keypress", t2);
1167
+ });
1168
+ });
1169
+ };
1170
+ return n3 && r2.write(cursor.hide), e.once("keypress", t2), () => {
1171
+ e.off("keypress", t2), n3 && r2.write(cursor.show), e instanceof ReadStream && e.isTTY && !R && e.setRawMode(false), s.terminal = false, s.close();
1172
+ };
1173
+ }
1174
+ var getColumns = (e) => "columns" in e && typeof e.columns == "number" ? e.columns : 80;
1175
+ var getRows = (e) => "rows" in e && typeof e.rows == "number" ? e.rows : 20;
1176
+ function wrapTextWithPrefix(e, r2, o, n3 = o, s = o, t2) {
1177
+ const l = getColumns(e ?? stdout), i2 = dist_default2(o);
1178
+ return wrapAnsi(r2, l - i2, {
1179
+ hard: true,
1180
+ trim: false
1181
+ }).split(`
1182
+ `).map((c3, a2, g) => {
1183
+ const m = t2 ? t2(c3, a2) : c3;
1184
+ return a2 === 0 ? `${n3}${m}` : a2 === g.length - 1 ? `${s}${m}` : `${o}${m}`;
1185
+ }).join(`
1186
+ `);
1187
+ }
1188
+ function runValidation(e, a2) {
1189
+ if ("~standard" in e) {
1190
+ const n3 = e["~standard"].validate(a2);
1191
+ return n3 instanceof Promise ? n3.then((r2) => r2.issues?.at(0)?.message) : n3.issues?.at(0)?.message;
1192
+ }
1193
+ return e(a2);
1194
+ }
1195
+ var C$1 = class C {
1196
+ input;
1197
+ output;
1198
+ _abortSignal;
1199
+ rl;
1200
+ opts;
1201
+ _render;
1202
+ _track = false;
1203
+ _prevFrame = "";
1204
+ _subscribers = /* @__PURE__ */ new Map();
1205
+ _cursor = 0;
1206
+ state = "initial";
1207
+ error = "";
1208
+ value;
1209
+ userInput = "";
1210
+ /**
1211
+ * Whether accessible (static, screen-reader friendly) output is enabled for
1212
+ * this prompt, resolved from the `accessible` option, the global setting,
1213
+ * and the `ACCESSIBLE` env var.
1214
+ */
1215
+ get accessible() {
1216
+ return isAccessible(this.opts.accessible);
1217
+ }
1218
+ constructor(t2, e = true) {
1219
+ const { input: i2 = stdin, output: s = stdout, render: r2, signal: n3, ...o } = t2;
1220
+ this.opts = o, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = r2.bind(this), this._track = e, this._abortSignal = n3, this.input = i2, this.output = s;
1221
+ }
1222
+ /**
1223
+ * Unsubscribe all listeners
1224
+ */
1225
+ unsubscribe() {
1226
+ this._subscribers.clear();
1227
+ }
1228
+ /**
1229
+ * Set a subscriber with opts
1230
+ * @param event - The event name
1231
+ */
1232
+ setSubscriber(t2, e) {
1233
+ const i2 = this._subscribers.get(t2) ?? [];
1234
+ i2.push(e), this._subscribers.set(t2, i2);
1235
+ }
1236
+ /**
1237
+ * Subscribe to an event
1238
+ * @param event - The event name
1239
+ * @param cb - The callback
1240
+ */
1241
+ on(t2, e) {
1242
+ this.setSubscriber(t2, { cb: e });
1243
+ }
1244
+ /**
1245
+ * Subscribe to an event once
1246
+ * @param event - The event name
1247
+ * @param cb - The callback
1248
+ */
1249
+ once(t2, e) {
1250
+ this.setSubscriber(t2, { cb: e, once: true });
1251
+ }
1252
+ /**
1253
+ * Emit an event with data
1254
+ * @param event - The event name
1255
+ * @param data - The data to pass to the callback
1256
+ */
1257
+ emit(t2, ...e) {
1258
+ const i2 = this._subscribers.get(t2) ?? [], s = [];
1259
+ for (const r2 of i2)
1260
+ r2.cb(...e), r2.once && s.push(() => i2.splice(i2.indexOf(r2), 1));
1261
+ for (const r2 of s)
1262
+ r2();
1263
+ }
1264
+ prompt() {
1265
+ return new Promise((t2) => {
1266
+ if (this._abortSignal) {
1267
+ if (this._abortSignal.aborted)
1268
+ return this.state = "cancel", this.close(), t2(CANCEL_SYMBOL);
1269
+ this._abortSignal.addEventListener(
1270
+ "abort",
1271
+ () => {
1272
+ this.state = "cancel", this.close();
1273
+ },
1274
+ { once: true }
1275
+ );
1276
+ }
1277
+ this.rl = f__default.createInterface({
1278
+ input: this.input,
1279
+ tabSize: 2,
1280
+ prompt: "",
1281
+ escapeCodeTimeout: 50,
1282
+ terminal: true
1283
+ }), this.rl.prompt(), this.opts.initialUserInput !== void 0 && this._setUserInput(this.opts.initialUserInput, true), this.input.on("keypress", this.onKeypress), setRawMode(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
1284
+ this.output.write(cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t2(this.value);
1285
+ }), this.once("cancel", () => {
1286
+ this.output.write(cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t2(CANCEL_SYMBOL);
1287
+ });
1288
+ });
1289
+ }
1290
+ _isActionKey(t2, e) {
1291
+ return t2 === " ";
1292
+ }
1293
+ _shouldSubmit(t2, e) {
1294
+ return true;
1295
+ }
1296
+ _setValue(t2) {
1297
+ this.value = t2, this.emit("value", this.value);
1298
+ }
1299
+ _setUserInput(t2, e) {
1300
+ this.userInput = t2 ?? "", this.emit("userInput", this.userInput), e && this._track && this.rl && (this.rl.write(this.userInput), this._cursor = this.rl.cursor);
1301
+ }
1302
+ _clearUserInput() {
1303
+ this.rl?.write(null, { ctrl: true, name: "u" }), this._setUserInput("");
1304
+ }
1305
+ async onKeypress(t2, e) {
1306
+ if (this.state !== "validating") {
1307
+ if (this._track && e.name !== "return" && (e.name && this._isActionKey(t2, e) && this.rl?.write(null, { ctrl: true, name: "h" }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === "error" && (this.state = "active"), e?.name && (!this._track && settings.aliases.has(e.name) && this.emit("cursor", settings.aliases.get(e.name)), settings.actions.has(e.name) && this.emit("cursor", e.name)), t2 && (t2.toLowerCase() === "y" || t2.toLowerCase() === "n") && this.emit("confirm", t2.toLowerCase() === "y"), this.emit("key", t2, e), e?.name === "return" && this._shouldSubmit(t2, e)) {
1308
+ if (this.opts.validate) {
1309
+ const i2 = runValidation(this.opts.validate, this.value);
1310
+ let s;
1311
+ i2 instanceof Promise ? (this.state = "validating", this.render(), s = await i2) : s = i2, s && (this.error = s instanceof Error ? s.message : s, this.state = "error", this.rl?.write(this.userInput));
1312
+ }
1313
+ this.state !== "error" && (this.state = "submit");
1314
+ }
1315
+ isActionKey([t2, e?.name, e?.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
1316
+ }
1317
+ }
1318
+ close() {
1319
+ this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
1320
+ `), setRawMode(this.input, false), this.rl?.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();
1321
+ }
1322
+ restoreCursor() {
1323
+ const t2 = wrapAnsi(this._prevFrame, getColumns(this.output), { hard: true, trim: false }).split(`
1324
+ `).length - 1;
1325
+ this.output.write(cursor.move(-999, t2 * -1));
1326
+ }
1327
+ render() {
1328
+ const t2 = wrapAnsi(this._render(this) ?? "", getColumns(this.output), {
1329
+ hard: true,
1330
+ trim: false
1331
+ });
1332
+ if (t2 !== this._prevFrame) {
1333
+ if (this.state === "initial")
1334
+ this.output.write(cursor.hide);
1335
+ else {
1336
+ const e = diffLines(this._prevFrame, t2), i2 = getRows(this.output);
1337
+ if (this.restoreCursor(), e) {
1338
+ const s = Math.max(0, e.numLinesAfter - i2), r2 = Math.max(0, e.numLinesBefore - i2);
1339
+ let n3 = e.lines.find((o) => o >= s);
1340
+ if (n3 === void 0) {
1341
+ this._prevFrame = t2;
1342
+ return;
1343
+ }
1344
+ if (e.lines.length === 1) {
1345
+ this.output.write(cursor.move(0, n3 - r2)), this.output.write(erase.lines(1));
1346
+ const o = t2.split(`
1347
+ `);
1348
+ this.output.write(o[n3]), this._prevFrame = t2, this.output.write(cursor.move(0, o.length - n3 - 1));
1349
+ return;
1350
+ } else if (e.lines.length > 1) {
1351
+ if (s < r2)
1352
+ n3 = s;
1353
+ else {
1354
+ const h2 = n3 - r2;
1355
+ h2 > 0 && this.output.write(cursor.move(0, h2));
1356
+ }
1357
+ this.output.write(erase.down());
1358
+ const m = t2.split(`
1359
+ `).slice(n3);
1360
+ this.output.write(m.join(`
1361
+ `)), this._prevFrame = t2;
1362
+ return;
1363
+ }
1364
+ }
1365
+ this.output.write(erase.down());
1366
+ }
1367
+ this.output.write(t2), this.state === "initial" && (this.state = "active"), this._prevFrame = t2;
1368
+ }
1369
+ }
1370
+ };
1371
+ var r = class extends C$1 {
1372
+ get cursor() {
1373
+ return this.value ? 0 : 1;
1374
+ }
1375
+ get _value() {
1376
+ return this.cursor === 0;
1377
+ }
1378
+ constructor(t2) {
1379
+ super(t2, false), this.value = !!t2.initialValue, this.on("userInput", () => {
1380
+ this.value = this._value;
1381
+ }), this.on("confirm", (i2) => {
1382
+ this.output.write(cursor.move(0, -1)), this.value = i2, this.state = "submit", this.close();
1383
+ }), this.on("cursor", () => {
1384
+ this.value = !this.value;
1385
+ });
1386
+ }
1387
+ };
1388
+ var n$1 = class n extends C$1 {
1389
+ options;
1390
+ cursor = 0;
1391
+ get _selectedValue() {
1392
+ return this.options[this.cursor];
1393
+ }
1394
+ changeValue() {
1395
+ const e = this._selectedValue;
1396
+ this.value = e === void 0 ? void 0 : e.value;
1397
+ }
1398
+ constructor(e) {
1399
+ super(e, false), this.options = e.options;
1400
+ const o = this.options.findIndex(({ value: s }) => s === e.initialValue), t2 = o === -1 ? 0 : o;
1401
+ this.cursor = this.options[t2]?.disabled ? findCursor(t2, 1, this.options) : t2, this.changeValue(), this.on("cursor", (s) => {
1402
+ switch (s) {
1403
+ case "left":
1404
+ case "up":
1405
+ this.cursor = findCursor(this.cursor, -1, this.options);
1406
+ break;
1407
+ case "down":
1408
+ case "right":
1409
+ this.cursor = findCursor(this.cursor, 1, this.options);
1410
+ break;
1411
+ }
1412
+ this.changeValue();
1413
+ });
1414
+ }
1415
+ };
1416
+ var n2 = class extends C$1 {
1417
+ get userInputWithCursor() {
1418
+ if (this.state === "submit")
1419
+ return this.userInput;
1420
+ const t2 = this.userInput;
1421
+ if (this.cursor >= t2.length)
1422
+ return `${this.userInput}\u2588`;
1423
+ const r2 = t2.slice(0, this.cursor), s = t2.slice(this.cursor, this.cursor + 1), e = t2.slice(this.cursor + 1);
1424
+ return `${r2}${styleText("inverse", s)}${e}`;
1425
+ }
1426
+ get cursor() {
1427
+ return this._cursor;
1428
+ }
1429
+ constructor(t2) {
1430
+ super({
1431
+ ...t2,
1432
+ initialUserInput: t2.initialUserInput ?? t2.initialValue
1433
+ }), this.on("userInput", (r2) => {
1434
+ this._setValue(r2);
1435
+ }), this.on("finalize", () => {
1436
+ this.value || (this.value = t2.defaultValue), this.value === void 0 && (this.value = "");
1437
+ });
1438
+ }
1439
+ };
1440
+
1441
+ // ../../node_modules/.pnpm/@clack+prompts@1.9.0/node_modules/@clack/prompts/dist/index.mjs
1442
+ import { styleText as styleText2, stripVTControlCharacters } from "node:util";
1443
+ import process$1 from "node:process";
1444
+ function isUnicodeSupported() {
1445
+ if (process$1.platform !== "win32") {
1446
+ return process$1.env.TERM !== "linux";
1447
+ }
1448
+ return Boolean(process$1.env.CI) || Boolean(process$1.env.WT_SESSION) || Boolean(process$1.env.TERMINUS_SUBLIME) || process$1.env.ConEmuTask === "{cmd::Cmder}" || process$1.env.TERM_PROGRAM === "Terminus-Sublime" || process$1.env.TERM_PROGRAM === "vscode" || process$1.env.TERM === "xterm-256color" || process$1.env.TERM === "alacritty" || process$1.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
1449
+ }
1450
+ var unicode = isUnicodeSupported();
1451
+ var isCI = () => process.env.CI === "true";
1452
+ var unicodeOr = (e, o) => unicode ? e : o;
1453
+ var S_STEP_ACTIVE = unicodeOr("\u25C6", "*");
1454
+ var S_STEP_CANCEL = unicodeOr("\u25A0", "x");
1455
+ var S_STEP_ERROR = unicodeOr("\u25B2", "x");
1456
+ var S_STEP_SUBMIT = unicodeOr("\u25C7", "o");
1457
+ var S_BAR_START = unicodeOr("\u250C", "T");
1458
+ var S_BAR = unicodeOr("\u2502", "|");
1459
+ var S_BAR_END = unicodeOr("\u2514", "\u2014");
1460
+ var S_BAR_START_RIGHT = unicodeOr("\u2510", "T");
1461
+ var S_BAR_END_RIGHT = unicodeOr("\u2518", "\u2014");
1462
+ var S_RADIO_ACTIVE = unicodeOr("\u25CF", ">");
1463
+ var S_RADIO_INACTIVE = unicodeOr("\u25CB", " ");
1464
+ var S_CHECKBOX_ACTIVE = unicodeOr("\u25FB", "[\u2022]");
1465
+ var S_CHECKBOX_SELECTED = unicodeOr("\u25FC", "[+]");
1466
+ var S_CHECKBOX_INACTIVE = unicodeOr("\u25FB", "[ ]");
1467
+ var S_PASSWORD_MASK = unicodeOr("\u25AA", "\u2022");
1468
+ var S_BAR_H = unicodeOr("\u2500", "-");
1469
+ var S_CORNER_TOP_RIGHT = unicodeOr("\u256E", "+");
1470
+ var S_CONNECT_LEFT = unicodeOr("\u251C", "+");
1471
+ var S_CORNER_BOTTOM_RIGHT = unicodeOr("\u256F", "+");
1472
+ var S_CORNER_BOTTOM_LEFT = unicodeOr("\u2570", "+");
1473
+ var S_CORNER_TOP_LEFT = unicodeOr("\u256D", "+");
1474
+ var S_INFO = unicodeOr("\u25CF", "\u2022");
1475
+ var S_SUCCESS = unicodeOr("\u25C6", "*");
1476
+ var S_WARN = unicodeOr("\u25B2", "!");
1477
+ var S_ERROR = unicodeOr("\u25A0", "x");
1478
+ var symbol = (e) => {
1479
+ switch (e) {
1480
+ case "initial":
1481
+ case "active":
1482
+ return styleText2("cyan", S_STEP_ACTIVE);
1483
+ case "cancel":
1484
+ return styleText2("red", S_STEP_CANCEL);
1485
+ case "error":
1486
+ return styleText2("yellow", S_STEP_ERROR);
1487
+ case "submit":
1488
+ return styleText2("green", S_STEP_SUBMIT);
1489
+ case "validating":
1490
+ return styleText2("dim", S_STEP_ACTIVE);
1491
+ }
1492
+ };
1493
+ var symbolBar = (e) => {
1494
+ switch (e) {
1495
+ case "initial":
1496
+ case "active":
1497
+ return styleText2("cyan", S_BAR);
1498
+ case "cancel":
1499
+ return styleText2("red", S_BAR);
1500
+ case "error":
1501
+ return styleText2("yellow", S_BAR);
1502
+ case "submit":
1503
+ return styleText2("green", S_BAR);
1504
+ }
1505
+ };
1506
+ function formatInstructionFooter(e, o, r2) {
1507
+ const s = r2 ? `${styleText2("cyan", S_BAR)} ` : "", n3 = wrapTextWithPrefix(e, o.join(" \u2022 "), s).split(`
1508
+ `);
1509
+ return r2 && n3.push(styleText2("cyan", S_BAR_END)), n3;
1510
+ }
1511
+ var E$1 = (l, e, w, p, b, C3 = false) => {
1512
+ let r2 = e, O = 0;
1513
+ if (C3)
1514
+ for (let i2 = p - 1; i2 >= w; i2--) {
1515
+ const m = l[i2];
1516
+ if (m && (r2 -= m.length), O++, r2 <= b) break;
1517
+ }
1518
+ else
1519
+ for (let i2 = w; i2 < p; i2++) {
1520
+ const m = l[i2];
1521
+ if (m && (r2 -= m.length), O++, r2 <= b) break;
1522
+ }
1523
+ return { lineCount: r2, removals: O };
1524
+ };
1525
+ var limitOptions = ({
1526
+ cursor: l,
1527
+ options: e,
1528
+ style: w,
1529
+ output: p = process.stdout,
1530
+ maxItems: b = Number.POSITIVE_INFINITY,
1531
+ columnPadding: C3 = 0,
1532
+ rowPadding: r2 = 4
1533
+ }) => {
1534
+ const i2 = getColumns(p) - C3, m = getRows(p), M = styleText2("dim", "..."), v = Math.max(m - r2, 0), a2 = Math.max(Math.min(b, v), 5);
1535
+ let f = 0;
1536
+ l >= a2 - 3 && (f = Math.max(
1537
+ Math.min(l - a2 + 3, e.length - a2),
1538
+ 0
1539
+ ));
1540
+ let d = a2 < e.length && f > 0, c3 = a2 < e.length && f + a2 < e.length;
1541
+ const I = Math.min(
1542
+ f + a2,
1543
+ e.length
1544
+ ), s = [];
1545
+ let g = 0;
1546
+ d && g++, c3 && g++;
1547
+ const T = f + (d ? 1 : 0), W2 = I - (c3 ? 1 : 0);
1548
+ for (let t2 = T; t2 < W2; t2++) {
1549
+ const n3 = e[t2], o = n3 !== void 0 ? w(n3, t2 === l) : "", h2 = wrapAnsi(o, i2, {
1550
+ hard: true,
1551
+ trim: false
1552
+ }).split(`
1553
+ `);
1554
+ s.push(h2), g += h2.length;
1555
+ }
1556
+ if (g > v) {
1557
+ let t2 = 0, n3 = 0, o = g;
1558
+ const h2 = l - T;
1559
+ let u3 = v;
1560
+ const L = () => E$1(s, o, 0, h2, u3), y = () => E$1(
1561
+ s,
1562
+ o,
1563
+ h2 + 1,
1564
+ s.length,
1565
+ u3,
1566
+ true
1567
+ );
1568
+ d ? ({ lineCount: o, removals: t2 } = L(), o > u3 && (c3 || (u3 -= 1), { lineCount: o, removals: n3 } = y())) : (c3 || (u3 -= 1), { lineCount: o, removals: n3 } = y(), o > u3 && (u3 -= 1, { lineCount: o, removals: t2 } = L())), t2 > 0 && (d = true, s.splice(0, t2)), n3 > 0 && (c3 = true, s.splice(s.length - n3, n3));
1569
+ }
1570
+ const x = [];
1571
+ d && x.push(M);
1572
+ for (const t2 of s)
1573
+ for (const n3 of t2)
1574
+ x.push(n3);
1575
+ return c3 && x.push(M), x;
1576
+ };
1577
+ var confirm = (e) => {
1578
+ const a2 = e.active ?? "Yes", o = e.inactive ?? "No";
1579
+ return new r({
1580
+ active: a2,
1581
+ inactive: o,
1582
+ signal: e.signal,
1583
+ input: e.input,
1584
+ output: e.output,
1585
+ initialValue: e.initialValue ?? true,
1586
+ render() {
1587
+ const i2 = e.withGuide ?? settings.withGuide, u3 = `${symbol(this.state)} `, l = i2 ? `${styleText2("gray", S_BAR)} ` : "", f = wrapTextWithPrefix(
1588
+ e.output,
1589
+ e.message,
1590
+ l,
1591
+ u3
1592
+ ), s = `${i2 ? `${styleText2("gray", S_BAR)}
1593
+ ` : ""}${f}
1594
+ `, c3 = this.value ? a2 : o;
1595
+ switch (this.state) {
1596
+ case "submit": {
1597
+ const r2 = i2 ? `${styleText2("gray", S_BAR)} ` : "";
1598
+ return `${s}${r2}${styleText2("dim", c3)}`;
1599
+ }
1600
+ case "cancel": {
1601
+ const r2 = i2 ? `${styleText2("gray", S_BAR)} ` : "";
1602
+ return `${s}${r2}${styleText2(["strikethrough", "dim"], c3)}${i2 ? `
1603
+ ${styleText2("gray", S_BAR)}` : ""}`;
1604
+ }
1605
+ default: {
1606
+ const r2 = i2 ? `${styleText2("cyan", S_BAR)} ` : "", g = i2 ? styleText2("cyan", S_BAR_END) : "";
1607
+ return `${s}${r2}${this.value ? `${styleText2("green", S_RADIO_ACTIVE)} ${a2}` : `${styleText2("dim", S_RADIO_INACTIVE)} ${styleText2("dim", a2)}`}${e.vertical ? i2 ? `
1608
+ ${styleText2("cyan", S_BAR)} ` : `
1609
+ ` : ` ${styleText2("dim", "/")} `}${this.value ? `${styleText2("dim", S_RADIO_INACTIVE)} ${styleText2("dim", o)}` : `${styleText2("green", S_RADIO_ACTIVE)} ${o}`}
1610
+ ${g}
1611
+ `;
1612
+ }
1613
+ }
1614
+ }
1615
+ }).prompt();
1616
+ };
1617
+ var MULTISELECT_INSTRUCTIONS = [
1618
+ `${styleText2("dim", "\u2191/\u2193")} to navigate`,
1619
+ `${styleText2("dim", "Space:")} select`,
1620
+ `${styleText2("dim", "Enter:")} confirm`
1621
+ ];
1622
+ var log = {
1623
+ message: (s = [], {
1624
+ symbol: e = styleText2("gray", S_BAR),
1625
+ secondarySymbol: r2 = styleText2("gray", S_BAR),
1626
+ output: m = process.stdout,
1627
+ spacing: l = 1,
1628
+ withGuide: c3
1629
+ } = {}) => {
1630
+ const t2 = [], o = c3 ?? settings.withGuide, f = o ? r2 : "", O = o ? `${e} ` : "", u3 = o ? `${r2} ` : "";
1631
+ for (let i2 = 0; i2 < l; i2++)
1632
+ t2.push(f);
1633
+ const g = Array.isArray(s) ? s : s.split(`
1634
+ `);
1635
+ if (g.length > 0) {
1636
+ const [i2, ...y] = g;
1637
+ i2.length > 0 ? t2.push(`${O}${i2}`) : t2.push(o ? e : "");
1638
+ for (const p of y)
1639
+ p.length > 0 ? t2.push(`${u3}${p}`) : t2.push(o ? r2 : "");
1640
+ }
1641
+ m.write(`${t2.join(`
1642
+ `)}
1643
+ `);
1644
+ },
1645
+ info: (s, e) => {
1646
+ log.message(s, { ...e, symbol: styleText2("blue", S_INFO) });
1647
+ },
1648
+ success: (s, e) => {
1649
+ log.message(s, { ...e, symbol: styleText2("green", S_SUCCESS) });
1650
+ },
1651
+ step: (s, e) => {
1652
+ log.message(s, { ...e, symbol: styleText2("green", S_STEP_SUBMIT) });
1653
+ },
1654
+ warn: (s, e) => {
1655
+ log.message(s, { ...e, symbol: styleText2("yellow", S_WARN) });
1656
+ },
1657
+ /** alias for `log.warn()`. */
1658
+ warning: (s, e) => {
1659
+ log.warn(s, e);
1660
+ },
1661
+ error: (s, e) => {
1662
+ log.message(s, { ...e, symbol: styleText2("red", S_ERROR) });
1663
+ }
1664
+ };
1665
+ var cancel = (o = "", t2) => {
1666
+ const i2 = t2?.output ?? process.stdout, e = t2?.withGuide ?? settings.withGuide ? `${styleText2("gray", S_BAR_END)} ` : "";
1667
+ i2.write(`${e}${styleText2("red", o)}
1668
+
1669
+ `);
1670
+ };
1671
+ var intro = (o = "", t2) => {
1672
+ const i2 = t2?.output ?? process.stdout, e = t2?.withGuide ?? settings.withGuide ? `${styleText2("gray", S_BAR_START)} ` : "";
1673
+ i2.write(`${e}${o}
1674
+ `);
1675
+ };
1676
+ var outro = (o = "", t2) => {
1677
+ const i2 = t2?.output ?? process.stdout, e = t2?.withGuide ?? settings.withGuide ? `${styleText2("gray", S_BAR)}
1678
+ ${styleText2("gray", S_BAR_END)} ` : "";
1679
+ i2.write(`${e}${o}
1680
+
1681
+ `);
1682
+ };
1683
+ var W = (o) => o;
1684
+ var C2 = (o, e, s) => {
1685
+ const a2 = {
1686
+ hard: true,
1687
+ trim: false
1688
+ }, i2 = wrapAnsi(o, e, a2).split(`
1689
+ `), c3 = i2.reduce((n3, t2) => Math.max(dist_default2(t2), n3), 0), u3 = i2.map(s).reduce((n3, t2) => Math.max(dist_default2(t2), n3), 0), g = e - (u3 - c3);
1690
+ return wrapAnsi(o, g, a2);
1691
+ };
1692
+ var note = (o = "", e = "", s) => {
1693
+ const a2 = s?.output ?? process$1.stdout, i2 = s?.withGuide ?? settings.withGuide, c3 = s?.format ?? W, g = ["", ...C2(o, getColumns(a2) - 6, c3).split(`
1694
+ `).map(c3), ""], n3 = dist_default2(e), t2 = Math.max(
1695
+ g.reduce((m, F) => {
1696
+ const O = dist_default2(F);
1697
+ return O > m ? O : m;
1698
+ }, 0),
1699
+ n3
1700
+ ) + 2, h2 = g.map(
1701
+ (m) => `${styleText2("gray", S_BAR)} ${m}${" ".repeat(t2 - dist_default2(m))}${styleText2("gray", S_BAR)}`
1702
+ ).join(`
1703
+ `), T = i2 ? `${styleText2("gray", S_BAR)}
1704
+ ` : "", l$1 = i2 ? S_CONNECT_LEFT : S_CORNER_BOTTOM_LEFT;
1705
+ a2.write(
1706
+ `${T}${styleText2("green", S_STEP_SUBMIT)} ${styleText2("reset", e)} ${styleText2(
1707
+ "gray",
1708
+ S_BAR_H.repeat(Math.max(t2 - n3 - 1, 1)) + S_CORNER_TOP_RIGHT
1709
+ )}
1710
+ ${h2}
1711
+ ${styleText2("gray", l$1 + S_BAR_H.repeat(t2 + 2) + S_CORNER_BOTTOM_RIGHT)}
1712
+ `
1713
+ );
1714
+ };
1715
+ var Y = 3e4;
1716
+ var Z = (c3) => styleText2("magenta", c3);
1717
+ var spinner = ({
1718
+ indicator: c3 = "dots",
1719
+ onCancel: b,
1720
+ output: n3 = process.stdout,
1721
+ cancelMessage: _,
1722
+ errorMessage: C3,
1723
+ frames: M = unicode ? ["\u25D2", "\u25D0", "\u25D3", "\u25D1"] : ["\u2022", "o", "O", "0"],
1724
+ delay: O = unicode ? 80 : 120,
1725
+ signal: g,
1726
+ ...E
1727
+ } = {}) => {
1728
+ const u3 = isCI(), h2 = isAccessible(E.accessible);
1729
+ let x, I, p = false, l = false, r2 = "", v, w = performance.now();
1730
+ const y = getColumns(n3), F = E?.styleFrame ?? Z, S = (e) => {
1731
+ const s = e > 1 ? C3 ?? settings.messages.error : _ ?? settings.messages.cancel;
1732
+ l = e === 1, p && (m(s, e), l && typeof b == "function" && b());
1733
+ }, $ = () => S(2), a2 = () => S(1), H = () => {
1734
+ process.on("uncaughtExceptionMonitor", $), process.on("unhandledRejection", $), process.on("SIGINT", a2), process.on("SIGTERM", a2), process.on("exit", S), g && g.addEventListener("abort", a2);
1735
+ }, B = () => {
1736
+ process.removeListener("uncaughtExceptionMonitor", $), process.removeListener("unhandledRejection", $), process.removeListener("SIGINT", a2), process.removeListener("SIGTERM", a2), process.removeListener("exit", S), g && g.removeEventListener("abort", a2);
1737
+ }, R2 = () => {
1738
+ if (v === void 0) return;
1739
+ u3 && n3.write(`
1740
+ `);
1741
+ const s = wrapAnsi(v, y, {
1742
+ hard: true,
1743
+ trim: false
1744
+ }).split(`
1745
+ `);
1746
+ s.length > 1 && n3.write(cursor.up(s.length - 1)), n3.write(cursor.to(0)), n3.write(erase.down());
1747
+ }, L = (e) => e.replace(/\.+$/, ""), T = (e) => {
1748
+ const s = (performance.now() - e) / 1e3, i2 = Math.floor(s / 60), t2 = Math.floor(s % 60);
1749
+ return i2 > 0 ? `[${i2}m ${t2}s]` : `[${t2}s]`;
1750
+ }, N = E.withGuide ?? settings.withGuide, P = (e = "") => {
1751
+ if (p = true, l = false, r2 = L(e), w = performance.now(), H(), h2) {
1752
+ r2 !== "" && n3.write(`${r2}
1753
+ `), I = setInterval(() => {
1754
+ n3.write(r2 === "" ? `still working
1755
+ ` : `still working: ${r2}
1756
+ `);
1757
+ }, Y);
1758
+ return;
1759
+ }
1760
+ x = block({ output: n3 }), N && n3.write(`${styleText2("gray", S_BAR)}
1761
+ `);
1762
+ let s = 0, i2 = 0;
1763
+ I = setInterval(() => {
1764
+ if (u3 && r2 === v)
1765
+ return;
1766
+ R2(), v = r2;
1767
+ const t2 = F(M[s]);
1768
+ let o;
1769
+ if (u3)
1770
+ o = `${t2} ${r2}...`;
1771
+ else if (c3 === "timer")
1772
+ o = `${t2} ${r2} ${T(w)}`;
1773
+ else {
1774
+ const j = ".".repeat(Math.floor(i2)).slice(0, 3);
1775
+ o = `${t2} ${r2}${j}`;
1776
+ }
1777
+ const D = wrapAnsi(o, y, {
1778
+ hard: true,
1779
+ trim: false
1780
+ });
1781
+ n3.write(D), s = s + 1 < M.length ? s + 1 : 0, i2 = i2 < 4 ? i2 + 0.125 : 0;
1782
+ }, O);
1783
+ }, m = (e = "", s = 0, i2 = false) => {
1784
+ if (p) {
1785
+ if (p = false, l = s === 1, clearInterval(I), h2 || R2(), r2 = e ?? r2, !i2)
1786
+ if (h2) {
1787
+ const t2 = s === 1 ? _ ?? settings.messages.cancel : s === 2 ? C3 ?? settings.messages.error : "Done", o = r2 || t2;
1788
+ c3 === "timer" ? n3.write(`${o} ${T(w)}
1789
+ `) : n3.write(`${o}
1790
+ `);
1791
+ } else {
1792
+ const t2 = s === 0 ? styleText2("green", S_STEP_SUBMIT) : s === 1 ? styleText2("red", S_STEP_CANCEL) : styleText2("red", S_STEP_ERROR);
1793
+ c3 === "timer" ? n3.write(`${t2} ${r2} ${T(w)}
1794
+ `) : n3.write(`${t2} ${r2}
1795
+ `);
1796
+ }
1797
+ B(), x?.();
1798
+ }
1799
+ };
1800
+ return {
1801
+ start: P,
1802
+ stop: (e = "") => m(e, 0),
1803
+ message: (e = "") => {
1804
+ r2 = L(e ?? r2);
1805
+ },
1806
+ cancel: (e = "") => m(e, 1),
1807
+ error: (e = "") => m(e, 2),
1808
+ clear: () => m("", 0, true),
1809
+ get isCancelled() {
1810
+ return l;
1811
+ }
1812
+ };
1813
+ };
1814
+ var u2 = {
1815
+ light: unicodeOr("\u2500", "-"),
1816
+ heavy: unicodeOr("\u2501", "="),
1817
+ block: unicodeOr("\u2588", "#")
1818
+ };
1819
+ var SELECT_INSTRUCTIONS = [
1820
+ `${styleText2("dim", "\u2191/\u2193")} to navigate`,
1821
+ `${styleText2("dim", "Enter:")} confirm`
1822
+ ];
1823
+ var c2 = (t2, o) => t2.includes(`
1824
+ `) ? t2.split(`
1825
+ `).map((d) => o(d)).join(`
1826
+ `) : o(t2);
1827
+ var select = (t2) => {
1828
+ const o = (n3, m) => {
1829
+ if (n3 === void 0)
1830
+ return "";
1831
+ const s = n3.label ?? String(n3.value);
1832
+ switch (m) {
1833
+ case "disabled":
1834
+ return `${styleText2("gray", S_RADIO_INACTIVE)} ${c2(s, (i2) => styleText2("gray", i2))}${n3.hint ? ` ${styleText2("dim", `(${n3.hint ?? "disabled"})`)}` : ""}`;
1835
+ case "selected":
1836
+ return `${c2(s, (i2) => styleText2("dim", i2))}`;
1837
+ case "active":
1838
+ return `${styleText2("green", S_RADIO_ACTIVE)} ${s}${n3.hint ? ` ${styleText2("dim", `(${n3.hint})`)}` : ""}`;
1839
+ case "cancelled":
1840
+ return `${c2(s, (i2) => styleText2(["strikethrough", "dim"], i2))}`;
1841
+ default:
1842
+ return `${styleText2("dim", S_RADIO_INACTIVE)} ${c2(s, (i2) => styleText2("dim", i2))}`;
1843
+ }
1844
+ }, d = t2.showInstructions ?? true;
1845
+ return new n$1({
1846
+ options: t2.options,
1847
+ signal: t2.signal,
1848
+ input: t2.input,
1849
+ output: t2.output,
1850
+ initialValue: t2.initialValue,
1851
+ render() {
1852
+ const n3 = t2.withGuide ?? settings.withGuide, m = `${symbol(this.state)} `, s = `${symbolBar(this.state)} `, i2 = wrapTextWithPrefix(
1853
+ t2.output,
1854
+ t2.message,
1855
+ s,
1856
+ m
1857
+ ), u3 = `${n3 ? `${styleText2("gray", S_BAR)}
1858
+ ` : ""}${i2}
1859
+ `;
1860
+ switch (this.state) {
1861
+ case "submit": {
1862
+ const r2 = n3 ? `${styleText2("gray", S_BAR)} ` : "", a2 = wrapTextWithPrefix(
1863
+ t2.output,
1864
+ o(this.options[this.cursor], "selected"),
1865
+ r2
1866
+ );
1867
+ return `${u3}${a2}`;
1868
+ }
1869
+ case "cancel": {
1870
+ const r2 = n3 ? `${styleText2("gray", S_BAR)} ` : "", a2 = wrapTextWithPrefix(
1871
+ t2.output,
1872
+ o(this.options[this.cursor], "cancelled"),
1873
+ r2
1874
+ );
1875
+ return `${u3}${a2}${n3 ? `
1876
+ ${styleText2("gray", S_BAR)}` : ""}`;
1877
+ }
1878
+ default: {
1879
+ const r2 = n3 ? `${styleText2("cyan", S_BAR)} ` : "", a2 = u3.split(`
1880
+ `).length, p = d ? formatInstructionFooter(t2.output, SELECT_INSTRUCTIONS, n3) : n3 ? [styleText2("cyan", S_BAR_END)] : [], f = p.join(`
1881
+ `), b = p.length + 1;
1882
+ return `${u3}${r2}${limitOptions({
1883
+ output: t2.output,
1884
+ cursor: this.cursor,
1885
+ options: this.options,
1886
+ maxItems: t2.maxItems,
1887
+ columnPadding: r2.length,
1888
+ rowPadding: a2 + b,
1889
+ style: (g, x) => o(g, g.disabled ? "disabled" : x ? "active" : "inactive")
1890
+ }).join(`
1891
+ ${r2}`)}
1892
+ ${f}
1893
+ `;
1894
+ }
1895
+ }
1896
+ }
1897
+ }).prompt();
1898
+ };
1899
+ var i = `${styleText2("gray", S_BAR)} `;
1900
+ var text = (t2) => new n2({
1901
+ validate: t2.validate,
1902
+ placeholder: t2.placeholder,
1903
+ defaultValue: t2.defaultValue,
1904
+ initialValue: t2.initialValue,
1905
+ output: t2.output,
1906
+ signal: t2.signal,
1907
+ input: t2.input,
1908
+ render() {
1909
+ const r2 = t2?.withGuide ?? settings.withGuide, l = `${`${r2 ? `${styleText2("gray", S_BAR)}
1910
+ ` : ""}${symbol(this.state)} `}${t2.message}
1911
+ `, d = t2.placeholder && t2.placeholder.length > 0 ? (
1912
+ // biome-ignore lint/style/noNonNullAssertion: guarded by placeholder.length > 0
1913
+ styleText2("inverse", t2.placeholder[0]) + styleText2("dim", t2.placeholder.slice(1))
1914
+ ) : styleText2(["inverse", "hidden"], "_"), o = this.userInput ? this.userInputWithCursor : d, s = this.value ?? "";
1915
+ switch (this.state) {
1916
+ case "validating": {
1917
+ const n3 = r2 ? `${styleText2("cyan", S_BAR)} ` : "", i2 = r2 ? styleText2("cyan", S_BAR_END) : "", c3 = styleText2("dim", o), $ = styleText2("dim", "Validating...");
1918
+ return `${l}${n3}${c3}
1919
+ ${i2} ${$}
1920
+ `;
1921
+ }
1922
+ case "error": {
1923
+ const n3 = this.error ? ` ${styleText2("yellow", this.error)}` : "", i2 = r2 ? `${styleText2("yellow", S_BAR)} ` : "", c3 = r2 ? styleText2("yellow", S_BAR_END) : "";
1924
+ return `${l.trim()}
1925
+ ${i2}${o}
1926
+ ${c3}${n3}
1927
+ `;
1928
+ }
1929
+ case "submit": {
1930
+ const n3 = s ? `${r2 ? " " : ""}${styleText2("dim", s)}` : "", i2 = r2 ? styleText2("gray", S_BAR) : "";
1931
+ return `${l}${i2}${n3}`;
1932
+ }
1933
+ case "cancel": {
1934
+ const n3 = s ? ` ${styleText2(["strikethrough", "dim"], s)}` : "", i2 = r2 ? styleText2("gray", S_BAR) : "";
1935
+ return `${l}${i2}${n3}${s.trim() ? `
1936
+ ${i2}` : ""}`;
1937
+ }
1938
+ default: {
1939
+ const n3 = r2 ? `${styleText2("cyan", S_BAR)} ` : "", i2 = r2 ? styleText2("cyan", S_BAR_END) : "";
1940
+ return `${l}${n3}${o}
1941
+ ${i2}
1942
+ `;
1943
+ }
1944
+ }
1945
+ }
1946
+ }).prompt();
1947
+
1948
+ // src/cli/key-label/key-label.ts
1949
+ var keyLabel = (entry) => {
1950
+ const masked = maskKey(entry.key);
1951
+ return entry.name !== void 0 && entry.name !== "" ? `${entry.name} ${masked}` : `${entry.id} ${masked}`;
1952
+ };
1953
+
1954
+ // src/cli/management-env/management-env.ts
1955
+ var managementEnv = () => ({
1956
+ ...process.env["ROUTE33_CLIENT_ID"] === void 0 ? {} : { clientId: process.env["ROUTE33_CLIENT_ID"] },
1957
+ ...process.env["ROUTE33_AUTH_ISSUER"] === void 0 ? {} : { issuer: process.env["ROUTE33_AUTH_ISSUER"] },
1958
+ ...process.env["ROUTE33_API_BASE"] === void 0 ? {} : { apiBase: process.env["ROUTE33_API_BASE"] }
1959
+ });
1960
+
1961
+ // src/login/issuer-url/issuer-url.ts
1962
+ var DEFAULT_ISSUER_URL = "https://auth.route33.ai";
1963
+ var issuerUrl = (override) => {
1964
+ const trimmed = override?.trim();
1965
+ return trimmed !== void 0 && trimmed !== "" ? trimmed : DEFAULT_ISSUER_URL;
1966
+ };
1967
+
1968
+ // src/login/requested-scopes/requested-scopes.ts
1969
+ var REQUESTED_OAUTH_SCOPES = "openid offline_access orgs:read projects:read keys:read keys:write";
1970
+
1971
+ // ../auth-core/dist/index.js
1972
+ import { createHash } from "node:crypto";
1973
+ import { randomBytes } from "node:crypto";
1974
+ var AuthError = class extends Error {
1975
+ constructor(code, options) {
1976
+ super(
1977
+ "Route 33 authorization failed",
1978
+ options?.cause === void 0 ? void 0 : { cause: options.cause }
1979
+ );
1980
+ this.code = code;
1981
+ this.name = "AuthError";
1982
+ this.statusCode = options?.statusCode;
1983
+ }
1984
+ code;
1985
+ statusCode;
1986
+ };
1987
+ var buildAuthorizeUrl = (issuerUrl2, request) => {
1988
+ const url = new URL("/authorize", issuerUrl2);
1989
+ url.search = new URLSearchParams({
1990
+ client_id: request.clientId,
1991
+ code_challenge: request.codeChallenge,
1992
+ code_challenge_method: "S256",
1993
+ redirect_uri: request.redirectUri,
1994
+ response_type: "code",
1995
+ scope: request.scope,
1996
+ state: request.state
1997
+ }).toString();
1998
+ return url;
1999
+ };
2000
+ var parseTokenSet = (value) => {
2001
+ const isRecord = (candidate) => typeof candidate === "object" && candidate !== null;
2002
+ if (!isRecord(value)) {
2003
+ throw new AuthError("AUTH_TOKEN_RESPONSE_INVALID");
2004
+ }
2005
+ if (typeof value["access_token"] !== "string" || typeof value["expires_in"] !== "number" || value["token_type"] !== "Bearer") {
2006
+ throw new AuthError("AUTH_TOKEN_RESPONSE_INVALID");
2007
+ }
2008
+ return {
2009
+ access_token: value["access_token"],
2010
+ expires_in: value["expires_in"],
2011
+ token_type: "Bearer",
2012
+ ...typeof value["id_token"] === "string" ? { id_token: value["id_token"] } : {},
2013
+ ...typeof value["refresh_token"] === "string" ? { refresh_token: value["refresh_token"] } : {},
2014
+ ...typeof value["refresh_token_expires_in"] === "number" ? { refresh_token_expires_in: value["refresh_token_expires_in"] } : {},
2015
+ ...typeof value["scope"] === "string" ? { scope: value["scope"] } : {}
2016
+ };
2017
+ };
2018
+ var pkceChallenge = (verifier) => createHash("sha256").update(verifier).digest("base64url");
2019
+ var createPkceVerifierAndChallenge = () => {
2020
+ const codeVerifier = randomBytes(32).toString("base64url");
2021
+ return {
2022
+ codeChallenge: pkceChallenge(codeVerifier),
2023
+ codeVerifier,
2024
+ state: randomBytes(32).toString("base64url")
2025
+ };
2026
+ };
2027
+
2028
+ // ../auth-browser/dist/index.js
2029
+ import { timingSafeEqual } from "node:crypto";
2030
+ import { createServer } from "node:http";
2031
+ import { spawn } from "node:child_process";
2032
+ var exchangeCodeAndParse = async (options) => {
2033
+ const body = new URLSearchParams({
2034
+ client_id: options.clientId,
2035
+ code: options.input.code,
2036
+ code_verifier: options.input.codeVerifier,
2037
+ grant_type: "authorization_code",
2038
+ redirect_uri: options.input.redirectUri
2039
+ });
2040
+ let response;
2041
+ try {
2042
+ response = await (options.fetchImpl ?? fetch)(options.tokenUrl, {
2043
+ body,
2044
+ headers: { "content-type": "application/x-www-form-urlencoded" },
2045
+ method: "POST"
2046
+ });
2047
+ } catch (cause) {
2048
+ throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", { cause });
2049
+ }
2050
+ if (!response.ok) {
2051
+ throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", {
2052
+ statusCode: response.status
2053
+ });
2054
+ }
2055
+ let payload;
2056
+ try {
2057
+ payload = await response.json();
2058
+ } catch (cause) {
2059
+ throw new AuthError("AUTH_CODE_EXCHANGE_FAILED", { cause });
2060
+ }
2061
+ return parseTokenSet(payload);
2062
+ };
2063
+ var refreshSession = async (options) => {
2064
+ const body = new URLSearchParams({
2065
+ client_id: options.clientId,
2066
+ grant_type: "refresh_token",
2067
+ refresh_token: options.refreshToken
2068
+ });
2069
+ let response;
2070
+ try {
2071
+ response = await (options.fetchImpl ?? fetch)(options.tokenUrl, {
2072
+ body,
2073
+ headers: { "content-type": "application/x-www-form-urlencoded" },
2074
+ method: "POST"
2075
+ });
2076
+ } catch (cause) {
2077
+ throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", { cause });
2078
+ }
2079
+ if (!response.ok) {
2080
+ throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", {
2081
+ statusCode: response.status
2082
+ });
2083
+ }
2084
+ let payload;
2085
+ try {
2086
+ payload = await response.json();
2087
+ } catch (cause) {
2088
+ throw new AuthError("AUTH_REAUTHENTICATION_REQUIRED", { cause });
2089
+ }
2090
+ return parseTokenSet(payload);
2091
+ };
2092
+ var createAuthSession = (options) => {
2093
+ const tokenUrl = new URL("/oauth/token", options.issuerUrl);
2094
+ return {
2095
+ authorizationUrl: (request) => buildAuthorizeUrl(options.issuerUrl, request),
2096
+ exchangeCode: (input) => exchangeCodeAndParse({
2097
+ clientId: options.clientId,
2098
+ ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl },
2099
+ input,
2100
+ tokenUrl
2101
+ }),
2102
+ refresh: (refreshToken) => refreshSession({
2103
+ clientId: options.clientId,
2104
+ ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl },
2105
+ refreshToken,
2106
+ tokenUrl
2107
+ })
2108
+ };
2109
+ };
2110
+ var DEFAULT_CALLBACK_PAGE_COPY = {
2111
+ errorHeadline: "Sign-in failed",
2112
+ errorSubline: "Return to the app and retry.",
2113
+ successHeadline: "Signed in to route33",
2114
+ successSubline: "You can close this window."
2115
+ };
2116
+ var MARK_PATHS = [
2117
+ "M310.6,175.8c0-6.1-2.7-11.8-7.2-15.9l-127.6-114.4V7h-43.5v48.3c0,6.2,2.6,12.1,7.2,16.2l92.5,82.9H0v43.5h234.7l-95.6,91.4c-4.3,4.1-6.7,9.8-6.7,15.7v48.3h43.5v-39l128.1-122.4c4.4-4.2,6.8-10,6.7-16.1h0Z",
2118
+ "M457.2,175.9v-2.6c18.4-4.9,33-14.1,44-27.7,11-13.6,16.5-30.3,16.5-50.3s-4.5-32.9-13.4-47.5c-9-14.5-21.6-26.1-38-34.9-16.4-8.7-35.8-13.1-58.3-13.1s-41.1,4-58.8,12.1-31.8,19.3-42.4,33.7-16.1,31-16.6,50h51.1c.3-10.8,3.6-20,9.8-27.7,6.2-7.6,14.2-13.5,24.1-17.5,9.9-4.1,20.6-6.1,32-6.1s22.3,2.2,31.1,6.7c8.8,4.5,15.6,10.8,20.5,18.8,4.9,8.1,7.3,17.5,7.3,28.4s-2.8,21.1-8.4,29.4-13.3,14.8-23.2,19.5-21.3,7.1-34.2,7.1h-29.9v43.3h29.9c16.2,0,30,2.5,41.5,7.5,11.5,5,20.2,12,26.1,21.1,6,9,9,19.4,9,31.2s-3,21.2-9.1,29.8-14.4,15.3-25.1,20.1c-10.7,4.9-22.9,7.3-36.7,7.3s-24.2-2.1-34.5-6.2-18.6-10-24.8-17.5c-6.3-7.5-9.8-16.5-10.6-26.8h-53.2c.6,19,6.3,35.7,17,50.2,10.7,14.5,25.2,25.7,43.6,33.8,18.4,8.1,39.4,12.1,63.1,12.1s45.1-4.4,63.7-13.2c18.6-8.8,33.3-20.8,44-36,10.8-15.2,16.1-32.5,16.1-51.8s-6.4-40.7-19.2-55.6c-12.8-14.9-30.8-24.2-54-27.8h0Z",
2119
+ "M763,203.7c-12.8-14.9-30.8-24.2-54-27.8v-2.6c18.4-4.9,33-14.1,44-27.7,11-13.6,16.5-30.3,16.5-50.3s-4.5-32.9-13.4-47.5c-8.9-14.5-21.6-26.1-38-34.9-16.4-8.7-35.8-13.1-58.3-13.1s-41.1,4-58.8,12.1-31.8,19.3-42.4,33.7-16.1,31-16.6,50h51.1c.3-10.8,3.6-20,9.8-27.7,6.2-7.6,14.2-13.5,24.1-17.5,9.9-4.1,20.6-6.1,32-6.1s22.3,2.2,31.1,6.7c8.8,4.5,15.6,10.8,20.5,18.8,4.9,8.1,7.3,17.5,7.3,28.4s-2.8,21.1-8.4,29.4c-5.6,8.3-13.3,14.8-23.2,19.5s-21.3,7.1-34.2,7.1h-29.9v43.3h29.9c16.2,0,30,2.5,41.5,7.5,11.5,5,20.2,12,26.1,21.1,6,9,8.9,19.4,8.9,31.2s-3,21.2-9.1,29.8c-6.1,8.6-14.4,15.3-25.1,20.1-10.7,4.9-22.9,7.3-36.7,7.3s-24.2-2.1-34.5-6.2-18.6-10-24.8-17.5c-6.3-7.5-9.8-16.5-10.6-26.8h-53.2c.6,19,6.3,35.7,17,50.2,10.7,14.5,25.2,25.7,43.6,33.8,18.4,8.1,39.4,12.1,63.1,12.1s45.1-4.4,63.7-13.2,33.3-20.8,44-36c10.8-15.2,16.1-32.5,16.1-51.8s-6.4-40.7-19.2-55.6h0Z"
2120
+ ];
2121
+ var BRAND_MARK = `<svg class="r33-mark" viewBox="0 0 782.2 360.3" fill="currentColor" role="img" aria-label="route33.ai" xmlns="http://www.w3.org/2000/svg"><path d="${MARK_PATHS[0]}"/><path d="${MARK_PATHS[1]}"/><path d="${MARK_PATHS[2]}"/></svg>`;
2122
+ var PAGE_STYLE = `:root{color-scheme:dark;--r33-euro-blue:#0000FF;--r33-off-white:#F1F1F1;--r33-off-black:#121212;--r33-grey-300:#C9CBCF;--r33-radius-fillet:4px;--r33-space-2:8px;--r33-space-3:16px;--r33-space-4:24px;--r33-space-6:64px;--r33-font-body:"Geist","Helvetica Neue",Arial,sans-serif;--r33-font-mono:"Geist Mono","SFMono-Regular",Menlo,monospace;--r33-surface:var(--r33-off-black);--r33-text-primary:var(--r33-off-white);--r33-text-secondary:var(--r33-grey-300);--r33-fill-accent:var(--r33-euro-blue);--r33-on-fill-accent:var(--r33-off-white)}
2123
+ *{box-sizing:border-box}
2124
+ html,body{margin:0}
2125
+ .r33-page{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:var(--r33-space-6);background:var(--r33-surface);color:var(--r33-text-primary);font-family:var(--r33-font-body);-webkit-font-smoothing:antialiased}
2126
+ .r33-panel{display:grid;gap:var(--r33-space-4);max-width:460px;width:100%}
2127
+ .r33-mark{height:40px;width:auto;color:var(--r33-text-primary)}
2128
+ .r33-status{display:inline-flex;align-items:center;gap:var(--r33-space-2);font-size:11px;letter-spacing:0.08em;text-transform:uppercase;color:var(--r33-text-secondary)}
2129
+ .r33-status__dot{width:8px;height:8px;background:var(--r33-fill-accent)}
2130
+ .r33-status__dot--error{background:transparent;border:1px solid var(--r33-text-primary);border-radius:50%}
2131
+ .r33-headline{margin:0;font-size:48px;line-height:0.85;letter-spacing:-0.02em;font-weight:600;color:var(--r33-text-primary);text-wrap:balance}
2132
+ .r33-subline{margin:0;font-size:16px;line-height:1.45;color:var(--r33-text-secondary);max-width:40ch;text-wrap:pretty}
2133
+ .r33-code{margin:0;font-size:13px;letter-spacing:0.04em;color:var(--r33-text-secondary)}
2134
+ .r33-code__value{font-family:var(--r33-font-mono);text-transform:uppercase;color:var(--r33-text-primary)}
2135
+ @media (prefers-reduced-motion:reduce){*{animation-duration:1ms!important;transition-duration:1ms!important}}`;
2136
+ var buildCallbackPage = (state, errorCode, copy = {}) => {
2137
+ const pageCopy = { ...DEFAULT_CALLBACK_PAGE_COPY, ...copy };
2138
+ const isError = state === "error";
2139
+ const safeCode = (errorCode ?? "").replace(/[^a-z0-9_-]/gi, "");
2140
+ const title = isError ? pageCopy.errorHeadline : pageCopy.successHeadline;
2141
+ const headline = title;
2142
+ const subline = isError ? pageCopy.errorSubline : pageCopy.successSubline;
2143
+ const statusLabel = isError ? "Authentication error" : "Authenticated";
2144
+ const dotClass = isError ? "r33-status__dot r33-status__dot--error" : "r33-status__dot";
2145
+ const codeLine = isError && safeCode.length > 0 ? `<p class="r33-code">Error code: <span class="r33-code__value">${safeCode}</span></p>` : "";
2146
+ return `<!doctype html>
2147
+ <html lang="en" data-theme="dark">
2148
+ <head>
2149
+ <meta charset="utf-8">
2150
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2151
+ <title>${title} \xB7 route33.ai</title>
2152
+ <style>${PAGE_STYLE}</style>
2153
+ </head>
2154
+ <body>
2155
+ <main class="r33-page">
2156
+ <div class="r33-panel">
2157
+ ${BRAND_MARK}
2158
+ <span class="r33-status"><span class="${dotClass}"></span>${statusLabel}</span>
2159
+ <h1 class="r33-headline">${headline}</h1>
2160
+ <p class="r33-subline">${subline}</p>
2161
+ ${codeLine}
2162
+ </div>
2163
+ </main>
2164
+ </body>
2165
+ </html>`;
2166
+ };
2167
+ var createAuthLoopbackCallback = async (options = {}) => {
2168
+ let redirectUri = "http://127.0.0.1/callback";
2169
+ let resolveCapture;
2170
+ const captured = new Promise((resolve) => {
2171
+ resolveCapture = resolve;
2172
+ });
2173
+ const server = createServer((request, response) => {
2174
+ const url = new URL(request.url ?? "/", redirectUri);
2175
+ if (request.method !== "GET" || url.pathname !== "/callback") {
2176
+ response.writeHead(404).end();
2177
+ return;
2178
+ }
2179
+ const resolve = resolveCapture;
2180
+ resolveCapture = void 0;
2181
+ resolve?.(url);
2182
+ const error = url.searchParams.get("error");
2183
+ const page = error === null || error.length === 0 ? buildCallbackPage("success", void 0, options.pageCopy) : buildCallbackPage("error", error, options.pageCopy);
2184
+ response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
2185
+ response.end(page);
2186
+ });
2187
+ await new Promise((resolve, reject) => {
2188
+ const onError = (cause) => {
2189
+ reject(new AuthError("AUTH_CALLBACK_LISTEN_FAILED", { cause }));
2190
+ };
2191
+ server.once("error", onError);
2192
+ server.listen(0, "127.0.0.1", () => {
2193
+ server.off("error", onError);
2194
+ resolve();
2195
+ });
2196
+ });
2197
+ const address = server.address();
2198
+ if (address === null || typeof address === "string") {
2199
+ server.close();
2200
+ throw new AuthError("AUTH_CALLBACK_LISTEN_FAILED");
2201
+ }
2202
+ redirectUri = `http://127.0.0.1:${String(address.port)}/callback`;
2203
+ return {
2204
+ redirectUri,
2205
+ close: () => {
2206
+ if (!server.listening) {
2207
+ return Promise.resolve();
2208
+ }
2209
+ return new Promise((resolve, reject) => {
2210
+ server.close((cause) => {
2211
+ if (cause === void 0) {
2212
+ resolve();
2213
+ return;
2214
+ }
2215
+ reject(new AuthError("AUTH_CALLBACK_CLEANUP_FAILED", { cause }));
2216
+ });
2217
+ });
2218
+ },
2219
+ wait: () => captured
2220
+ };
2221
+ };
2222
+ var openSystemBrowser = async (url, options = {}) => new Promise((resolve, reject) => {
2223
+ let command = "xdg-open";
2224
+ let args = [url.href];
2225
+ if (process.platform === "darwin") {
2226
+ command = "open";
2227
+ } else if (process.platform === "win32") {
2228
+ command = "cmd";
2229
+ args = ["/c", "start", "", url.href];
2230
+ }
2231
+ if (options.spawnUrl !== void 0) {
2232
+ options.spawnUrl(command, args, { detached: true, stdio: "ignore" });
2233
+ resolve();
2234
+ return;
2235
+ }
2236
+ const child = spawn(command, args, {
2237
+ detached: true,
2238
+ stdio: "ignore"
2239
+ });
2240
+ child.once("error", reject);
2241
+ child.once("spawn", () => {
2242
+ child.unref();
2243
+ resolve();
2244
+ });
2245
+ });
2246
+ var openBrowserAndCapture = async (options) => {
2247
+ const callback = await createAuthLoopbackCallback(
2248
+ options.pageCopy === void 0 ? {} : { pageCopy: options.pageCopy }
2249
+ );
2250
+ const authorizationUrl = options.authorizationUrl(callback.redirectUri);
2251
+ const browserRunner = options.browserRunner ?? ((url) => openSystemBrowser(url));
2252
+ let timer;
2253
+ const timeout = new Promise((_resolve, reject) => {
2254
+ timer = setTimeout(() => {
2255
+ reject(new AuthError("AUTH_CALLBACK_TIMEOUT"));
2256
+ }, options.timeoutMs ?? 12e4);
2257
+ });
2258
+ const launch = browserRunner(authorizationUrl).catch((cause) => {
2259
+ throw new AuthError("AUTH_BROWSER_LAUNCH_FAILED", { cause });
2260
+ });
2261
+ try {
2262
+ const completed = await Promise.race([
2263
+ Promise.all([launch, callback.wait()]),
2264
+ timeout
2265
+ ]);
2266
+ const callbackUrl = completed[1];
2267
+ const actualState = callbackUrl.searchParams.get("state");
2268
+ if (actualState === null) {
2269
+ throw new AuthError("AUTH_CALLBACK_RESPONSE_INVALID");
2270
+ }
2271
+ const expectedState = Buffer.from(options.expectedState);
2272
+ const receivedState = Buffer.from(actualState);
2273
+ if (expectedState.length !== receivedState.length || !timingSafeEqual(expectedState, receivedState)) {
2274
+ throw new AuthError("AUTH_CALLBACK_STATE_MISMATCH");
2275
+ }
2276
+ const code = callbackUrl.searchParams.get("code");
2277
+ if (code === null || code.length === 0) {
2278
+ throw new AuthError("AUTH_CALLBACK_RESPONSE_INVALID");
2279
+ }
2280
+ return { code, redirectUri: callback.redirectUri };
2281
+ } finally {
2282
+ if (timer !== void 0) {
2283
+ clearTimeout(timer);
2284
+ }
2285
+ await callback.close();
2286
+ }
2287
+ };
2288
+ var loginFlow = async (options) => {
2289
+ const log2 = options.logger ?? { info: () => void 0 };
2290
+ log2.info("auth.login.started");
2291
+ const pkce = createPkceVerifierAndChallenge();
2292
+ const captured = await openBrowserAndCapture({
2293
+ authorizationUrl: (redirectUri) => options.session.authorizationUrl({
2294
+ clientId: options.clientId,
2295
+ codeChallenge: pkce.codeChallenge,
2296
+ redirectUri,
2297
+ scope: options.scope,
2298
+ state: pkce.state
2299
+ }),
2300
+ ...options.browserRunner === void 0 ? {} : { browserRunner: options.browserRunner },
2301
+ expectedState: pkce.state,
2302
+ ...options.pageCopy === void 0 ? {} : { pageCopy: options.pageCopy },
2303
+ ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
2304
+ });
2305
+ const tokenSet = await options.session.exchangeCode({
2306
+ code: captured.code,
2307
+ codeVerifier: pkce.codeVerifier,
2308
+ redirectUri: captured.redirectUri
2309
+ });
2310
+ log2.info("auth.login.completed");
2311
+ return tokenSet;
2312
+ };
2313
+
2314
+ // src/login/wizard-login/wizard-login.ts
2315
+ var wizardLogin = async (options) => {
2316
+ if (options.clientId === "") {
2317
+ throw new Error(
2318
+ "No Route 33 OAuth client id configured \u2014 set ROUTE33_CLIENT_ID."
2319
+ );
2320
+ }
2321
+ const session = createAuthSession({
2322
+ clientId: options.clientId,
2323
+ issuerUrl: issuerUrl(options.issuerOverride)
2324
+ });
2325
+ const tokenSet = await loginFlow({
2326
+ clientId: options.clientId,
2327
+ scope: REQUESTED_OAUTH_SCOPES,
2328
+ session
2329
+ });
2330
+ return { accessToken: tokenSet.access_token };
2331
+ };
2332
+
2333
+ // src/management/error-message/error-message.ts
2334
+ var errorMessage = (error) => {
2335
+ if (error === null || typeof error !== "object") return "";
2336
+ const record = error;
2337
+ if (typeof record["error"] === "string") return record["error"];
2338
+ if (typeof record["message"] === "string") return record["message"];
2339
+ return "";
2340
+ };
2341
+
2342
+ // src/management/management-failure/management-failure.ts
2343
+ var classifyManagementOutcome = (raw) => {
2344
+ if (raw.data !== void 0) return { kind: "ok", data: raw.data };
2345
+ const status = raw.response?.status ?? 0;
2346
+ if (status === 401 || status === 403) return { kind: "unauthorized" };
2347
+ if (status > 0) {
2348
+ return { kind: "http", status, message: errorMessage(raw.error) };
2349
+ }
2350
+ return { kind: "network", message: errorMessage(raw.error) };
2351
+ };
2352
+
2353
+ // src/management/mint-request-body/mint-request-body.ts
2354
+ var mintRequestBody = (input) => ({
2355
+ budget_currency: "EUR",
2356
+ expires_at: input.expiresAt,
2357
+ name: input.name,
2358
+ owner_type: input.ownerType,
2359
+ ...input.projectId === null ? {} : { project_id: input.projectId },
2360
+ owner_user_id: input.ownerId
2361
+ });
2362
+
2363
+ // src/management/create-org-key/create-org-key.ts
2364
+ var createOrgKey = async (client, input) => {
2365
+ const outcome = classifyManagementOutcome(
2366
+ await client.POST("/api/v1/api-keys", {
2367
+ body: mintRequestBody(input)
2368
+ })
2369
+ );
2370
+ if (outcome.kind !== "ok") {
2371
+ throw new Error(`creating the key failed (${outcome.kind})`);
2372
+ }
2373
+ const key = outcome.data["key"];
2374
+ if (typeof key !== "string" || key === "") {
2375
+ throw new Error("creating the key returned no key material");
2376
+ }
2377
+ return key;
2378
+ };
2379
+
2380
+ // ../../node_modules/.pnpm/openapi-fetch@0.17.0/node_modules/openapi-fetch/dist/index.mjs
2381
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
2382
+ var supportsRequestInitExt = () => {
2383
+ return typeof process === "object" && Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 && process.versions.undici;
2384
+ };
2385
+ function randomID() {
2386
+ return Math.random().toString(36).slice(2, 11);
2387
+ }
2388
+ function createClient(clientOptions) {
2389
+ let {
2390
+ baseUrl = "",
2391
+ Request: CustomRequest = globalThis.Request,
2392
+ fetch: baseFetch = globalThis.fetch,
2393
+ querySerializer: globalQuerySerializer,
2394
+ bodySerializer: globalBodySerializer,
2395
+ pathSerializer: globalPathSerializer,
2396
+ headers: baseHeaders,
2397
+ requestInitExt = void 0,
2398
+ ...baseOptions
2399
+ } = { ...clientOptions };
2400
+ requestInitExt = supportsRequestInitExt() ? requestInitExt : void 0;
2401
+ baseUrl = removeTrailingSlash(baseUrl);
2402
+ const globalMiddlewares = [];
2403
+ async function coreFetch(schemaPath, fetchOptions) {
2404
+ const {
2405
+ baseUrl: localBaseUrl,
2406
+ fetch: fetch2 = baseFetch,
2407
+ Request: Request2 = CustomRequest,
2408
+ headers,
2409
+ params = {},
2410
+ parseAs = "json",
2411
+ querySerializer: requestQuerySerializer,
2412
+ bodySerializer = globalBodySerializer ?? defaultBodySerializer,
2413
+ pathSerializer: requestPathSerializer,
2414
+ body,
2415
+ middleware: requestMiddlewares = [],
2416
+ ...init
2417
+ } = fetchOptions || {};
2418
+ let finalBaseUrl = baseUrl;
2419
+ if (localBaseUrl) {
2420
+ finalBaseUrl = removeTrailingSlash(localBaseUrl) ?? baseUrl;
2421
+ }
2422
+ let querySerializer = typeof globalQuerySerializer === "function" ? globalQuerySerializer : createQuerySerializer(globalQuerySerializer);
2423
+ if (requestQuerySerializer) {
2424
+ querySerializer = typeof requestQuerySerializer === "function" ? requestQuerySerializer : createQuerySerializer({
2425
+ ...typeof globalQuerySerializer === "object" ? globalQuerySerializer : {},
2426
+ ...requestQuerySerializer
2427
+ });
2428
+ }
2429
+ const pathSerializer = requestPathSerializer || globalPathSerializer || defaultPathSerializer;
2430
+ const serializedBody = body === void 0 ? void 0 : bodySerializer(
2431
+ body,
2432
+ // Note: we declare mergeHeaders() both here and below because it’s a bit of a chicken-or-egg situation:
2433
+ // bodySerializer() needs all headers so we aren’t dropping ones set by the user, however,
2434
+ // the result of this ALSO sets the lowest-priority content-type header. So we re-merge below,
2435
+ // setting the content-type at the very beginning to be overwritten.
2436
+ // Lastly, based on the way headers work, it’s not a simple “present-or-not” check becauase null intentionally un-sets headers.
2437
+ mergeHeaders(baseHeaders, headers, params.header)
2438
+ );
2439
+ const finalHeaders = mergeHeaders(
2440
+ // with no body, we should not to set Content-Type
2441
+ serializedBody === void 0 || // if serialized body is FormData; browser will correctly set Content-Type & boundary expression
2442
+ serializedBody instanceof FormData ? {} : {
2443
+ "Content-Type": "application/json"
2444
+ },
2445
+ baseHeaders,
2446
+ headers,
2447
+ params.header
2448
+ );
2449
+ const finalMiddlewares = [...globalMiddlewares, ...requestMiddlewares];
2450
+ const requestInit = {
2451
+ redirect: "follow",
2452
+ ...baseOptions,
2453
+ ...init,
2454
+ body: serializedBody,
2455
+ headers: finalHeaders
2456
+ };
2457
+ let id;
2458
+ let options;
2459
+ let request = new Request2(
2460
+ createFinalURL(schemaPath, { baseUrl: finalBaseUrl, params, querySerializer, pathSerializer }),
2461
+ requestInit
2462
+ );
2463
+ let response;
2464
+ for (const key in init) {
2465
+ if (!(key in request)) {
2466
+ request[key] = init[key];
2467
+ }
2468
+ }
2469
+ if (finalMiddlewares.length) {
2470
+ id = randomID();
2471
+ options = Object.freeze({
2472
+ baseUrl: finalBaseUrl,
2473
+ fetch: fetch2,
2474
+ parseAs,
2475
+ querySerializer,
2476
+ bodySerializer,
2477
+ pathSerializer
2478
+ });
2479
+ for (const m of finalMiddlewares) {
2480
+ if (m && typeof m === "object" && typeof m.onRequest === "function") {
2481
+ const result = await m.onRequest({
2482
+ request,
2483
+ schemaPath,
2484
+ params,
2485
+ options,
2486
+ id
2487
+ });
2488
+ if (result) {
2489
+ if (result instanceof Request2) {
2490
+ request = result;
2491
+ } else if (result instanceof Response) {
2492
+ response = result;
2493
+ break;
2494
+ } else {
2495
+ throw new Error("onRequest: must return new Request() or Response() when modifying the request");
2496
+ }
2497
+ }
2498
+ }
2499
+ }
2500
+ }
2501
+ if (!response) {
2502
+ try {
2503
+ response = await fetch2(request, requestInitExt);
2504
+ } catch (error2) {
2505
+ let errorAfterMiddleware = error2;
2506
+ if (finalMiddlewares.length) {
2507
+ for (let i2 = finalMiddlewares.length - 1; i2 >= 0; i2--) {
2508
+ const m = finalMiddlewares[i2];
2509
+ if (m && typeof m === "object" && typeof m.onError === "function") {
2510
+ const result = await m.onError({
2511
+ request,
2512
+ error: errorAfterMiddleware,
2513
+ schemaPath,
2514
+ params,
2515
+ options,
2516
+ id
2517
+ });
2518
+ if (result) {
2519
+ if (result instanceof Response) {
2520
+ errorAfterMiddleware = void 0;
2521
+ response = result;
2522
+ break;
2523
+ }
2524
+ if (result instanceof Error) {
2525
+ errorAfterMiddleware = result;
2526
+ continue;
2527
+ }
2528
+ throw new Error("onError: must return new Response() or instance of Error");
2529
+ }
2530
+ }
2531
+ }
2532
+ }
2533
+ if (errorAfterMiddleware) {
2534
+ throw errorAfterMiddleware;
2535
+ }
2536
+ }
2537
+ if (finalMiddlewares.length) {
2538
+ for (let i2 = finalMiddlewares.length - 1; i2 >= 0; i2--) {
2539
+ const m = finalMiddlewares[i2];
2540
+ if (m && typeof m === "object" && typeof m.onResponse === "function") {
2541
+ const result = await m.onResponse({
2542
+ request,
2543
+ response,
2544
+ schemaPath,
2545
+ params,
2546
+ options,
2547
+ id
2548
+ });
2549
+ if (result) {
2550
+ if (!(result instanceof Response)) {
2551
+ throw new Error("onResponse: must return new Response() when modifying the response");
2552
+ }
2553
+ response = result;
2554
+ }
2555
+ }
2556
+ }
2557
+ }
2558
+ }
2559
+ const contentLength = response.headers.get("Content-Length");
2560
+ if (response.status === 204 || request.method === "HEAD" || contentLength === "0" && !response.headers.get("Transfer-Encoding")?.includes("chunked")) {
2561
+ return response.ok ? { data: void 0, response } : { error: void 0, response };
2562
+ }
2563
+ if (response.ok) {
2564
+ const getResponseData = async () => {
2565
+ if (parseAs === "stream") {
2566
+ return response.body;
2567
+ }
2568
+ if (parseAs === "json" && !contentLength) {
2569
+ const raw = await response.text();
2570
+ return raw ? JSON.parse(raw) : void 0;
2571
+ }
2572
+ return await response[parseAs]();
2573
+ };
2574
+ return { data: await getResponseData(), response };
2575
+ }
2576
+ let error = await response.text();
2577
+ try {
2578
+ error = JSON.parse(error);
2579
+ } catch {
2580
+ }
2581
+ return { error, response };
2582
+ }
2583
+ return {
2584
+ request(method, url, init) {
2585
+ return coreFetch(url, { ...init, method: method.toUpperCase() });
2586
+ },
2587
+ /** Call a GET endpoint */
2588
+ GET(url, init) {
2589
+ return coreFetch(url, { ...init, method: "GET" });
2590
+ },
2591
+ /** Call a PUT endpoint */
2592
+ PUT(url, init) {
2593
+ return coreFetch(url, { ...init, method: "PUT" });
2594
+ },
2595
+ /** Call a POST endpoint */
2596
+ POST(url, init) {
2597
+ return coreFetch(url, { ...init, method: "POST" });
2598
+ },
2599
+ /** Call a DELETE endpoint */
2600
+ DELETE(url, init) {
2601
+ return coreFetch(url, { ...init, method: "DELETE" });
2602
+ },
2603
+ /** Call a OPTIONS endpoint */
2604
+ OPTIONS(url, init) {
2605
+ return coreFetch(url, { ...init, method: "OPTIONS" });
2606
+ },
2607
+ /** Call a HEAD endpoint */
2608
+ HEAD(url, init) {
2609
+ return coreFetch(url, { ...init, method: "HEAD" });
2610
+ },
2611
+ /** Call a PATCH endpoint */
2612
+ PATCH(url, init) {
2613
+ return coreFetch(url, { ...init, method: "PATCH" });
2614
+ },
2615
+ /** Call a TRACE endpoint */
2616
+ TRACE(url, init) {
2617
+ return coreFetch(url, { ...init, method: "TRACE" });
2618
+ },
2619
+ /** Register middleware */
2620
+ use(...middleware) {
2621
+ for (const m of middleware) {
2622
+ if (!m) {
2623
+ continue;
2624
+ }
2625
+ if (typeof m !== "object" || !("onRequest" in m || "onResponse" in m || "onError" in m)) {
2626
+ throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
2627
+ }
2628
+ globalMiddlewares.push(m);
2629
+ }
2630
+ },
2631
+ /** Unregister middleware */
2632
+ eject(...middleware) {
2633
+ for (const m of middleware) {
2634
+ const i2 = globalMiddlewares.indexOf(m);
2635
+ if (i2 !== -1) {
2636
+ globalMiddlewares.splice(i2, 1);
2637
+ }
2638
+ }
2639
+ }
2640
+ };
2641
+ }
2642
+ function serializePrimitiveParam(name, value, options) {
2643
+ if (value === void 0 || value === null) {
2644
+ return "";
2645
+ }
2646
+ if (typeof value === "object") {
2647
+ throw new Error(
2648
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
2649
+ );
2650
+ }
2651
+ return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;
2652
+ }
2653
+ function serializeObjectParam(name, value, options) {
2654
+ if (!value || typeof value !== "object") {
2655
+ return "";
2656
+ }
2657
+ const values = [];
2658
+ const joiner = {
2659
+ simple: ",",
2660
+ label: ".",
2661
+ matrix: ";"
2662
+ }[options.style] || "&";
2663
+ if (options.style !== "deepObject" && options.explode === false) {
2664
+ for (const k in value) {
2665
+ values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));
2666
+ }
2667
+ const final2 = values.join(",");
2668
+ switch (options.style) {
2669
+ case "form": {
2670
+ return `${name}=${final2}`;
2671
+ }
2672
+ case "label": {
2673
+ return `.${final2}`;
2674
+ }
2675
+ case "matrix": {
2676
+ return `;${name}=${final2}`;
2677
+ }
2678
+ default: {
2679
+ return final2;
2680
+ }
2681
+ }
2682
+ }
2683
+ for (const k in value) {
2684
+ const finalName = options.style === "deepObject" ? `${name}[${k}]` : k;
2685
+ values.push(serializePrimitiveParam(finalName, value[k], options));
2686
+ }
2687
+ const final = values.join(joiner);
2688
+ return options.style === "label" || options.style === "matrix" ? `${joiner}${final}` : final;
2689
+ }
2690
+ function serializeArrayParam(name, value, options) {
2691
+ if (!Array.isArray(value)) {
2692
+ return "";
2693
+ }
2694
+ if (options.explode === false) {
2695
+ const joiner2 = { form: ",", spaceDelimited: "%20", pipeDelimited: "|" }[options.style] || ",";
2696
+ const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner2);
2697
+ switch (options.style) {
2698
+ case "simple": {
2699
+ return final;
2700
+ }
2701
+ case "label": {
2702
+ return `.${final}`;
2703
+ }
2704
+ case "matrix": {
2705
+ return `;${name}=${final}`;
2706
+ }
2707
+ // case "spaceDelimited":
2708
+ // case "pipeDelimited":
2709
+ default: {
2710
+ return `${name}=${final}`;
2711
+ }
2712
+ }
2713
+ }
2714
+ const joiner = { simple: ",", label: ".", matrix: ";" }[options.style] || "&";
2715
+ const values = [];
2716
+ for (const v of value) {
2717
+ if (options.style === "simple" || options.style === "label") {
2718
+ values.push(options.allowReserved === true ? v : encodeURIComponent(v));
2719
+ } else {
2720
+ values.push(serializePrimitiveParam(name, v, options));
2721
+ }
2722
+ }
2723
+ return options.style === "label" || options.style === "matrix" ? `${joiner}${values.join(joiner)}` : values.join(joiner);
2724
+ }
2725
+ function createQuerySerializer(options) {
2726
+ return function querySerializer(queryParams) {
2727
+ const search = [];
2728
+ if (queryParams && typeof queryParams === "object") {
2729
+ for (const name in queryParams) {
2730
+ const value = queryParams[name];
2731
+ if (value === void 0 || value === null) {
2732
+ continue;
2733
+ }
2734
+ if (Array.isArray(value)) {
2735
+ if (value.length === 0) {
2736
+ continue;
2737
+ }
2738
+ search.push(
2739
+ serializeArrayParam(name, value, {
2740
+ style: "form",
2741
+ explode: true,
2742
+ ...options?.array,
2743
+ allowReserved: options?.allowReserved || false
2744
+ })
2745
+ );
2746
+ continue;
2747
+ }
2748
+ if (typeof value === "object") {
2749
+ search.push(
2750
+ serializeObjectParam(name, value, {
2751
+ style: "deepObject",
2752
+ explode: true,
2753
+ ...options?.object,
2754
+ allowReserved: options?.allowReserved || false
2755
+ })
2756
+ );
2757
+ continue;
2758
+ }
2759
+ search.push(serializePrimitiveParam(name, value, options));
2760
+ }
2761
+ }
2762
+ return search.join("&");
2763
+ };
2764
+ }
2765
+ function defaultPathSerializer(pathname, pathParams) {
2766
+ let nextURL = pathname;
2767
+ for (const match of pathname.match(PATH_PARAM_RE) ?? []) {
2768
+ let name = match.substring(1, match.length - 1);
2769
+ let explode = false;
2770
+ let style = "simple";
2771
+ if (name.endsWith("*")) {
2772
+ explode = true;
2773
+ name = name.substring(0, name.length - 1);
2774
+ }
2775
+ if (name.startsWith(".")) {
2776
+ style = "label";
2777
+ name = name.substring(1);
2778
+ } else if (name.startsWith(";")) {
2779
+ style = "matrix";
2780
+ name = name.substring(1);
2781
+ }
2782
+ if (!pathParams || pathParams[name] === void 0 || pathParams[name] === null) {
2783
+ continue;
2784
+ }
2785
+ const value = pathParams[name];
2786
+ if (Array.isArray(value)) {
2787
+ nextURL = nextURL.replace(match, serializeArrayParam(name, value, { style, explode }));
2788
+ continue;
2789
+ }
2790
+ if (typeof value === "object") {
2791
+ nextURL = nextURL.replace(match, serializeObjectParam(name, value, { style, explode }));
2792
+ continue;
2793
+ }
2794
+ if (style === "matrix") {
2795
+ nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);
2796
+ continue;
2797
+ }
2798
+ nextURL = nextURL.replace(match, style === "label" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));
2799
+ }
2800
+ return nextURL;
2801
+ }
2802
+ function defaultBodySerializer(body, headers) {
2803
+ if (body instanceof FormData) {
2804
+ return body;
2805
+ }
2806
+ if (headers) {
2807
+ const contentType = headers.get instanceof Function ? headers.get("Content-Type") ?? headers.get("content-type") : headers["Content-Type"] ?? headers["content-type"];
2808
+ if (contentType === "application/x-www-form-urlencoded") {
2809
+ return new URLSearchParams(body).toString();
2810
+ }
2811
+ }
2812
+ return JSON.stringify(body);
2813
+ }
2814
+ function createFinalURL(pathname, options) {
2815
+ let finalURL = `${options.baseUrl}${pathname}`;
2816
+ if (options.params?.path) {
2817
+ finalURL = options.pathSerializer(finalURL, options.params.path);
2818
+ }
2819
+ let search = options.querySerializer(options.params.query ?? {});
2820
+ if (search.startsWith("?")) {
2821
+ search = search.substring(1);
2822
+ }
2823
+ if (search) {
2824
+ finalURL += `?${search}`;
2825
+ }
2826
+ return finalURL;
2827
+ }
2828
+ function mergeHeaders(...allHeaders) {
2829
+ const finalHeaders = new Headers();
2830
+ for (const h2 of allHeaders) {
2831
+ if (!h2 || typeof h2 !== "object") {
2832
+ continue;
2833
+ }
2834
+ const iterator = h2 instanceof Headers ? h2.entries() : Object.entries(h2);
2835
+ for (const [k, v] of iterator) {
2836
+ if (v === null) {
2837
+ finalHeaders.delete(k);
2838
+ } else if (Array.isArray(v)) {
2839
+ for (const v2 of v) {
2840
+ finalHeaders.append(k, v2);
2841
+ }
2842
+ } else if (v !== void 0) {
2843
+ finalHeaders.set(k, v);
2844
+ }
2845
+ }
2846
+ }
2847
+ return finalHeaders;
2848
+ }
2849
+ function removeTrailingSlash(url) {
2850
+ if (url.endsWith("/")) {
2851
+ return url.substring(0, url.length - 1);
2852
+ }
2853
+ return url;
2854
+ }
2855
+
2856
+ // ../sdk/dist/index.js
2857
+ var Route33SdkError = class extends Error {
2858
+ code;
2859
+ constructor(code, message, options) {
2860
+ super(message, options);
2861
+ this.name = "Route33SdkError";
2862
+ this.code = code;
2863
+ }
2864
+ };
2865
+ var DEFAULT_BASE_URL = "https://mapi.route33.ai";
2866
+ var DEFAULT_TIMEOUT_MS = 3e4;
2867
+ var createRoute33Client = (options = {}) => {
2868
+ const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
2869
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2870
+ const baseFetch = options.fetch ?? globalThis.fetch;
2871
+ const resolveToken = async (source) => {
2872
+ try {
2873
+ return await source;
2874
+ } catch (cause) {
2875
+ throw new Route33SdkError(
2876
+ "SDK_AUTH_UNAVAILABLE",
2877
+ "Resolving the bearer token failed.",
2878
+ {
2879
+ cause
2880
+ }
2881
+ );
2882
+ }
2883
+ };
2884
+ const mergeSignals = (init) => {
2885
+ const caller = init?.signal ?? void 0;
2886
+ if (timeoutMs <= 0) {
2887
+ return caller;
2888
+ }
2889
+ const timeout = AbortSignal.timeout(timeoutMs);
2890
+ if (caller === void 0) {
2891
+ return timeout;
2892
+ }
2893
+ return AbortSignal.any([caller, timeout]);
2894
+ };
2895
+ const sendWithBearer = async (bearer, input, init) => {
2896
+ const headers = new Headers(
2897
+ init?.headers ?? (input instanceof Request ? input.headers : void 0)
2898
+ );
2899
+ if (bearer !== void 0 && bearer.length > 0) {
2900
+ headers.set("authorization", `Bearer ${bearer}`);
2901
+ }
2902
+ const signal = mergeSignals(init);
2903
+ const nextInit = {
2904
+ ...init,
2905
+ headers,
2906
+ ...signal === void 0 ? {} : { signal }
2907
+ };
2908
+ return baseFetch(input, nextInit);
2909
+ };
2910
+ const classifyTransportFailure = (cause) => {
2911
+ if (cause instanceof Route33SdkError) {
2912
+ return cause;
2913
+ }
2914
+ if (cause instanceof Error && cause.name === "AbortError") {
2915
+ return cause;
2916
+ }
2917
+ if (cause instanceof Error && cause.name === "TimeoutError") {
2918
+ return new Route33SdkError(
2919
+ "SDK_TIMEOUT",
2920
+ "The management API request timed out.",
2921
+ {
2922
+ cause
2923
+ }
2924
+ );
2925
+ }
2926
+ return new Route33SdkError(
2927
+ "SDK_NETWORK_ERROR",
2928
+ "The management API request failed at the network level.",
2929
+ { cause }
2930
+ );
2931
+ };
2932
+ const routedFetch = async (input, init) => {
2933
+ try {
2934
+ const firstToken = options.provider === void 0 ? void 0 : await resolveToken(options.provider.getToken());
2935
+ let response = await sendWithBearer(firstToken, input, init);
2936
+ if (response.status === 401 && options.provider !== void 0) {
2937
+ const retryToken = await resolveToken(
2938
+ options.provider.onUnauthorized()
2939
+ );
2940
+ response = await sendWithBearer(retryToken, input, init);
2941
+ }
2942
+ return response;
2943
+ } catch (cause) {
2944
+ throw classifyTransportFailure(cause);
2945
+ }
2946
+ };
2947
+ return createClient({ baseUrl, fetch: routedFetch });
2948
+ };
2949
+
2950
+ // src/management/org-header-fetch/org-header-fetch.ts
2951
+ var ACTIVE_ORG_HEADER = "X-Active-Org-Id";
2952
+ var orgHeaderFetch = (orgId, fetchImpl) => {
2953
+ const base = fetchImpl ?? globalThis.fetch;
2954
+ return (input, init) => {
2955
+ if (input instanceof Request) {
2956
+ input.headers.set(ACTIVE_ORG_HEADER, orgId);
2957
+ }
2958
+ if (init?.headers instanceof Headers) {
2959
+ init.headers.set(ACTIVE_ORG_HEADER, orgId);
2960
+ }
2961
+ return base(input, init);
2962
+ };
2963
+ };
2964
+
2965
+ // src/management/static-token-provider/static-token-provider.ts
2966
+ var staticTokenProvider = (token) => ({
2967
+ getToken: () => Promise.resolve(token),
2968
+ onUnauthorized: () => Promise.resolve(token)
2969
+ });
2970
+
2971
+ // src/management/create-wizard-management/create-wizard-management.ts
2972
+ var createWizardManagement = (accessToken, baseUrl, activeOrgId) => createRoute33Client({
2973
+ baseUrl,
2974
+ provider: staticTokenProvider(accessToken),
2975
+ ...activeOrgId === void 0 ? {} : { fetch: orgHeaderFetch(activeOrgId) }
2976
+ });
2977
+
2978
+ // src/management/is-usable-key/is-usable-key.ts
2979
+ var isUsableKey = (key, now) => key.status === "active" && !key.revoked && new Date(key.expires_at) > now;
2980
+
2981
+ // src/management/drain-key-pages/drain-key-pages.ts
2982
+ var drainKeyPages = async (fetchPage) => {
2983
+ const rows = [];
2984
+ let cursor2 = "";
2985
+ for (; ; ) {
2986
+ const page = await fetchPage(cursor2);
2987
+ rows.push(...page.data);
2988
+ const next = page.page.next_cursor;
2989
+ if (page.page.has_more !== true || next === null || next === void 0) {
2990
+ return rows;
2991
+ }
2992
+ cursor2 = next;
2993
+ }
2994
+ };
2995
+
2996
+ // src/management/list-member-projects/list-member-projects.ts
2997
+ var listMemberProjects = async (client, orgId, subject) => {
2998
+ const rows = await drainKeyPages(async (cursor2) => {
2999
+ const outcome = classifyManagementOutcome(
3000
+ await client.GET("/api/v1/projects", {
3001
+ params: {
3002
+ query: {
3003
+ member_user_id: subject,
3004
+ org_id: orgId,
3005
+ ...cursor2 === "" ? {} : { cursor: cursor2 }
3006
+ }
3007
+ }
3008
+ })
3009
+ );
3010
+ if (outcome.kind !== "ok") {
3011
+ throw new Error(`listing projects failed (${outcome.kind})`);
3012
+ }
3013
+ return outcome.data;
3014
+ });
3015
+ return rows.map((row) => ({
3016
+ id: row.id,
3017
+ name: row.name
3018
+ }));
3019
+ };
3020
+
3021
+ // src/management/list-org-keys/list-org-keys.ts
3022
+ var listOrgKeys = async (client) => {
3023
+ const now = /* @__PURE__ */ new Date();
3024
+ const rows = await drainKeyPages(async (cursor2) => {
3025
+ const outcome = classifyManagementOutcome(
3026
+ await client.GET("/api/v1/api-keys", {
3027
+ params: { query: cursor2 === "" ? {} : { cursor: cursor2 } }
3028
+ })
3029
+ );
3030
+ if (outcome.kind !== "ok") {
3031
+ throw new Error(`listing keys failed (${outcome.kind})`);
3032
+ }
3033
+ return outcome.data;
3034
+ });
3035
+ return rows.filter((row) => isUsableKey(row, now)).map((row) => ({
3036
+ id: row.id,
3037
+ name: row.name,
3038
+ keyPrefix: row.key_prefix,
3039
+ expiresAt: row.expires_at
3040
+ }));
3041
+ };
3042
+
3043
+ // src/management/list-orgs/list-orgs.ts
3044
+ var listOrgs = async (client) => {
3045
+ const outcome = classifyManagementOutcome(
3046
+ await client.GET("/api/v1/orgs", {})
3047
+ );
3048
+ if (outcome.kind !== "ok") {
3049
+ throw new Error(`listing organisations failed (${outcome.kind})`);
3050
+ }
3051
+ const data = outcome.data["data"];
3052
+ const rows = Array.isArray(data) ? data : [];
3053
+ return rows.map((row) => ({
3054
+ id: row.id,
3055
+ name: row.name
3056
+ }));
3057
+ };
3058
+
3059
+ // src/management/management-base-url/management-base-url.ts
3060
+ var DEFAULT_BASE_URL2 = "https://mapi.route33.ai";
3061
+ var API_PREFIX_PATTERN = /\/api\/v1\/?$/;
3062
+ var managementBaseUrl = (override) => {
3063
+ const trimmed = override?.trim();
3064
+ const base = trimmed !== void 0 && trimmed !== "" ? trimmed : DEFAULT_BASE_URL2;
3065
+ return base.replace(API_PREFIX_PATTERN, "");
3066
+ };
3067
+
3068
+ // src/management/management-subject/management-subject.ts
3069
+ var managementSubject = (accessToken) => {
3070
+ const segments = accessToken.split(".");
3071
+ const payload = segments[1];
3072
+ if (segments.length !== 3 || payload === void 0 || payload === "") {
3073
+ throw new Error("management token is not a decodable JWT");
3074
+ }
3075
+ const decoded = JSON.parse(
3076
+ Buffer.from(payload, "base64url").toString("utf8")
3077
+ );
3078
+ if (decoded === null || typeof decoded !== "object") {
3079
+ throw new Error("management token payload is not an object");
3080
+ }
3081
+ const sub = decoded["sub"];
3082
+ if (typeof sub !== "string" || sub === "") {
3083
+ throw new Error("management token carries no usable subject");
3084
+ }
3085
+ return sub;
3086
+ };
3087
+
3088
+ // src/management/regenerate-key-secret/regenerate-key-secret.ts
3089
+ var regenerateKeySecret = async (client, keyId) => {
3090
+ const outcome = classifyManagementOutcome(
3091
+ await client.POST("/api/v1/api-keys/{api_key_id}/secrets", {
3092
+ body: {},
3093
+ params: { path: { api_key_id: keyId } }
3094
+ })
3095
+ );
3096
+ if (outcome.kind !== "ok") {
3097
+ throw new Error(`rotating the key failed (${outcome.kind})`);
3098
+ }
3099
+ const key = outcome.data["key"];
3100
+ if (typeof key !== "string" || key === "") {
3101
+ throw new Error("rotating the key returned no key material");
3102
+ }
3103
+ return key;
3104
+ };
3105
+
3106
+ // src/management/resolve-key-ownership/resolve-key-ownership.ts
3107
+ var resolveKeyOwnership = (attribution, subject) => {
3108
+ if (subject === "") {
3109
+ throw new Error("management token carries no usable subject");
3110
+ }
3111
+ if (attribution.kind === "project") {
3112
+ return {
3113
+ ownerId: subject,
3114
+ ownerType: "user_project",
3115
+ projectId: attribution.projectId
3116
+ };
3117
+ }
3118
+ return { ownerId: subject, ownerType: "user_personal", projectId: null };
3119
+ };
3120
+
3121
+ // src/cli/log-save-result/log-save-result.ts
3122
+ var logSaveResult = (result, name, key) => {
3123
+ if (result === "saved") {
3124
+ const displayName = name || maskKey(key);
3125
+ log.success(
3126
+ `Key saved as "${displayName}" \u2014 future runs will offer it here.`
3127
+ );
3128
+ return;
3129
+ }
3130
+ if (result === "duplicate") {
3131
+ log.info("That key is already saved \u2014 using it for this setup.");
3132
+ return;
3133
+ }
3134
+ log.warn(
3135
+ "Could not write the key store \u2014 the wizard still works, the key just won't be remembered."
3136
+ );
3137
+ };
3138
+
3139
+ // src/cli/exit-cancelled/exit-cancelled.ts
3140
+ var exitCancelled = () => {
3141
+ cancel("Setup cancelled \u2014 nothing was written.");
3142
+ process.exit(0);
3143
+ };
3144
+
3145
+ // src/cli/unwrap-string/unwrap-string.ts
3146
+ var unwrapString = (value) => {
3147
+ if (isCancel(value)) exitCancelled();
3148
+ return value;
3149
+ };
3150
+
3151
+ // src/cli/pick-attribution/pick-attribution.ts
3152
+ var pickAttribution = async (projects) => {
3153
+ const chosen = unwrapString(
3154
+ await select({
3155
+ message: "What should the key be attributed to?",
3156
+ options: [
3157
+ {
3158
+ value: "__personal__",
3159
+ label: "Personal",
3160
+ hint: "a personal key owned by you"
3161
+ },
3162
+ ...projects.map((project) => ({
3163
+ value: project.id,
3164
+ label: `Project: ${project.name}`
3165
+ }))
3166
+ ],
3167
+ initialValue: "__personal__"
3168
+ })
3169
+ );
3170
+ if (chosen === "__personal__") return { kind: "personal" };
3171
+ return { kind: "project", projectId: chosen };
3172
+ };
3173
+
3174
+ // src/cli/unwrap-boolean/unwrap-boolean.ts
3175
+ var unwrapBoolean = (value) => {
3176
+ if (isCancel(value)) exitCancelled();
3177
+ return value;
3178
+ };
3179
+
3180
+ // src/cli/confirm-regenerate/confirm-regenerate.ts
3181
+ var confirmRegenerate = async (keyName) => unwrapBoolean(
3182
+ await confirm({
3183
+ message: `Generate a fresh secret for "${keyName}"? The current secret stops working immediately.`,
3184
+ initialValue: false
3185
+ })
3186
+ );
3187
+
3188
+ // src/cli/offer-signin-keys/offer-signin-keys.ts
3189
+ var offerSigninKeys = async (keys) => {
3190
+ const chosen = unwrapString(
3191
+ await select({
3192
+ message: "Use one of your existing keys, or create a new one?",
3193
+ options: [
3194
+ ...keys.map((key2) => ({
3195
+ value: key2.id,
3196
+ label: `${key2.name} ${key2.keyPrefix}\u2026`,
3197
+ hint: `expires ${key2.expiresAt.slice(0, 10)} \u2014 rotating gives you a fresh secret`
3198
+ })),
3199
+ {
3200
+ value: "__create__",
3201
+ label: "Create a new key",
3202
+ hint: "minted via the management API, shown once"
3203
+ },
3204
+ {
3205
+ value: "__back__",
3206
+ label: "Back",
3207
+ hint: "other key sources"
3208
+ }
3209
+ ],
3210
+ initialValue: keys[0]?.id ?? "__create__"
3211
+ })
3212
+ );
3213
+ if (chosen === "__create__") return { choice: "create" };
3214
+ if (chosen === "__back__") return { choice: "back" };
3215
+ const key = keys.find((candidate) => candidate.id === chosen);
3216
+ return key === void 0 ? { choice: "back" } : { choice: "key", key };
3217
+ };
3218
+
3219
+ // src/cli/prompt-key-name/prompt-key-name.ts
3220
+ var promptKeyName = async (options) => {
3221
+ const name = unwrapString(
3222
+ await text({
3223
+ message: options.required ? "Name this key (e.g. claude-setup, work-laptop)" : "Give this key a local name (e.g. personal, work-org)",
3224
+ placeholder: options.required ? "claude-setup" : "personal",
3225
+ validate: (input) => {
3226
+ const trimmed = (input ?? "").trim();
3227
+ if (options.required && trimmed === "") return "A name is required.";
3228
+ if (trimmed.length > 40) return "Keep it under 40 characters.";
3229
+ }
3230
+ })
3231
+ );
3232
+ return name.trim();
3233
+ };
3234
+
3235
+ // src/cli/signin-key-flow/obtain-signin-key/obtain-signin-key.ts
3236
+ var obtainSigninKey = async (client, attribution, subject) => {
3237
+ const keys = await listOrgKeys(client);
3238
+ const offer = await offerSigninKeys(keys);
3239
+ if (offer.choice === "back") return null;
3240
+ if (offer.choice === "key") {
3241
+ const confirmed = await confirmRegenerate(offer.key.name);
3242
+ if (!confirmed) return null;
3243
+ const material2 = await regenerateKeySecret(client, offer.key.id);
3244
+ return { key: material2, name: offer.key.name };
3245
+ }
3246
+ const name = await promptKeyName({ required: true });
3247
+ const material = await createOrgKey(client, {
3248
+ name,
3249
+ expiresAt: defaultKeyExpiry(),
3250
+ ...resolveKeyOwnership(attribution, subject)
3251
+ });
3252
+ return { key: material, name };
3253
+ };
3254
+
3255
+ // src/cli/pick-org/pick-org.ts
3256
+ var pickOrg = async (orgs) => {
3257
+ const chosen = unwrapString(
3258
+ await select({
3259
+ message: "Which organisation should the key live in?",
3260
+ options: [
3261
+ ...orgs.map((org) => ({
3262
+ value: org.id,
3263
+ label: org.name
3264
+ })),
3265
+ {
3266
+ value: "__back__",
3267
+ label: "Back",
3268
+ hint: "other key sources"
3269
+ }
3270
+ ],
3271
+ initialValue: orgs[0]?.id
3272
+ })
3273
+ );
3274
+ if (chosen === "__back__") return null;
3275
+ return orgs.find((org) => org.id === chosen) ?? null;
3276
+ };
3277
+
3278
+ // src/cli/signin-key-flow/resolve-signin-org/resolve-signin-org.ts
3279
+ var resolveSigninOrg = async (client) => {
3280
+ const orgs = await listOrgs(client);
3281
+ if (orgs.length === 0) {
3282
+ log.warn(
3283
+ "No organisations visible to this login \u2014 pick another key source."
3284
+ );
3285
+ return null;
3286
+ }
3287
+ if (orgs.length === 1) {
3288
+ const org = orgs[0] ?? null;
3289
+ if (org !== null) log.step(`Organisation: ${org.name}`);
3290
+ return org;
3291
+ }
3292
+ return pickOrg(orgs);
3293
+ };
3294
+
3295
+ // src/cli/signin-key-flow/signin-key-flow.ts
3296
+ var signinKeyFlow = async (env) => {
3297
+ try {
3298
+ const { accessToken } = await wizardLogin({
3299
+ clientId: env.clientId ?? "",
3300
+ ...env.issuer === void 0 ? {} : { issuerOverride: env.issuer }
3301
+ });
3302
+ const subject = managementSubject(accessToken);
3303
+ const baseUrl = managementBaseUrl(env.apiBase);
3304
+ const org = await resolveSigninOrg(
3305
+ createWizardManagement(accessToken, baseUrl)
3306
+ );
3307
+ if (org === null) return null;
3308
+ const client = createWizardManagement(accessToken, baseUrl, org.id);
3309
+ let projects = [];
3310
+ try {
3311
+ projects = await listMemberProjects(client, org.id, subject);
3312
+ } catch {
3313
+ log.warn("Could not list projects \u2014 offering personal keys only.");
3314
+ }
3315
+ const attribution = await pickAttribution(projects);
3316
+ const obtained = await obtainSigninKey(client, attribution, subject);
3317
+ if (obtained === null) return null;
3318
+ logSaveResult(
3319
+ saveKey(obtained.key, obtained.name),
3320
+ obtained.name,
3321
+ obtained.key
3322
+ );
3323
+ return obtained.key;
3324
+ } catch (error) {
3325
+ log.warn(`Sign-in failed: ${error.message}.`);
3326
+ return null;
3327
+ }
3328
+ };
3329
+
3330
+ // src/cli/choose-api-key/choose-api-key.ts
3331
+ var chooseApiKey = async () => {
3332
+ for (; ; ) {
3333
+ const savedKeys = loadSavedKeys();
3334
+ const currentKey = currentClaudeKey();
3335
+ const options = savedKeys.map((entry) => ({
3336
+ value: entry.key,
3337
+ label: keyLabel(entry),
3338
+ hint: `saved ${entry.addedAt?.slice(0, 10) ?? "earlier"}`
3339
+ }));
3340
+ options.push({
3341
+ value: "__signin__",
3342
+ label: "Sign in with Route 33",
3343
+ hint: "browser login \u2014 list or create keys in your org"
3344
+ });
3345
+ if (currentKey !== null && !savedKeys.some((entry) => entry.key === currentKey)) {
3346
+ options.push({
3347
+ value: currentKey,
3348
+ label: `current Claude Code key ${maskKey(currentKey)}`,
3349
+ hint: "from ~/.claude/settings.json"
3350
+ });
3351
+ }
3352
+ if (options.length === 1) {
3353
+ const key2 = await signinKeyFlow(managementEnv());
3354
+ if (key2 !== null) return key2;
3355
+ log.error(
3356
+ "Sign-in is the only key source left and it failed \u2014 set ROUTE33_CLIENT_ID, or configure Claude Code with a Route 33 key first."
3357
+ );
3358
+ process.exit(1);
3359
+ }
3360
+ const chosen = unwrapString(
3361
+ await select({
3362
+ message: "Which Route 33 API key should Claude Code use?",
3363
+ options,
3364
+ initialValue: options[0]?.value
3365
+ })
3366
+ );
3367
+ if (chosen !== "__signin__") return chosen;
3368
+ const key = await signinKeyFlow(managementEnv());
3369
+ if (key !== null) return key;
3370
+ }
3371
+ };
3372
+
3373
+ // src/cli/choose-auth-mode/choose-auth-mode.ts
3374
+ var chooseAuthMode = async () => {
3375
+ const mode = unwrapString(
3376
+ await select({
3377
+ message: "How should Claude Code authenticate to Route 33?",
3378
+ options: [
3379
+ {
3380
+ value: "static",
3381
+ label: "Static key",
3382
+ hint: "ANTHROPIC_AUTH_TOKEN in settings \u2014 simple, no switching"
3383
+ },
3384
+ {
3385
+ value: "switchable",
3386
+ label: "Switchable key",
3387
+ hint: "apiKeyHelper + /r33-key \u2014 switch keys inside a running session (\u226430s)"
3388
+ }
3389
+ ],
3390
+ initialValue: "static"
3391
+ })
3392
+ );
3393
+ return mode === "switchable" ? "switchable" : "static";
3394
+ };
3395
+
3396
+ // src/cli/fetch-chat-models/fetch-chat-models.ts
3397
+ var fetchChatModels = async (key) => {
3398
+ const spinner2 = spinner();
3399
+ spinner2.start(
3400
+ `Fetching the Route 33 model catalog (${R33_BASE_URL}/v1/models)\u2026`
3401
+ );
3402
+ try {
3403
+ const entries = await listModels(key);
3404
+ const messagesCapable = entries.filter(
3405
+ (entry) => !entry.endpoints || entry.endpoints.includes("messages")
3406
+ ).map((entry) => entry.id);
3407
+ const models = filterChatModels(messagesCapable);
3408
+ spinner2.stop(
3409
+ `Loaded ${String(models.length)} Claude-Code-capable models from the Route 33 catalog`
3410
+ );
3411
+ return models;
3412
+ } catch (error) {
3413
+ spinner2.stop(`Catalog fetch failed: ${error.message}`);
3414
+ log.warn(
3415
+ "Falling back to the wizard's built-in model list \u2014 every pick is still verified against the live API."
3416
+ );
3417
+ return filterChatModels(FALLBACK_MODELS);
3418
+ }
3419
+ };
3420
+
3421
+ // src/cli/handle-verification/handle-verification.ts
3422
+ var handleVerification = async (model, verification) => {
3423
+ if (verification.outcome === "ok") {
3424
+ log.success(`${model} answers Claude Code requests on Route 33.`);
3425
+ return { model, needsThinkingOff: false };
3426
+ }
3427
+ if (verification.outcome === "needs-thinking-off") {
3428
+ log.warn(
3429
+ `${model} only accepts Claude Code requests with extended thinking disabled (MAX_THINKING_TOKENS=0).`
3430
+ );
3431
+ const useAnyway = unwrapBoolean(
3432
+ await confirm({
3433
+ message: `Use ${model} anyway? Thinking would be disabled for every model.`,
3434
+ initialValue: true
3435
+ })
3436
+ );
3437
+ return useAnyway ? { model, needsThinkingOff: true } : null;
3438
+ }
3439
+ const authHint = "status" in verification && (verification.status === 401 || verification.status === 403) ? " \u2014 your Route 33 key looks invalid" : "";
3440
+ const statusText = "status" in verification ? ` (HTTP ${String(verification.status)})` : "";
3441
+ log.warn(
3442
+ `Verification failed for ${model}${statusText}${authHint}: ${verification.detail || "no error detail"}`
3443
+ );
3444
+ const keepAnyway = unwrapBoolean(
3445
+ await confirm({
3446
+ message: `Write ${model} into this slot anyway?`,
3447
+ initialValue: false
3448
+ })
3449
+ );
3450
+ return keepAnyway ? { model, needsThinkingOff: false } : null;
3451
+ };
3452
+
3453
+ // src/cli/pick-slot-model/pick-slot-model.ts
3454
+ var pickSlotModel = async (slot, available, key) => {
3455
+ const recommended = slot.preferences.find((id) => available.includes(id)) ?? available[0];
3456
+ for (; ; ) {
3457
+ const model = unwrapString(
3458
+ await select({
3459
+ message: `${slot.label} \u2014 which Route 33 model?`,
3460
+ options: available.map((id) => ({
3461
+ value: id,
3462
+ label: id,
3463
+ hint: id === recommended ? "recommended" : void 0
3464
+ })),
3465
+ initialValue: recommended,
3466
+ maxItems: 12
3467
+ })
3468
+ );
3469
+ log.info(`Verifying ${model} with a Claude-Code-shaped request\u2026`);
3470
+ const verification = await verifyModel(key, model);
3471
+ const result = await handleVerification(model, verification);
3472
+ if (result !== null) return result;
3473
+ }
3474
+ };
3475
+
3476
+ // src/cli/choose-models/choose-models.ts
3477
+ var chooseModels = async (key) => {
3478
+ const models = await fetchChatModels(key);
3479
+ if (models.length === 0) {
3480
+ log.error("No usable models found in the Route 33 catalog.");
3481
+ exitCancelled();
3482
+ }
3483
+ const [firstSlot, ...optionalSlots] = MODEL_SLOTS;
3484
+ if (firstSlot === void 0) {
3485
+ log.error("No default model slot configured.");
3486
+ exitCancelled();
3487
+ throw new Error("unreachable");
3488
+ }
3489
+ const defaultSlot = firstSlot;
3490
+ const taken = /* @__PURE__ */ new Set();
3491
+ const picks = [];
3492
+ const defaultPick = await pickSlotModel(defaultSlot, models, key);
3493
+ taken.add(defaultPick.model);
3494
+ picks.push({ ...defaultSlot, ...defaultPick });
3495
+ while (picks.length < MODEL_SLOTS.length) {
3496
+ const remainingSlots = optionalSlots.filter(
3497
+ (slot2) => !picks.some((pick) => pick.envKey === slot2.envKey)
3498
+ );
3499
+ const available = models.filter((id) => !taken.has(id));
3500
+ const addMore = unwrapString(
3501
+ await select({
3502
+ message: "Add another model?",
3503
+ options: [
3504
+ ...remainingSlots.map((slot2) => ({
3505
+ value: slot2.envKey,
3506
+ label: `Add: ${slot2.label}`,
3507
+ hint: slot2.hint
3508
+ })),
3509
+ {
3510
+ value: "__done__",
3511
+ label: "Done \u2014 stick with the models above",
3512
+ hint: "1\u20135 models; slots you skip keep Claude Code's built-in behavior"
3513
+ }
3514
+ ]
3515
+ })
3516
+ );
3517
+ if (addMore === "__done__" || available.length === 0) break;
3518
+ const slot = optionalSlots.find(
3519
+ (candidate) => candidate.envKey === addMore
3520
+ );
3521
+ if (!slot) break;
3522
+ const picked = await pickSlotModel(slot, available, key);
3523
+ taken.add(picked.model);
3524
+ picks.push({ ...slot, ...picked });
3525
+ }
3526
+ return { picks, thinkingOff: picks.some((pick) => pick.needsThinkingOff) };
3527
+ };
3528
+
3529
+ // src/cli/install-r33-commands/install-r33-commands.ts
3530
+ import { realpathSync } from "node:fs";
3531
+
3532
+ // src/cli/install-key-commands/install-key-commands.ts
3533
+ import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync4 } from "node:fs";
3534
+ import { homedir as homedir6 } from "node:os";
3535
+ import { join as join6 } from "node:path";
3536
+
3537
+ // src/cli/helper-entry/helper-entry.ts
3538
+ var NEEDS_QUOTING = /[\s"']/;
3539
+ var helperEntry = (entry) => {
3540
+ if (!NEEDS_QUOTING.test(entry)) return entry;
3541
+ return `"${entry.replaceAll('"', '\\"')}"`;
3542
+ };
3543
+
3544
+ // src/cli/install-key-commands/install-key-commands.ts
3545
+ var installKeyCommands = (entry) => {
3546
+ const quoted = helperEntry(entry);
3547
+ const dir = join6(homedir6(), ".claude", "commands");
3548
+ mkdirSync4(dir, { recursive: true });
3549
+ writeFileSync4(
3550
+ join6(dir, "r33-key.md"),
3551
+ `---
3552
+ description: Switch the active Route 33 API key for Claude Code
3553
+ argument-hint: <key name or id>
3554
+ allowed-tools:
3555
+ - 'Bash(${quoted} key use:*)'
3556
+ - 'Bash(${quoted} key list:*)'
3557
+ ---
3558
+ Switch the active Route 33 API key to "$ARGUMENTS" for this user:
3559
+
3560
+ 1. Run \`${quoted} key use $ARGUMENTS\` with the bash tool.
3561
+ 2. Run \`${quoted} key list\` with the bash tool and tell the user which key is active now.
3562
+
3563
+ If a command fails, show its error output to the user. Otherwise answer in one short line.
3564
+ `
3565
+ );
3566
+ writeFileSync4(
3567
+ join6(dir, "r33-keys.md"),
3568
+ `---
3569
+ description: List the saved Route 33 API keys and show the active one
3570
+ allowed-tools:
3571
+ - 'Bash(${quoted} key list:*)'
3572
+ ---
3573
+ Run \`${quoted} key list\` with the bash tool and show the result to the user, naming the active key.
3574
+ `
3575
+ );
3576
+ };
3577
+
3578
+ // src/cli/install-model-commands/install-model-commands.ts
3579
+ import { mkdirSync as mkdirSync5, writeFileSync as writeFileSync5 } from "node:fs";
3580
+ import { homedir as homedir7 } from "node:os";
3581
+ import { join as join7 } from "node:path";
3582
+ var installModelCommands = (entry) => {
3583
+ const quoted = helperEntry(entry);
3584
+ const dir = join7(homedir7(), ".claude", "commands");
3585
+ mkdirSync5(dir, { recursive: true });
3586
+ writeFileSync5(
3587
+ join7(dir, "r33-model.md"),
3588
+ `---
3589
+ description: Switch the active model \u2014 pick from the live Route 33 catalog, or pass an id directly
3590
+ argument-hint: [model id, e.g. anthropic/claude-sonnet-5-5]
3591
+ allowed-tools:
3592
+ - 'Bash(${quoted} model list:*)'
3593
+ - 'Bash(${quoted} model check:*)'
3594
+ ---
3595
+ The user wants to switch the active model. Arguments: "$ARGUMENTS"
3596
+
3597
+ **When no model id was given** (arguments are empty):
3598
+
3599
+ 1. Run \`${quoted} model list\` with the bash tool.
3600
+ 2. Present the catalog to the user as a numbered list (compact, one id per line) and ask which one they want. Wait for their pick.
3601
+ 3. Continue with the picked id as the model id below.
3602
+
3603
+ **When a model id was given** (or once the user picked one):
3604
+
3605
+ 1. Run \`${quoted} model check <id>\` with the bash tool.
3606
+ 2. If it printed \`ok\` or \`needs-thinking-off\`, run the built-in \`/model <id>\` command to switch. If it printed anything else, show it to the user and stop.
3607
+ 3. If the check printed \`needs-thinking-off\`, warn the user: this model only works with extended thinking disabled (MAX_THINKING_TOKENS=0) \u2014 the wizard offers that wiring on the next run.
3608
+
3609
+ Answer in one short line: which model is now active, plus the thinking warning when it applies.
3610
+ `
3611
+ );
3612
+ writeFileSync5(
3613
+ join7(dir, "r33-models.md"),
3614
+ `---
3615
+ description: List the chat-capable models in the live Route 33 catalog
3616
+ allowed-tools:
3617
+ - 'Bash(${quoted} model list:*)'
3618
+ ---
3619
+ Run \`${quoted} model list\` with the bash tool and show the result to the user as a compact list, noting they can switch with /r33-model <id>.
3620
+ `
3621
+ );
3622
+ };
3623
+
3624
+ // src/cli/install-r33-commands/install-r33-commands.ts
3625
+ var installR33Commands = (switchable) => {
3626
+ installModelCommands(realpathSync(process.argv[1] ?? ""));
3627
+ if (switchable !== null) installKeyCommands(switchable.entryPath);
3628
+ };
3629
+
3630
+ // src/cli/prepare-switchable-auth/prepare-switchable-auth.ts
3631
+ import { realpathSync as realpathSync2 } from "node:fs";
3632
+
3633
+ // src/cli/ensure-stored-key/ensure-stored-key.ts
3634
+ var ensureStoredKey = async (key) => {
3635
+ const existing = loadSavedKeys().find((entry) => entry.key === key);
3636
+ if (existing !== void 0) return existing;
3637
+ const name = await promptKeyName({ required: false });
3638
+ const trimmed = name.trim();
3639
+ const result = saveKey(key, trimmed === "" ? void 0 : trimmed);
3640
+ if (result === "failed") {
3641
+ throw new Error(
3642
+ "Could not save the key to the local store \u2014 switchable auth needs a stored key."
3643
+ );
3644
+ }
3645
+ const stored = loadSavedKeys().find((entry) => entry.key === key);
3646
+ if (stored === void 0) {
3647
+ throw new Error("Could not find the saved key in the local store.");
3648
+ }
3649
+ return stored;
3650
+ };
3651
+
3652
+ // src/cli/prepare-switchable-auth/prepare-switchable-auth.ts
3653
+ var prepareSwitchableAuth = (mode, key) => {
3654
+ if (mode !== "switchable") return Promise.resolve(null);
3655
+ return ensureStoredKey(key).then((stored) => ({
3656
+ stored,
3657
+ entryPath: realpathSync2(process.argv[1] ?? "")
3658
+ }));
3659
+ };
3660
+
3661
+ // src/cli/auth-review-lines/auth-review-lines.ts
3662
+ var SWITCHABLE_LINES = [
3663
+ "Auth apiKeyHelper \u2192 r33-claude key current (switch with /r33-key)",
3664
+ "Switch latency \u226430s (CLAUDE_CODE_API_KEY_HELPER_TTL_MS=30000)"
3665
+ ];
3666
+ var STATIC_LINES = [
3667
+ "Auth ANTHROPIC_AUTH_TOKEN in settings (static)"
3668
+ ];
3669
+ var authReviewLines = (mode) => mode === "switchable" ? SWITCHABLE_LINES : STATIC_LINES;
3670
+
3671
+ // src/cli/review-note/review-note.ts
3672
+ var reviewNote = (args) => {
3673
+ const thinkingOffModels = args.picks.filter((pick) => pick.needsThinkingOff).map((pick) => pick.model);
3674
+ const pickedEnvKeys = new Set(args.picks.map((pick) => pick.envKey));
3675
+ const unsetSlots = MODEL_SLOTS.filter(
3676
+ (slot) => !pickedEnvKeys.has(slot.envKey)
3677
+ );
3678
+ const thinkingLabel = args.thinkingOff ? `OFF \u2014 required by: ${thinkingOffModels.join(", ")}` : "on (Claude Code default)";
3679
+ return [
3680
+ `Base URL ${R33_BASE_URL}`,
3681
+ `API key ${maskKey(args.key)}`,
3682
+ "",
3683
+ ...args.picks.map(
3684
+ (pick) => `${pick.label.padEnd(22)}${pick.model}${pick.needsThinkingOff ? " (needs thinking off)" : ""}`
3685
+ ),
3686
+ ...unsetSlots.length > 0 ? [
3687
+ "",
3688
+ `Not set ${unsetSlots.map((slot) => slot.label).join(", ")} \u2014 /model picks for those fall back to Claude Code's built-in ids, which Route 33 does not serve`
3689
+ ] : [],
3690
+ "",
3691
+ `Extended thinking ${thinkingLabel}`,
3692
+ "",
3693
+ ...authReviewLines(args.mode),
3694
+ `Settings file ${settingsPath()}`,
3695
+ "Backup settings.backup-<timestamp>.json",
3696
+ "",
3697
+ "All existing ANTHROPIC_* values (incl. ANTHROPIC_API_KEY) are replaced \u2014 only the models above are written.",
3698
+ "Switch between your models during a session with /model (Default \xB7 Opus \xB7 Sonnet \xB7 Haiku)."
3699
+ ];
3700
+ };
3701
+
3702
+ // src/cli/start-claude/start-claude.ts
3703
+ import { spawn as spawn2 } from "node:child_process";
3704
+ var startClaude = () => new Promise((resolve) => {
3705
+ const child = spawn2("claude", { stdio: "inherit" });
3706
+ child.on("error", (error) => {
3707
+ if (error.code === "ENOENT") {
3708
+ log.warn(
3709
+ "claude was not found on your PATH \u2014 install it with: npm install -g @anthropic-ai/claude-code"
3710
+ );
3711
+ resolve(127);
3712
+ } else {
3713
+ log.error(`Could not start claude: ${error.message}`);
3714
+ resolve(1);
3715
+ }
3716
+ });
3717
+ child.on("exit", (code) => {
3718
+ resolve(code ?? 0);
3719
+ });
3720
+ });
3721
+
3722
+ // src/cli/env-for-route33/env-for-route33.ts
3723
+ var envForRoute33 = (key, picks, thinkingOff) => {
3724
+ const env = {
3725
+ ANTHROPIC_BASE_URL: R33_BASE_URL,
3726
+ ANTHROPIC_AUTH_TOKEN: key
3727
+ };
3728
+ for (const pick of picks) env[pick.envKey] = pick.model;
3729
+ if (thinkingOff) env["MAX_THINKING_TOKENS"] = "0";
3730
+ return env;
3731
+ };
3732
+
3733
+ // src/cli/helper-command/helper-command.ts
3734
+ var helperCommand = (entry) => `${helperEntry(entry)} key current`;
3735
+
3736
+ // src/cli/write-wizard-settings/write-wizard-settings.ts
3737
+ var writeWizardSettings = (args) => {
3738
+ const env = envForRoute33(args.key, args.picks, args.thinkingOff);
3739
+ let helperOptions = {};
3740
+ if (args.mode === "switchable") {
3741
+ delete env["ANTHROPIC_AUTH_TOKEN"];
3742
+ env["CLAUDE_CODE_API_KEY_HELPER_TTL_MS"] = "30000";
3743
+ helperOptions = args.entryPath === null ? {} : { apiKeyHelper: helperCommand(args.entryPath) };
3744
+ }
3745
+ return writeRoute33Settings(env, helperOptions);
3746
+ };
3747
+
3748
+ // src/cli/wizard/wizard.ts
3749
+ var wizard = async () => {
3750
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
3751
+ console.error(
3752
+ "r33-claude is an interactive wizard \u2014 run it in a terminal."
3753
+ );
3754
+ process.exit(1);
3755
+ }
3756
+ intro("r33-claude");
3757
+ note(
3758
+ [
3759
+ "Welcome to Route 33 Claude CLI!",
3760
+ "",
3761
+ `This wizard points Claude Code at Route 33 inference (${R33_BASE_URL})`,
3762
+ "so every claude session runs on Route 33 models.",
3763
+ "",
3764
+ `It writes ANTHROPIC_* env vars to ${settingsPath()}`,
3765
+ "and backs up your previous settings first.",
3766
+ "",
3767
+ "You'll add up to 5 models for your sessions (at least 1;",
3768
+ "you can stop after any pick). Claude Code starts right after setup."
3769
+ ].join("\n"),
3770
+ "Route 33 Claude CLI"
3771
+ );
3772
+ const key = await chooseApiKey();
3773
+ const mode = await chooseAuthMode();
3774
+ const switchable = await prepareSwitchableAuth(mode, key);
3775
+ const { picks, thinkingOff } = await chooseModels(key);
3776
+ note(
3777
+ reviewNote({ key, picks, thinkingOff, mode }).join("\n"),
3778
+ "Route 33 x Claude Code \u2014 review"
3779
+ );
3780
+ const confirmed = unwrapBoolean(
3781
+ await confirm({
3782
+ message: "Write these settings to Claude Code?",
3783
+ initialValue: true
3784
+ })
3785
+ );
3786
+ if (!confirmed) exitCancelled();
3787
+ const { backup, broken } = writeWizardSettings({
3788
+ key,
3789
+ picks,
3790
+ thinkingOff,
3791
+ mode,
3792
+ entryPath: switchable === null ? null : switchable.entryPath
3793
+ });
3794
+ if (broken) {
3795
+ log.warn(
3796
+ "Your previous settings.json was not valid JSON \u2014 it was backed up and replaced."
3797
+ );
3798
+ }
3799
+ log.success(`Route 33 env vars written to ${settingsPath()}`);
3800
+ if (backup !== null) log.step(`Previous settings backed up: ${backup}`);
3801
+ installR33Commands(switchable);
3802
+ if (switchable !== null) {
3803
+ writeActiveKey(switchable.stored.name ?? switchable.stored.id);
3804
+ log.step(
3805
+ `Active key set to "${switchable.stored.name ?? switchable.stored.id}" \u2014 switch inside a session with /r33-key.`
3806
+ );
3807
+ }
3808
+ outro("Route 33 is ready \u2014 starting Claude Code\u2026");
3809
+ const exitCode = await startClaude();
3810
+ process.exit(exitCode);
3811
+ };
3812
+
3813
+ // src/cli/run-cli/run-cli.ts
3814
+ var CLI_USAGE = [
3815
+ "usage: r33-claude [key|model <subcommand>]",
3816
+ "",
3817
+ " (no arguments) run the setup wizard",
3818
+ " key current print the active key's material (the apiKeyHelper command)",
3819
+ " key list list the saved keys, marking the active one",
3820
+ " key use <name> switch the active key",
3821
+ " model list list the chat-capable models in the live catalog",
3822
+ " model check <id> verify a model answers Claude-Code-shaped requests"
3823
+ ].join("\n");
3824
+ var runCli = async (argv) => {
3825
+ if (argv.length === 0) {
3826
+ await wizard();
3827
+ return 0;
3828
+ }
3829
+ if (argv[0] === "key") {
3830
+ return runKeyCommand(keyCommand(argv.slice(1)));
3831
+ }
3832
+ if (argv[0] === "model") {
3833
+ return runModelCommand(modelCommand(argv.slice(1)));
3834
+ }
3835
+ console.error(CLI_USAGE);
3836
+ return 1;
3837
+ };
3838
+
3839
+ // src/cli/main/main.ts
3840
+ var main = async () => runCli(process.argv.slice(2));
3841
+ if (process.argv[1] !== void 0 && pathToFileURL(realpathSync3(process.argv[1])).href === import.meta.url) {
3842
+ main().then((code) => {
3843
+ process.exit(code);
3844
+ }).catch((error) => {
3845
+ console.error(`r33-claude: ${error.message}`);
3846
+ process.exit(1);
3847
+ });
3848
+ }
3849
+ export {
3850
+ main
3851
+ };