dsh-keys-manager 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1785 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res, err) => function __init() {
4
+ if (err) throw err[0];
5
+ try {
6
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
+ } catch (e) {
8
+ throw err = [e], e;
9
+ }
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+
16
+ // scripts/omp-oauth/omp-shim/bun-global.ts
17
+ import { createHash } from "node:crypto";
18
+ import { writeFile } from "node:fs/promises";
19
+ function toBytes(value) {
20
+ if (typeof value === "string") return new TextEncoder().encode(value);
21
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
22
+ return new Uint8Array(value);
23
+ }
24
+ function binaryLike(value) {
25
+ return typeof value === "string" ? value : toBytes(value);
26
+ }
27
+ function exactBuffer(bytes) {
28
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
29
+ }
30
+ var SHA256, CryptoHasher, Bun;
31
+ var init_bun_global = __esm({
32
+ "scripts/omp-oauth/omp-shim/bun-global.ts"() {
33
+ "use strict";
34
+ SHA256 = class {
35
+ #hash = createHash("sha256");
36
+ static hash(data, target) {
37
+ const digest = createHash("sha256").update(binaryLike(data)).digest();
38
+ if (target instanceof Uint8Array) {
39
+ target.set(digest.subarray(0, target.length));
40
+ return target;
41
+ }
42
+ if (typeof target === "string") return digest.toString(target);
43
+ return exactBuffer(digest);
44
+ }
45
+ update(data) {
46
+ this.#hash.update(binaryLike(data));
47
+ return this;
48
+ }
49
+ digest(encoding) {
50
+ if (encoding === void 0) return exactBuffer(this.#hash.digest());
51
+ return this.#hash.digest(encoding);
52
+ }
53
+ };
54
+ CryptoHasher = class {
55
+ #hash;
56
+ constructor(algorithm = "sha256") {
57
+ this.#hash = createHash(algorithm);
58
+ }
59
+ update(data) {
60
+ this.#hash.update(binaryLike(data));
61
+ return this;
62
+ }
63
+ digest(encoding) {
64
+ if (encoding === void 0) return exactBuffer(this.#hash.digest());
65
+ return this.#hash.digest(encoding);
66
+ }
67
+ };
68
+ Bun = {
69
+ env: process.env,
70
+ /** Resolve after `ms`; the Kilo device poll paces itself with this. */
71
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
72
+ /**
73
+ * Deterministic 64-bit hash. `simplify:` Bun uses wyhash; this chains
74
+ * SHA-256 into a `number` (Bun's return contract). The sign-in flows only
75
+ * read it through shared helpers that no flow branches on.
76
+ */
77
+ hash: (value) => {
78
+ const digest = createHash("sha256").update(binaryLike(value)).digest();
79
+ return digest.readUInt32BE(0);
80
+ },
81
+ SHA256,
82
+ CryptoHasher,
83
+ /** Write a file and report the byte count, like `Bun.write`. */
84
+ write: async (destination, data) => {
85
+ const bytes = toBytes(data);
86
+ await writeFile(destination, bytes);
87
+ return bytes.byteLength;
88
+ }
89
+ };
90
+ }
91
+ });
92
+
93
+ // scripts/omp-oauth/omp-shim/pi-utils.ts
94
+ var $env, logger;
95
+ var init_pi_utils = __esm({
96
+ "scripts/omp-oauth/omp-shim/pi-utils.ts"() {
97
+ init_bun_global();
98
+ $env = new Proxy(
99
+ {},
100
+ {
101
+ get: (_target, key) => process.env[key],
102
+ has: (_target, key) => key in process.env
103
+ }
104
+ );
105
+ logger = {
106
+ debug: console.debug,
107
+ info: console.info,
108
+ warn: console.warn,
109
+ error: console.error
110
+ };
111
+ }
112
+ });
113
+
114
+ // node_modules/@oh-my-pi/pi-ai/src/error/aws.ts
115
+ var init_aws = __esm({
116
+ "node_modules/@oh-my-pi/pi-ai/src/error/aws.ts"() {
117
+ init_bun_global();
118
+ }
119
+ });
120
+
121
+ // node_modules/@oh-my-pi/pi-ai/src/error/network-cause.ts
122
+ var init_network_cause = __esm({
123
+ "node_modules/@oh-my-pi/pi-ai/src/error/network-cause.ts"() {
124
+ init_bun_global();
125
+ }
126
+ });
127
+
128
+ // node_modules/@oh-my-pi/pi-ai/src/error/classes.ts
129
+ var ProviderHttpError, MAX_ANTHROPIC_ERROR_BODY_BYTES;
130
+ var init_classes = __esm({
131
+ "node_modules/@oh-my-pi/pi-ai/src/error/classes.ts"() {
132
+ init_bun_global();
133
+ init_abort();
134
+ init_network_cause();
135
+ ProviderHttpError = class extends Error {
136
+ status;
137
+ headers;
138
+ code;
139
+ constructor(message, status2, options) {
140
+ super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
141
+ this.name = "ProviderHttpError";
142
+ this.status = status2;
143
+ this.headers = options?.headers;
144
+ this.code = options?.code;
145
+ }
146
+ };
147
+ MAX_ANTHROPIC_ERROR_BODY_BYTES = 64 * 1024;
148
+ }
149
+ });
150
+
151
+ // node_modules/@oh-my-pi/pi-ai/src/error/rate-limit.ts
152
+ var QUOTA_EXHAUSTED_BACKOFF_MS, RATE_LIMIT_EXCEEDED_BACKOFF_MS, CONCURRENT_LIMIT_BACKOFF_MS, MODEL_CAPACITY_BASE_MS, MODEL_CAPACITY_JITTER_MS, SERVER_ERROR_BACKOFF_MS, LONG_RATE_LIMIT_DELAY_MS;
153
+ var init_rate_limit = __esm({
154
+ "node_modules/@oh-my-pi/pi-ai/src/error/rate-limit.ts"() {
155
+ init_bun_global();
156
+ init_pi_utils();
157
+ QUOTA_EXHAUSTED_BACKOFF_MS = 30 * 60 * 1e3;
158
+ RATE_LIMIT_EXCEEDED_BACKOFF_MS = 30 * 1e3;
159
+ CONCURRENT_LIMIT_BACKOFF_MS = 5 * 1e3;
160
+ MODEL_CAPACITY_BASE_MS = 45 * 1e3;
161
+ MODEL_CAPACITY_JITTER_MS = 30 * 1e3;
162
+ SERVER_ERROR_BACKOFF_MS = 20 * 1e3;
163
+ LONG_RATE_LIMIT_DELAY_MS = 5 * 60 * 1e3;
164
+ }
165
+ });
166
+
167
+ // node_modules/@oh-my-pi/pi-ai/src/error/flags.ts
168
+ function create(...flags) {
169
+ let bits = 0;
170
+ for (const f of flags) bits |= f;
171
+ return bits | Flag.Class;
172
+ }
173
+ function attach(error, id) {
174
+ Object.defineProperty(error, "errorId", { value: id, enumerable: false, configurable: true });
175
+ return error;
176
+ }
177
+ var Flag, KIND_MASK, RETRIABLE_KINDS, CONTEXT_OVERFLOW_EVIDENCE_PATTERNS, GENERIC_LIMIT_OVERFLOW_PATTERN, OVERFLOW_PATTERNS, ERROR_KIND_LABELS;
178
+ var init_flags = __esm({
179
+ "node_modules/@oh-my-pi/pi-ai/src/error/flags.ts"() {
180
+ init_bun_global();
181
+ init_pi_utils();
182
+ init_aws();
183
+ init_classes();
184
+ init_rate_limit();
185
+ Flag = {
186
+ Class: 4096,
187
+ ThinkingLoop: 65536,
188
+ Transient: 131072,
189
+ Timeout: 262144,
190
+ UsageLimit: 524288,
191
+ StaleResponsesItem: 1048576,
192
+ MalformedFunctionCall: 2097152,
193
+ ProviderFinishError: 4194304,
194
+ EmptyResponse: 8192,
195
+ ContentBlocked: 32768,
196
+ /** Account-scoped provider policy denial that may succeed with another credential. */
197
+ AccountPolicy: 16384,
198
+ ContextOverflow: 8388608,
199
+ AuthFailed: 16777216,
200
+ SilentAbort: 33554432,
201
+ UserInterrupt: 67108864,
202
+ Abort: 134217728,
203
+ /** Strict-tool rejection (400): grammar too large, schema too complex, or structured outputs unsupported by the model/endpoint. */
204
+ Grammar: 268435456,
205
+ /** Anthropic model/account does not support fast mode / the `speed` parameter. */
206
+ FastModeUnsupported: 536870912,
207
+ /** OAuth refresh failed definitively — the stored grant is dead, re-login required. */
208
+ OAuthExpiry: 1073741824,
209
+ /**
210
+ * An Anthropic-compatible endpoint rejected the `cache_control` field with a
211
+ * 400, so prompt-cache breakpoints must be dropped for it.
212
+ *
213
+ * Every bit from {@link Flag.Class} up is already taken, so this claims a low
214
+ * bit instead. Those belong to the raw-status lane — an unclassified id is an
215
+ * HTTP status (100-599, see `statusFromId`) — and 0x800 is 2048, above every
216
+ * status value, so no raw status id can set it.
217
+ */
218
+ CacheControlUnsupported: 2048,
219
+ /** HTTP 413 byte/media rejection — token compaction cannot shrink bytes or media budgets (#9235). */
220
+ PayloadRejected: 2147483648
221
+ };
222
+ KIND_MASK = Flag.ThinkingLoop | Flag.Transient | Flag.Timeout | Flag.UsageLimit | Flag.StaleResponsesItem | Flag.MalformedFunctionCall | Flag.ProviderFinishError | Flag.EmptyResponse | Flag.ContentBlocked | Flag.AccountPolicy | Flag.ContextOverflow | Flag.AuthFailed | Flag.PayloadRejected | Flag.SilentAbort | Flag.UserInterrupt | Flag.Abort | Flag.Grammar | Flag.FastModeUnsupported | Flag.CacheControlUnsupported | Flag.OAuthExpiry;
223
+ RETRIABLE_KINDS = Flag.Transient | Flag.UsageLimit | Flag.ThinkingLoop | Flag.StaleResponsesItem | Flag.ProviderFinishError | Flag.EmptyResponse;
224
+ CONTEXT_OVERFLOW_EVIDENCE_PATTERNS = [
225
+ /prompt is too long/i,
226
+ // Anthropic
227
+ /input is too long for requested model/i,
228
+ // Amazon Bedrock
229
+ /exceeds the context window/i,
230
+ // OpenAI (Completions & Responses API)
231
+ /input token count.*exceeds the maximum/i,
232
+ // Google (Gemini)
233
+ /maximum prompt length is \d+/i,
234
+ // xAI (Grok)
235
+ /reduce the length of the messages/i,
236
+ // Groq
237
+ /maximum context length is \d+ tokens/i,
238
+ // OpenRouter (all backends)
239
+ /exceeds the available context size/i,
240
+ // llama.cpp server
241
+ /\bprompt\s*\(\s*\d+\s+tokens\s*\)\s*\+\s*max\s+tokens\s*\(\s*\d+\s*\)\s+exceeds\s+the\s+context\s*\(\s*\d+\s*\)/i,
242
+ // Strata server
243
+ /\bprompt\s*\(\s*\d+\s+tokens\s*\)\s+leaves\s+no\s+room\s+to\s+answer\s+in\s+the\s+context\s*\(\s*\d+\s*\)/i,
244
+ // Strata server
245
+ /requested tokens?.*exceed.*context (window|length|size)/i,
246
+ // llama.cpp / OpenAI-compatible local servers
247
+ /context (window|length|size).*(exceeded|overflow|too small)/i,
248
+ // Generic local server variants
249
+ /(prompt|input).*(too long|too large).*(context|n_ctx)/i,
250
+ // llama.cpp phrasing variants
251
+ /requested tokens?.*(exceeds?|greater than).*(n_ctx|context)/i,
252
+ // llama.cpp n_ctx variants
253
+ /greater than the context length/i,
254
+ // LM Studio
255
+ /context window exceeds limit/i,
256
+ // MiniMax
257
+ /exceeded model token limit/i,
258
+ // Kimi For Coding
259
+ /context[_ ]length[_ ]exceeded/i,
260
+ // Generic fallback
261
+ /too many tokens/i,
262
+ // Generic fallback
263
+ /token limit exceeded/i,
264
+ // Generic fallback
265
+ /request_too_large[^\n]*\btokens?\b/i,
266
+ /\btokens?\b[^\n]*request_too_large/i,
267
+ /model_context_window_exceeded/i,
268
+ // z.ai non-standard finish_reason surfaced as error text
269
+ /prompt filled the context window/i,
270
+ // Ollama OpenAI-compatible empty length completion
271
+ /exceeds the limit of \d+ tokens?\b/i,
272
+ /chat history exceeds the \d+-message limit/i
273
+ // Provider message-count cap
274
+ ];
275
+ GENERIC_LIMIT_OVERFLOW_PATTERN = /exceeds the limit of \d+/i;
276
+ OVERFLOW_PATTERNS = [...CONTEXT_OVERFLOW_EVIDENCE_PATTERNS, GENERIC_LIMIT_OVERFLOW_PATTERN];
277
+ ERROR_KIND_LABELS = [
278
+ [Flag.ThinkingLoop, "thinking-loop"],
279
+ [Flag.Transient, "transient"],
280
+ [Flag.Timeout, "timeout"],
281
+ [Flag.UsageLimit, "usage-limit"],
282
+ [Flag.StaleResponsesItem, "stale-responses-item"],
283
+ [Flag.MalformedFunctionCall, "malformed-function-call"],
284
+ [Flag.ProviderFinishError, "provider-finish-error"],
285
+ [Flag.EmptyResponse, "empty-response"],
286
+ [Flag.ContentBlocked, "content-blocked"],
287
+ [Flag.AccountPolicy, "account-policy"],
288
+ [Flag.ContextOverflow, "context-overflow"],
289
+ [Flag.PayloadRejected, "payload-rejected"],
290
+ [Flag.AuthFailed, "auth-failed"],
291
+ [Flag.SilentAbort, "silent-abort"],
292
+ [Flag.UserInterrupt, "user-interrupt"],
293
+ [Flag.Abort, "abort"]
294
+ ];
295
+ }
296
+ });
297
+
298
+ // node_modules/@oh-my-pi/pi-ai/src/error/abort.ts
299
+ var init_abort = __esm({
300
+ "node_modules/@oh-my-pi/pi-ai/src/error/abort.ts"() {
301
+ init_bun_global();
302
+ init_flags();
303
+ }
304
+ });
305
+
306
+ // node_modules/@oh-my-pi/pi-ai/src/error/auth.ts
307
+ var LoginCancelledError;
308
+ var init_auth = __esm({
309
+ "node_modules/@oh-my-pi/pi-ai/src/error/auth.ts"() {
310
+ init_bun_global();
311
+ init_flags();
312
+ LoginCancelledError = class extends Error {
313
+ constructor(message = "Login cancelled") {
314
+ super(message);
315
+ this.name = "LoginCancelledError";
316
+ attach(this, create(Flag.Abort));
317
+ }
318
+ };
319
+ }
320
+ });
321
+
322
+ // node_modules/@oh-my-pi/pi-ai/src/error/oauth.ts
323
+ var OAuthError;
324
+ var init_oauth = __esm({
325
+ "node_modules/@oh-my-pi/pi-ai/src/error/oauth.ts"() {
326
+ init_bun_global();
327
+ init_flags();
328
+ OAuthError = class extends Error {
329
+ kind;
330
+ provider;
331
+ status;
332
+ constructor(message, options = {}) {
333
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
334
+ this.name = "OAuthError";
335
+ this.kind = options.kind ?? "http";
336
+ this.provider = options.provider;
337
+ this.status = options.status;
338
+ attach(
339
+ this,
340
+ this.kind === "timeout" || this.kind === "polling" ? create(Flag.Transient) : create(Flag.AuthFailed)
341
+ );
342
+ }
343
+ };
344
+ }
345
+ });
346
+
347
+ // node_modules/@oh-my-pi/pi-ai/src/error/auth-classify.ts
348
+ var init_auth_classify = __esm({
349
+ "node_modules/@oh-my-pi/pi-ai/src/error/auth-classify.ts"() {
350
+ init_bun_global();
351
+ init_pi_utils();
352
+ init_flags();
353
+ init_oauth();
354
+ init_rate_limit();
355
+ }
356
+ });
357
+
358
+ // node_modules/@oh-my-pi/pi-ai/src/error/provider.ts
359
+ var init_provider = __esm({
360
+ "node_modules/@oh-my-pi/pi-ai/src/error/provider.ts"() {
361
+ init_bun_global();
362
+ init_classes();
363
+ init_flags();
364
+ }
365
+ });
366
+
367
+ // node_modules/@oh-my-pi/pi-ai/src/error/body-error.ts
368
+ var IN_BAND_FLAGS;
369
+ var init_body_error = __esm({
370
+ "node_modules/@oh-my-pi/pi-ai/src/error/body-error.ts"() {
371
+ init_bun_global();
372
+ init_classes();
373
+ init_flags();
374
+ init_rate_limit();
375
+ init_provider();
376
+ IN_BAND_FLAGS = create(Flag.Transient);
377
+ }
378
+ });
379
+
380
+ // scripts/omp-oauth/overrides/compat-policy.ts
381
+ var init_compat_policy = __esm({
382
+ "scripts/omp-oauth/overrides/compat-policy.ts"() {
383
+ init_bun_global();
384
+ }
385
+ });
386
+
387
+ // node_modules/@oh-my-pi/pi-ai/src/utils/retry-after.ts
388
+ var init_retry_after = __esm({
389
+ "node_modules/@oh-my-pi/pi-ai/src/utils/retry-after.ts"() {
390
+ init_bun_global();
391
+ init_compat_policy();
392
+ init_pi_utils();
393
+ }
394
+ });
395
+
396
+ // node_modules/@oh-my-pi/pi-ai/src/utils/http-inspector.ts
397
+ var HTTP_DUMP_MAX_AGE_MS, HTTP_DUMP_MAX_TOTAL_BYTES;
398
+ var init_http_inspector = __esm({
399
+ "node_modules/@oh-my-pi/pi-ai/src/utils/http-inspector.ts"() {
400
+ init_bun_global();
401
+ init_pi_utils();
402
+ init_flags();
403
+ init_retry_after();
404
+ HTTP_DUMP_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
405
+ HTTP_DUMP_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
406
+ }
407
+ });
408
+
409
+ // node_modules/@oh-my-pi/pi-ai/src/error/format.ts
410
+ var init_format = __esm({
411
+ "node_modules/@oh-my-pi/pi-ai/src/error/format.ts"() {
412
+ init_bun_global();
413
+ init_http_inspector();
414
+ init_retry_after();
415
+ init_flags();
416
+ }
417
+ });
418
+
419
+ // node_modules/@oh-my-pi/pi-ai/src/error/finalize.ts
420
+ var init_finalize = __esm({
421
+ "node_modules/@oh-my-pi/pi-ai/src/error/finalize.ts"() {
422
+ init_bun_global();
423
+ init_flags();
424
+ init_format();
425
+ }
426
+ });
427
+
428
+ // node_modules/@oh-my-pi/pi-ai/src/error/gateway.ts
429
+ var init_gateway = __esm({
430
+ "node_modules/@oh-my-pi/pi-ai/src/error/gateway.ts"() {
431
+ init_bun_global();
432
+ init_flags();
433
+ }
434
+ });
435
+
436
+ // node_modules/@oh-my-pi/pi-ai/src/error/retryable.ts
437
+ var init_retryable = __esm({
438
+ "node_modules/@oh-my-pi/pi-ai/src/error/retryable.ts"() {
439
+ init_bun_global();
440
+ init_pi_utils();
441
+ init_flags();
442
+ }
443
+ });
444
+
445
+ // node_modules/@oh-my-pi/pi-ai/src/error/validation.ts
446
+ var ConfigurationError;
447
+ var init_validation = __esm({
448
+ "node_modules/@oh-my-pi/pi-ai/src/error/validation.ts"() {
449
+ init_bun_global();
450
+ init_flags();
451
+ ConfigurationError = class extends Error {
452
+ constructor(message, options) {
453
+ super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
454
+ this.name = "ConfigurationError";
455
+ }
456
+ };
457
+ }
458
+ });
459
+
460
+ // node_modules/@oh-my-pi/pi-ai/src/error/index.ts
461
+ var init_error = __esm({
462
+ "node_modules/@oh-my-pi/pi-ai/src/error/index.ts"() {
463
+ init_bun_global();
464
+ init_abort();
465
+ init_auth();
466
+ init_auth_classify();
467
+ init_aws();
468
+ init_body_error();
469
+ init_classes();
470
+ init_finalize();
471
+ init_flags();
472
+ init_format();
473
+ init_gateway();
474
+ init_network_cause();
475
+ init_oauth();
476
+ init_provider();
477
+ init_rate_limit();
478
+ init_retryable();
479
+ init_validation();
480
+ }
481
+ });
482
+
483
+ // node_modules/@oh-my-pi/pi-ai/src/registry/oauth/zai.ts
484
+ var zai_exports = {};
485
+ __export(zai_exports, {
486
+ zaiMintKeyHook: () => zaiMintKeyHook
487
+ });
488
+ function isSuccessCode(code) {
489
+ if (code == null) return true;
490
+ if (typeof code === "number") return code === 0 || code === 200;
491
+ if (typeof code === "string") return code === "0" || code === "200";
492
+ return false;
493
+ }
494
+ function unwrapEnvelope(body, operation) {
495
+ if (body && typeof body === "object" && ("code" in body || "success" in body)) {
496
+ const envelope = body;
497
+ if (envelope.success === false || !isSuccessCode(envelope.code)) {
498
+ throw new OAuthError(`Z.ai ${operation} failed: ${envelope.msg ?? `code ${String(envelope.code)}`}`, {
499
+ kind: "token-exchange",
500
+ provider: "zai"
501
+ });
502
+ }
503
+ return "data" in envelope ? envelope.data : envelope;
504
+ }
505
+ return body;
506
+ }
507
+ async function getJson(url, headers, fetchImpl) {
508
+ const response = await fetchImpl(url, {
509
+ method: "GET",
510
+ headers,
511
+ signal: AbortSignal.timeout(3e4)
512
+ });
513
+ const responseBody = await response.text();
514
+ if (!response.ok) {
515
+ throw new ProviderHttpError(
516
+ `HTTP request failed. status=${response.status}; url=${url}; body=${responseBody}`,
517
+ response.status
518
+ );
519
+ }
520
+ return responseBody.length > 0 ? JSON.parse(responseBody) : void 0;
521
+ }
522
+ async function postJson(url, body, headers, fetchImpl) {
523
+ const response = await fetchImpl(url, {
524
+ method: "POST",
525
+ headers: { ...headers, "Content-Type": "application/json" },
526
+ body: JSON.stringify(body),
527
+ signal: AbortSignal.timeout(3e4)
528
+ });
529
+ const responseBody = await response.text();
530
+ if (!response.ok) {
531
+ throw new ProviderHttpError(
532
+ `HTTP request failed. status=${response.status}; url=${url}; body=${responseBody}`,
533
+ response.status
534
+ );
535
+ }
536
+ return responseBody.length > 0 ? JSON.parse(responseBody) : void 0;
537
+ }
538
+ function asKeyArray(value) {
539
+ if (Array.isArray(value)) return value;
540
+ if (value && typeof value === "object") {
541
+ const record = value;
542
+ for (const field of ["list", "keys", "apiKeys", "records"]) {
543
+ if (Array.isArray(record[field])) return record[field];
544
+ }
545
+ }
546
+ return [];
547
+ }
548
+ function trimmedString(value) {
549
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
550
+ }
551
+ async function businessLogin(oauthAccessToken, fetchImpl) {
552
+ const data = unwrapEnvelope(
553
+ await postJson(BUSINESS_LOGIN_URL, { token: oauthAccessToken }, {}, fetchImpl),
554
+ "business login"
555
+ );
556
+ const bizToken = trimmedString(data?.access_token) ?? trimmedString(data?.accessToken);
557
+ if (!bizToken) {
558
+ throw new OAuthError("Z.ai business login returned no access token", {
559
+ kind: "token-exchange",
560
+ provider: "zai"
561
+ });
562
+ }
563
+ return bizToken;
564
+ }
565
+ async function mintZaiApiKey(oauthAccessToken, fetchImpl) {
566
+ const bizToken = await businessLogin(oauthAccessToken, fetchImpl);
567
+ const auth = { Authorization: `Bearer ${bizToken}` };
568
+ const customer = unwrapEnvelope(
569
+ await getJson(`${BIZ_BASE}/api/biz/customer/getCustomerInfo`, auth, fetchImpl),
570
+ "customer lookup"
571
+ );
572
+ const orgs = Array.isArray(customer?.organizations) ? customer.organizations : [];
573
+ const org = orgs.find((o) => o?.isDefault) ?? orgs[0];
574
+ const projects = Array.isArray(org?.projects) ? org.projects : [];
575
+ const project = projects.find((p) => p?.isDefault) ?? projects[0];
576
+ const organizationId = trimmedString(org?.organizationId);
577
+ const projectId = trimmedString(project?.projectId);
578
+ if (!organizationId || !projectId) {
579
+ throw new OAuthError("Z.ai key provisioning failed: no organization/project on account", {
580
+ kind: "token-exchange",
581
+ provider: "zai"
582
+ });
583
+ }
584
+ const keysUrl = `${BIZ_BASE}/api/biz/v1/organization/${organizationId}/projects/${projectId}/api_keys`;
585
+ const existing = asKeyArray(unwrapEnvelope(await getJson(keysUrl, auth, fetchImpl), "api key list")).find(
586
+ (key) => key.name === KEY_NAME
587
+ );
588
+ const keyRecord = existing ?? unwrapEnvelope(await postJson(keysUrl, { name: KEY_NAME }, auth, fetchImpl), "api key create");
589
+ const apiKey = trimmedString(keyRecord?.apiKey);
590
+ if (!apiKey) {
591
+ throw new OAuthError("Z.ai key provisioning returned no apiKey", {
592
+ kind: "token-exchange",
593
+ provider: "zai"
594
+ });
595
+ }
596
+ const copied = unwrapEnvelope(
597
+ await getJson(`${keysUrl}/copy/${encodeURIComponent(apiKey)}`, auth, fetchImpl),
598
+ "api key copy"
599
+ );
600
+ const secretKey = trimmedString(copied?.secretKey);
601
+ if (!secretKey) {
602
+ throw new OAuthError("Z.ai key provisioning returned no secretKey", {
603
+ kind: "token-exchange",
604
+ provider: "zai"
605
+ });
606
+ }
607
+ return `${apiKey}.${secretKey}`;
608
+ }
609
+ var env, BIZ_BASE, BUSINESS_LOGIN_URL, KEY_NAME, zaiMintKeyHook;
610
+ var init_zai = __esm({
611
+ "node_modules/@oh-my-pi/pi-ai/src/registry/oauth/zai.ts"() {
612
+ init_bun_global();
613
+ init_error();
614
+ env = (key) => {
615
+ const value = process.env[key];
616
+ return typeof value === "string" && value.length > 0 ? value : void 0;
617
+ };
618
+ BIZ_BASE = env("ZAI_BIZ_BASE") ?? "https://api.z.ai";
619
+ BUSINESS_LOGIN_URL = env("ZAI_BUSINESS_LOGIN_URL") ?? "https://api.z.ai/api/auth/z/login";
620
+ KEY_NAME = "oh-my-pi";
621
+ zaiMintKeyHook = async (credentials, context) => ({
622
+ ...credentials,
623
+ access: await mintZaiApiKey(credentials.access, context.fetch)
624
+ });
625
+ }
626
+ });
627
+
628
+ // scripts/omp-oauth/entry.ts
629
+ init_bun_global();
630
+
631
+ // node_modules/@oh-my-pi/pi-ai/src/registry/oauth/kilo.ts
632
+ init_bun_global();
633
+ init_error();
634
+ var KILO_DEVICE_AUTH_BASE_URL = "https://api.kilo.ai/api/device-auth";
635
+ var POLL_INTERVAL_MS = 5e3;
636
+ var ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1e3;
637
+ async function loginKilo(callbacks) {
638
+ const fetchImpl = callbacks.fetch ?? fetch;
639
+ const initiateResponse = await fetchImpl(`${KILO_DEVICE_AUTH_BASE_URL}/codes`, {
640
+ method: "POST",
641
+ headers: { "Content-Type": "application/json" }
642
+ });
643
+ if (!initiateResponse.ok) {
644
+ if (initiateResponse.status === 429) {
645
+ throw new OAuthError("Too many pending authorization requests. Please try again later.", {
646
+ kind: "polling",
647
+ provider: "kilo",
648
+ status: initiateResponse.status
649
+ });
650
+ }
651
+ throw new OAuthError(`Failed to initiate device authorization: ${initiateResponse.status}`, {
652
+ kind: "device-auth",
653
+ provider: "kilo",
654
+ status: initiateResponse.status
655
+ });
656
+ }
657
+ const initiateData = await initiateResponse.json();
658
+ const userCode = initiateData.code;
659
+ const verificationUrl = initiateData.verificationUrl;
660
+ const expiresInSeconds = initiateData.expiresIn;
661
+ if (!userCode || !verificationUrl || typeof expiresInSeconds !== "number" || expiresInSeconds <= 0) {
662
+ throw new OAuthError("Kilo device authorization response missing required fields", {
663
+ kind: "validation",
664
+ provider: "kilo"
665
+ });
666
+ }
667
+ callbacks.onAuth?.({
668
+ url: verificationUrl,
669
+ instructions: `Enter code: ${userCode}`
670
+ });
671
+ const deadline = Date.now() + expiresInSeconds * 1e3;
672
+ while (Date.now() < deadline) {
673
+ if (callbacks.signal?.aborted) {
674
+ throw new LoginCancelledError();
675
+ }
676
+ const pollResponse = await fetchImpl(`${KILO_DEVICE_AUTH_BASE_URL}/codes/${encodeURIComponent(userCode)}`);
677
+ if (pollResponse.status === 202) {
678
+ await Bun.sleep(POLL_INTERVAL_MS);
679
+ continue;
680
+ }
681
+ if (pollResponse.status === 403) {
682
+ throw new OAuthError("Authorization was denied", { kind: "device-auth", provider: "kilo" });
683
+ }
684
+ if (pollResponse.status === 410) {
685
+ throw new OAuthError("Authorization code expired. Please try again.", {
686
+ kind: "device-auth",
687
+ provider: "kilo"
688
+ });
689
+ }
690
+ if (!pollResponse.ok) {
691
+ throw new OAuthError(`Failed to poll device authorization: ${pollResponse.status}`, {
692
+ kind: "polling",
693
+ provider: "kilo",
694
+ status: pollResponse.status
695
+ });
696
+ }
697
+ const pollData = await pollResponse.json();
698
+ if (pollData.status === "approved" && pollData.token) {
699
+ return {
700
+ refresh: "",
701
+ access: pollData.token,
702
+ expires: Date.now() + ONE_YEAR_MS
703
+ };
704
+ }
705
+ if (pollData.status === "denied") {
706
+ throw new OAuthError("Authorization was denied", { kind: "device-auth", provider: "kilo" });
707
+ }
708
+ if (pollData.status === "expired") {
709
+ throw new OAuthError("Authorization code expired. Please try again.", {
710
+ kind: "device-auth",
711
+ provider: "kilo"
712
+ });
713
+ }
714
+ await Bun.sleep(POLL_INTERVAL_MS);
715
+ }
716
+ throw new OAuthError("Authentication timed out. Please try again.", { kind: "timeout", provider: "kilo" });
717
+ }
718
+
719
+ // node_modules/@oh-my-pi/pi-ai/src/registry/engine/oauth-code.ts
720
+ init_bun_global();
721
+ init_error();
722
+
723
+ // scripts/omp-oauth/overrides/api-key-validation.ts
724
+ init_bun_global();
725
+ async function validateApiKeyAgainstModelsEndpoint() {
726
+ throw new Error("omp-oauth: api-key paste validation is not bundled (no sign-in rule declares pasteKey)");
727
+ }
728
+
729
+ // node_modules/@oh-my-pi/pi-ai/src/registry/oauth/callback-server.ts
730
+ init_bun_global();
731
+ init_pi_utils();
732
+ init_error();
733
+ import * as os from "node:os";
734
+
735
+ // node_modules/@oh-my-pi/pi-ai/src/registry/oauth/native-scheme-callback.ts
736
+ init_bun_global();
737
+
738
+ // scripts/omp-oauth/overrides/pi-natives.ts
739
+ init_bun_global();
740
+ var NativeOAuthCallback = class {
741
+ constructor(_options) {
742
+ throw new Error("omp-oauth: native URI-scheme callbacks are not available on this host");
743
+ }
744
+ };
745
+
746
+ // node_modules/@oh-my-pi/pi-ai/src/registry/oauth/native-scheme-callback.ts
747
+ async function createNativeSchemeCallbackReceiver(scheme, options = {}) {
748
+ options.signal?.throwIfAborted();
749
+ const receiver = new NativeOAuthCallback({ scheme });
750
+ const cancel = () => receiver.cancel();
751
+ const detach = () => options.signal?.removeEventListener("abort", cancel);
752
+ options.signal?.addEventListener("abort", cancel, { once: true });
753
+ try {
754
+ if (!await receiver.start()) {
755
+ await receiver.dispose();
756
+ detach();
757
+ return void 0;
758
+ }
759
+ options.signal?.throwIfAborted();
760
+ } catch (error) {
761
+ try {
762
+ await receiver.dispose();
763
+ } catch (cleanupError) {
764
+ throw new AggregateError([error, cleanupError], "Native OAuth setup and recovery both failed");
765
+ } finally {
766
+ detach();
767
+ }
768
+ throw error;
769
+ }
770
+ return {
771
+ async dispose() {
772
+ try {
773
+ await receiver.dispose();
774
+ } finally {
775
+ detach();
776
+ }
777
+ },
778
+ async waitForCallback(signal, timeoutMs) {
779
+ signal?.throwIfAborted();
780
+ signal?.addEventListener("abort", cancel, { once: true });
781
+ try {
782
+ return await receiver.waitForCallback(timeoutMs);
783
+ } finally {
784
+ signal?.removeEventListener("abort", cancel);
785
+ }
786
+ }
787
+ };
788
+ }
789
+
790
+ // node_modules/@oh-my-pi/pi-ai/src/registry/oauth/oauth.html
791
+ var oauth_default = '<!doctype html>\n<html lang="en">\n <head>\n <meta charset="UTF-8" />\n <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n <meta name="color-scheme" content="dark light" />\n <title>omp \xB7 authentication</title>\n <style>\n :root {\n --bg: #000;\n --card: #0b0b0d;\n --ink-1: #f4f4f5;\n --ink-2: #b4b4bb;\n --ink-3: #7a7a83;\n --line-1: rgb(255 255 255 / 0.07);\n --line-2: rgb(255 255 255 / 0.12);\n --top-lit: rgb(255 255 255 / 0.22);\n --accent-a: #22d3ee;\n --accent-b: #f472b6;\n --accent-gradient: linear-gradient(135deg, var(--accent-a), var(--accent-b));\n --ok: #4ade80;\n --ok-soft: rgb(74 222 128 / 0.12);\n --bad: #f87171;\n --bad-soft: rgb(248 113 113 / 0.12);\n --pending: #a1a1aa;\n --pending-soft: rgb(161 161 170 / 0.12);\n --glow-a: rgb(34 211 238 / 0.1);\n --glow-b: rgb(244 114 182 / 0.08);\n --shadow: 0 30px 60px -20px rgb(0 0 0 / 0.8);\n --btn-bg: #f4f4f5;\n --btn-fg: #000;\n --r-control: 8px;\n --r-panel: 16px;\n --sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n color-scheme: dark;\n }\n\n @media (prefers-color-scheme: light) {\n :root {\n --bg: #fafafa;\n --card: #fff;\n --ink-1: #111113;\n --ink-2: #4b4b52;\n --ink-3: #83838b;\n --line-1: rgb(0 0 0 / 0.08);\n --line-2: rgb(0 0 0 / 0.12);\n --top-lit: rgb(0 0 0 / 0.04);\n --accent-a: #0891b2;\n --accent-b: #db2777;\n --ok: #16a34a;\n --ok-soft: rgb(22 163 74 / 0.1);\n --bad: #dc2626;\n --bad-soft: rgb(220 38 38 / 0.1);\n --pending: #71717a;\n --pending-soft: rgb(113 113 122 / 0.1);\n --glow-a: rgb(8 145 178 / 0.08);\n --glow-b: rgb(219 39 119 / 0.06);\n --shadow: 0 20px 50px -24px rgb(0 0 0 / 0.18);\n --btn-bg: #111113;\n --btn-fg: #fff;\n color-scheme: light;\n }\n }\n\n * {\n box-sizing: border-box;\n }\n\n body {\n margin: 0;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 1.5rem;\n font-family: var(--sans);\n background: var(--bg);\n color: var(--ink-1);\n -webkit-font-smoothing: antialiased;\n overflow-x: clip;\n }\n\n /* ambient glow */\n .glow {\n position: fixed;\n inset: 0;\n pointer-events: none;\n background:\n radial-gradient(ellipse 50vw 40vh at 38% 30%, var(--glow-a), transparent 70%),\n radial-gradient(ellipse 50vw 40vh at 64% 64%, var(--glow-b), transparent 70%);\n }\n\n .container {\n position: relative;\n width: 100%;\n max-width: 400px;\n padding: 2rem 2rem 1.75rem;\n background: var(--card);\n border: 1px solid var(--line-1);\n border-radius: var(--r-panel);\n box-shadow: var(--shadow);\n overflow: hidden;\n animation: rise 0.5s cubic-bezier(0.16, 1, 0.3, 1) both;\n }\n /* top-lit hairline */\n .container::before {\n content: "";\n position: absolute;\n top: 0;\n left: 12%;\n right: 12%;\n height: 1px;\n background: linear-gradient(90deg, transparent, var(--top-lit), transparent);\n }\n @keyframes rise {\n from {\n opacity: 0;\n transform: translateY(8px);\n }\n }\n\n .brand {\n display: flex;\n align-items: center;\n gap: 0.6rem;\n margin-bottom: 1.75rem;\n }\n .omp-mark {\n flex: none;\n display: block;\n }\n .wordmark {\n font-size: 13px;\n font-weight: 600;\n letter-spacing: -0.01em;\n }\n .wordmark-sub {\n margin-left: auto;\n font-family: var(--mono);\n font-size: 12px;\n color: var(--ink-3);\n }\n\n .status {\n display: inline-flex;\n align-items: center;\n gap: 0.45rem;\n padding: 0.22rem 0.6rem 0.22rem 0.5rem;\n margin-bottom: 1rem;\n border-radius: 999px;\n font-size: 12px;\n font-weight: 500;\n color: var(--pending);\n background: var(--pending-soft);\n }\n .status-dot {\n width: 7px;\n height: 7px;\n border-radius: 50%;\n background: currentColor;\n }\n .status-word {\n display: none;\n }\n .container:not(.success):not(.error) .status-pending,\n .success .status-success,\n .error .status-error {\n display: inline;\n }\n .container:not(.success):not(.error) .status-dot {\n animation: pulse 1.4s ease-in-out infinite;\n }\n @keyframes pulse {\n 50% {\n opacity: 0.35;\n }\n }\n .success .status {\n color: var(--ok);\n background: var(--ok-soft);\n }\n .error .status {\n color: var(--bad);\n background: var(--bad-soft);\n }\n\n h1 {\n margin: 0 0 0.5rem;\n font-size: 1.35rem;\n font-weight: 600;\n letter-spacing: -0.02em;\n line-height: 1.25;\n text-wrap: balance;\n }\n p {\n margin: 0 0 1.5rem;\n font-size: 0.9rem;\n line-height: 1.6;\n color: var(--ink-2);\n }\n p:last-of-type:not(:has(+ .btn)) {\n margin-bottom: 0.25rem;\n }\n .error p {\n font-family: var(--mono);\n font-size: 0.8rem;\n padding: 0.6rem 0.75rem;\n border: 1px solid var(--line-1);\n border-radius: var(--r-control);\n overflow-wrap: anywhere;\n }\n\n .btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 100%;\n padding: 0.6rem 1rem;\n font: inherit;\n font-size: 0.875rem;\n font-weight: 500;\n color: var(--btn-fg);\n background: var(--btn-bg);\n border: none;\n border-radius: var(--r-control);\n cursor: pointer;\n transition: opacity 0.15s;\n }\n .btn:hover {\n opacity: 0.86;\n }\n .btn:focus-visible {\n outline: 2px solid var(--accent-a);\n outline-offset: 2px;\n }\n .error .btn {\n color: var(--ink-1);\n background: transparent;\n border: 1px solid var(--line-2);\n }\n\n /* auto-close progress */\n .timer {\n position: absolute;\n left: 0;\n bottom: 0;\n height: 2px;\n width: 100%;\n background: var(--accent-gradient);\n transform-origin: left;\n transform: scaleX(0);\n }\n .countdown .timer {\n animation: countdown 3s linear forwards;\n }\n @keyframes countdown {\n from {\n transform: scaleX(1);\n }\n to {\n transform: scaleX(0);\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .container,\n .countdown .timer,\n .status-dot {\n animation: none !important;\n }\n }\n </style>\n </head>\n <body>\n <span aria-hidden="true" class="glow"></span>\n <div id="app" class="container">\n <div class="brand">\n <svg class="omp-mark" viewBox="0 0 64 64" width="24" height="24" aria-hidden="true">\n <defs>\n <linearGradient id="omp-mark-grad" x1="0" y1="0" x2="1" y2="1">\n <stop offset="0" stop-color="oklch(0.7 0.24 340)" />\n <stop offset=".5" stop-color="oklch(0.62 0.21 295)" />\n <stop offset="1" stop-color="oklch(0.81 0.14 200)" />\n </linearGradient>\n </defs>\n <path fill="url(#omp-mark-grad)" d="M10 14h44v9H43v33h-9V23h-9v22h-9V23H10z" />\n </svg>\n <span class="wordmark">omp</span>\n <span class="wordmark-sub">oauth</span>\n </div>\n\n <div class="status" role="status">\n <span aria-hidden="true" class="status-dot"></span>\n <span class="status-word status-pending">Waiting</span>\n <span class="status-word status-success">Connected</span>\n <span class="status-word status-error">Failed</span>\n </div>\n\n <h1 id="title">Authentication</h1>\n <p id="message"></p>\n <button onclick="window.close()" class="btn">Close window</button>\n <span aria-hidden="true" class="timer"></span>\n </div>\n\n <script id="server-state" type="application/json">\n __OAUTH_STATE__\n </script>\n\n <script>\n let serverState;\n try {\n serverState = JSON.parse(document.getElementById("server-state").textContent);\n } catch {\n const params = new URLSearchParams(window.location.search);\n serverState = {\n ok: params.get("ok") === "1",\n error: params.get("error") || "Authentication failed",\n };\n }\n\n const app = document.getElementById("app");\n const title = document.getElementById("title");\n const message = document.getElementById("message");\n\n if (serverState.ok) {\n const closeButton = document.querySelector(".btn");\n app.classList.add("success", "countdown");\n title.textContent = "Authentication successful";\n message.textContent = "You have successfully logged in.";\n window.close();\n setTimeout(() => {\n app.classList.remove("countdown");\n closeButton.remove();\n message.innerHTML = "You have successfully logged in.<br>Please close this tab manually.";\n }, 300);\n } else {\n app.classList.add("error");\n title.textContent = "Authentication failed";\n message.textContent = serverState.error || "An error occurred";\n }\n </script>\n </body>\n</html>\n';
792
+
793
+ // node_modules/@oh-my-pi/pi-ai/src/registry/oauth/callback-server.ts
794
+ var DEFAULT_TIMEOUT = 3e5;
795
+ var DEFAULT_HOSTNAME = "localhost";
796
+ var CALLBACK_PATH = "/callback";
797
+ var IPV4_LOOPBACK = "127.0.0.1";
798
+ var IPV6_LOOPBACK = "::1";
799
+ var IPV6_COMPANION_ATTEMPTS = 4;
800
+ var LAUNCH_PATH = "/launch";
801
+ function isAddressInUse(error) {
802
+ const code = error?.code;
803
+ if (typeof code === "string") return code === "EADDRINUSE";
804
+ return error instanceof Error && /EADDRINUSE|in use/i.test(error.message);
805
+ }
806
+ function serializeCallbackState(state) {
807
+ return JSON.stringify(state).replaceAll("<", "\\u003c");
808
+ }
809
+ function ipv6LoopbackAvailable() {
810
+ const interfaces = os.networkInterfaces();
811
+ for (const name in interfaces) {
812
+ const addresses = interfaces[name];
813
+ if (!addresses) continue;
814
+ for (const address of addresses) {
815
+ if (address.internal && address.family === "IPv6") return true;
816
+ }
817
+ }
818
+ return false;
819
+ }
820
+ function parseNativeCallback(input, redirectUri, expectedState) {
821
+ let callback;
822
+ let expected;
823
+ try {
824
+ callback = new URL(input);
825
+ expected = new URL(redirectUri);
826
+ } catch {
827
+ throw new OAuthError("OAuth application callback was not a valid URL", { kind: "device-auth" });
828
+ }
829
+ if (callback.protocol !== expected.protocol || callback.host !== expected.host || callback.pathname !== expected.pathname) {
830
+ throw new OAuthError("OAuth application returned an unexpected callback target", {
831
+ kind: "device-auth"
832
+ });
833
+ }
834
+ const state = callback.searchParams.get("state") ?? "";
835
+ if (expectedState && state !== expectedState) {
836
+ throw new OAuthError("State mismatch - possible CSRF attack", { kind: "device-auth" });
837
+ }
838
+ const error = callback.searchParams.get("error");
839
+ if (error) {
840
+ const description = callback.searchParams.get("error_description") || error;
841
+ throw new OAuthError(`Authorization failed: ${description}`, { kind: "device-auth" });
842
+ }
843
+ const code = callback.searchParams.get("code") ?? callback.searchParams.get("authCode");
844
+ if (!code)
845
+ throw new OAuthError("OAuth application callback omitted the authorization code", {
846
+ kind: "device-auth"
847
+ });
848
+ return { code, state };
849
+ }
850
+ var OAuthCallbackFlow = class {
851
+ ctrl;
852
+ preferredPort;
853
+ callbackPath;
854
+ callbackHostname;
855
+ redirectUri;
856
+ allowPortFallback;
857
+ #manualInputOnly;
858
+ #nativeScheme;
859
+ #callbackResolve;
860
+ #callbackReject;
861
+ /**
862
+ * Authorization URL the `/launch` route currently redirects to. Set by
863
+ * {@link login} after {@link generateAuthUrl} and before {@link OAuthController.onAuth}
864
+ * fires, cleared when the server stops. `undefined` before the flow reaches
865
+ * that point and after it finishes, so `/launch` returns 503 rather than
866
+ * a stale URL.
867
+ */
868
+ #pendingAuthUrl;
869
+ constructor(ctrl, preferredPortOrOptions, callbackPath = CALLBACK_PATH) {
870
+ this.ctrl = ctrl;
871
+ if (typeof preferredPortOrOptions === "number") {
872
+ this.preferredPort = preferredPortOrOptions;
873
+ this.callbackPath = callbackPath;
874
+ this.callbackHostname = DEFAULT_HOSTNAME;
875
+ this.allowPortFallback = true;
876
+ this.#manualInputOnly = false;
877
+ this.#nativeScheme = false;
878
+ return;
879
+ }
880
+ this.preferredPort = preferredPortOrOptions.preferredPort;
881
+ this.callbackPath = preferredPortOrOptions.callbackPath ?? CALLBACK_PATH;
882
+ this.callbackHostname = preferredPortOrOptions.callbackHostname ?? DEFAULT_HOSTNAME;
883
+ this.redirectUri = preferredPortOrOptions.redirectUri;
884
+ this.allowPortFallback = preferredPortOrOptions.allowPortFallback ?? true;
885
+ this.#manualInputOnly = preferredPortOrOptions.manualInputOnly ?? false;
886
+ this.#nativeScheme = preferredPortOrOptions.nativeScheme ?? false;
887
+ }
888
+ /**
889
+ * Generate CSRF state token. Override if provider needs custom state generation.
890
+ */
891
+ generateState() {
892
+ const bytes = new Uint8Array(16);
893
+ crypto.getRandomValues(bytes);
894
+ return Array.from(bytes).map((value) => value.toString(16).padStart(2, "0")).join("");
895
+ }
896
+ #loginCancelledError() {
897
+ return new LoginCancelledError(`OAuth callback cancelled: ${this.ctrl.signal?.reason}`);
898
+ }
899
+ #throwIfCancelled() {
900
+ if (this.ctrl.signal?.aborted) throw this.#loginCancelledError();
901
+ }
902
+ /**
903
+ * Execute the OAuth login flow.
904
+ */
905
+ async login() {
906
+ const state = this.generateState();
907
+ this.#throwIfCancelled();
908
+ const { server, redirectUri, launchUrl } = this.#manualInputOnly ? { server: void 0, redirectUri: this.#buildRedirectUri(), launchUrl: void 0 } : await this.#startCallbackServer(state);
909
+ const receiverAbort = new AbortController();
910
+ let receiver;
911
+ let nativeCallback;
912
+ try {
913
+ this.#throwIfCancelled();
914
+ if (this.#nativeScheme) {
915
+ const redirect = new URL(redirectUri);
916
+ if (redirect.protocol !== "http:" && redirect.protocol !== "https:") {
917
+ try {
918
+ receiver = await createNativeSchemeCallbackReceiver(
919
+ redirect.protocol.slice(0, -1),
920
+ { signal: this.ctrl.signal }
921
+ );
922
+ } catch (error) {
923
+ this.#throwIfCancelled();
924
+ this.#reportNativeWarning(
925
+ "Native OAuth callback setup failed; paste the authorization code instead",
926
+ error
927
+ );
928
+ }
929
+ }
930
+ }
931
+ this.#throwIfCancelled();
932
+ if (receiver) {
933
+ nativeCallback = receiver.waitForCallback(receiverAbort.signal).then((input) => parseNativeCallback(input, redirectUri, state));
934
+ void nativeCallback.catch(() => void 0);
935
+ }
936
+ const { url: authUrl, instructions } = await this.generateAuthUrl(state, redirectUri);
937
+ this.#throwIfCancelled();
938
+ this.#pendingAuthUrl = authUrl;
939
+ this.ctrl.onAuth?.({ url: authUrl, launchUrl, instructions });
940
+ this.#throwIfCancelled();
941
+ this.ctrl.onProgress?.(
942
+ receiver || !this.#manualInputOnly ? "Waiting for browser authentication..." : "Waiting for pasted authorization code..."
943
+ );
944
+ this.#throwIfCancelled();
945
+ let callback;
946
+ try {
947
+ callback = await this.#waitForCallback(state, nativeCallback);
948
+ } catch (error) {
949
+ this.#throwIfCancelled();
950
+ throw error;
951
+ }
952
+ this.#throwIfCancelled();
953
+ receiverAbort.abort("OAuth callback received");
954
+ await nativeCallback?.catch(() => void 0);
955
+ this.ctrl.onProgress?.("Exchanging authorization code for tokens...");
956
+ this.#throwIfCancelled();
957
+ return await this.exchangeToken(callback.code, state, redirectUri);
958
+ } finally {
959
+ this.#pendingAuthUrl = void 0;
960
+ receiverAbort.abort("OAuth login finished");
961
+ await nativeCallback?.catch(() => void 0);
962
+ if (receiver) {
963
+ try {
964
+ await receiver.dispose();
965
+ } catch (error) {
966
+ this.#reportNativeWarning(
967
+ "Native OAuth callback cleanup failed; recovery information was retained",
968
+ error
969
+ );
970
+ }
971
+ }
972
+ server?.stop();
973
+ }
974
+ }
975
+ /**
976
+ * Surface native callback failures without allowing reporting hooks to
977
+ * replace the login result they are meant to describe.
978
+ */
979
+ #reportNativeWarning(message, error) {
980
+ const detail = error instanceof Error ? error.message : String(error);
981
+ const warning = `${message}: ${detail}`;
982
+ logger.warn(warning, { error });
983
+ try {
984
+ this.ctrl.onProgress?.(warning);
985
+ } catch (progressError) {
986
+ logger.warn("OAuth progress callback failed while reporting a native callback warning", {
987
+ error: progressError
988
+ });
989
+ }
990
+ }
991
+ #buildRedirectUri() {
992
+ return this.redirectUri ?? `http://${this.callbackHostname}:${this.preferredPort}${this.callbackPath}`;
993
+ }
994
+ /**
995
+ * Start callback server, trying preferred port first, falling back to random.
996
+ * `launchUrl` is `undefined` when the caller configured `callbackPath` to
997
+ * collide with {@link LAUNCH_PATH} — the callback handler resolves the real
998
+ * callback in that case, so advertising a self-redirecting URL would be
999
+ * incorrect.
1000
+ */
1001
+ async #startCallbackServer(expectedState) {
1002
+ try {
1003
+ const server = this.#createServer(this.preferredPort, expectedState);
1004
+ const actualPort = this.#resolveServerPort(server);
1005
+ const launchUrl = this.#launchUrlIfSafe(actualPort);
1006
+ if (this.redirectUri) {
1007
+ return { server, redirectUri: this.redirectUri, launchUrl };
1008
+ }
1009
+ const redirectUri = `http://${this.callbackHostname}:${actualPort}${this.callbackPath}`;
1010
+ return { server, redirectUri, launchUrl };
1011
+ } catch (cause) {
1012
+ if (this.redirectUri) {
1013
+ throw new ConfigurationError(
1014
+ `OAuth callback port ${this.preferredPort} is in use, but oauth.redirectUri (${this.redirectUri}) requires this exact port. Free port ${this.preferredPort} (e.g. stop the process bound to it) and retry, or change oauth.redirectUri to point at an available port.`,
1015
+ { cause }
1016
+ );
1017
+ }
1018
+ if (!this.allowPortFallback) {
1019
+ throw new ConfigurationError(
1020
+ `OAuth callback port ${this.preferredPort} is in use. The OAuth provider validates redirect URIs against its registered callback, so falling back to a random port would be rejected. Free port ${this.preferredPort} (e.g. stop the process bound to it) and retry, or set oauth.callbackPort/oauth.redirectUri to a port the provider has registered.`,
1021
+ { cause }
1022
+ );
1023
+ }
1024
+ const server = this.#createServer(0, expectedState);
1025
+ const actualPort = this.#resolveServerPort(server);
1026
+ const redirectUri = `http://${this.callbackHostname}:${actualPort}${this.callbackPath}`;
1027
+ const launchUrl = this.#launchUrlIfSafe(actualPort);
1028
+ this.ctrl.onProgress?.(`Preferred port ${this.preferredPort} unavailable, using port ${actualPort}`);
1029
+ return { server, redirectUri, launchUrl };
1030
+ }
1031
+ }
1032
+ /**
1033
+ * Read the numeric port a callback server bound to. `Bun.Server.port` is
1034
+ * declared `number | undefined` because Unix-socket servers have no port,
1035
+ * but every callback flow uses TCP; a missing port here indicates a
1036
+ * configuration error rather than a fallback case.
1037
+ */
1038
+ #resolveServerPort(server) {
1039
+ const port = server.port;
1040
+ if (typeof port !== "number") {
1041
+ throw new ConfigurationError(
1042
+ "OAuth callback server bound to a non-TCP endpoint; expected a numeric port. Check `oauth.callbackPort`/`oauth.redirectUri`."
1043
+ );
1044
+ }
1045
+ return port;
1046
+ }
1047
+ /**
1048
+ * Build the `/launch` URL served by the callback server bound to `port`, or
1049
+ * `undefined` when it must not be advertised:
1050
+ * - the configured `callbackPath` (or a `redirectUri` whose pathname
1051
+ * resolves to {@link LAUNCH_PATH}) would collide with the launch route;
1052
+ * - the flow's `redirectUri` never returns to this loopback server: fixed
1053
+ * non-loopback hosts, or custom schemes like GitLab Duo's `vscode://`
1054
+ * URI — which `new URL` parses without complaint, so a scheme/host check
1055
+ * is required, not just the parse failure path. Advertising a localhost
1056
+ * `/launch` target for such flows misrepresents the callback endpoint
1057
+ * and hands remote users a URL that resolves nowhere.
1058
+ * Kept short (~30 chars) so UIs can advertise it as a
1059
+ * viewport-truncation-safe copy target for the full authorization URL.
1060
+ */
1061
+ #launchUrlIfSafe(port) {
1062
+ if (this.callbackPath === LAUNCH_PATH) return void 0;
1063
+ if (this.redirectUri) {
1064
+ try {
1065
+ const parsed = new URL(this.redirectUri);
1066
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return void 0;
1067
+ if (parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1" && parsed.hostname !== "[::1]") {
1068
+ return void 0;
1069
+ }
1070
+ if (parsed.pathname === LAUNCH_PATH) return void 0;
1071
+ } catch {
1072
+ return void 0;
1073
+ }
1074
+ }
1075
+ return `http://${this.callbackHostname}:${port}${LAUNCH_PATH}`;
1076
+ }
1077
+ /**
1078
+ * Create the HTTP listener(s) for the OAuth callback.
1079
+ *
1080
+ * `localhost` is not a single endpoint: it resolves to both
1081
+ * {@link IPV4_LOOPBACK} and {@link IPV6_LOOPBACK}, and clients commonly try
1082
+ * `::1` first. Binding only the IPv4 literal hands the authorization code to
1083
+ * whatever holds the IPv6 loopback on the same port — a dev server on
1084
+ * `*:3000` is the common case — which answers from its own routes while this
1085
+ * flow waits out the full {@link DEFAULT_TIMEOUT}. Nothing detects it either:
1086
+ * a specific-address bind coexists with another process's wildcard bind, so
1087
+ * `Bun.serve` reports the port as free and the random-port fallback in
1088
+ * {@link #startCallbackServer} never runs.
1089
+ *
1090
+ * Binding both loopback literals fixes the delivery rather than dodging it:
1091
+ * the kernel routes a connection to the most specific matching bind, so our
1092
+ * `::1` listener receives `localhost` traffic that would otherwise reach a
1093
+ * process bound to the `::` wildcard. Both listeners answer the same routes,
1094
+ * so which family the client resolves stops mattering.
1095
+ *
1096
+ * A genuine collision — another process on exactly this loopback address and
1097
+ * port — still raises EADDRINUSE and reaches the caller's in-use policy. A
1098
+ * host that cannot bind `::1` at all (IPv6 disabled, address unavailable) is
1099
+ * not a collision: the IPv4 listener is the only reachable endpoint there, so
1100
+ * it serves alone.
1101
+ */
1102
+ #createServer(port, expectedState) {
1103
+ if (this.callbackHostname !== DEFAULT_HOSTNAME) {
1104
+ return this.#serve(this.callbackHostname, port, expectedState);
1105
+ }
1106
+ const dualStack = ipv6LoopbackAvailable();
1107
+ for (let attempt = 0; ; attempt++) {
1108
+ const primary = this.#serve(IPV4_LOOPBACK, port, expectedState);
1109
+ const boundPort = primary.port;
1110
+ if (typeof boundPort !== "number") return primary;
1111
+ if (!dualStack) return primary;
1112
+ let companion;
1113
+ try {
1114
+ companion = this.#serve(IPV6_LOOPBACK, boundPort, expectedState);
1115
+ } catch (cause) {
1116
+ if (!isAddressInUse(cause)) return primary;
1117
+ void primary.stop(true);
1118
+ if (port !== 0 || attempt >= IPV6_COMPANION_ATTEMPTS) throw cause;
1119
+ continue;
1120
+ }
1121
+ return {
1122
+ get port() {
1123
+ return primary.port;
1124
+ },
1125
+ stop: (closeActiveConnections) => {
1126
+ void companion.stop(closeActiveConnections);
1127
+ return primary.stop(closeActiveConnections);
1128
+ }
1129
+ };
1130
+ }
1131
+ }
1132
+ /** Bind one loopback listener serving the callback and launch routes. */
1133
+ #serve(hostname, port, expectedState) {
1134
+ return Bun.serve({
1135
+ hostname,
1136
+ port,
1137
+ reusePort: false,
1138
+ fetch: (req) => this.#handleCallback(req, expectedState)
1139
+ });
1140
+ }
1141
+ /**
1142
+ * Handle OAuth callback HTTP request. Two routes on the same loopback server:
1143
+ * - `callbackPath` (default `/callback`) — the provider redirect target.
1144
+ * - {@link LAUNCH_PATH} (`/launch`) — 302 to the pending authorization URL so
1145
+ * viewport-safe copy targets can survive TUI truncation.
1146
+ *
1147
+ * `callbackPath` wins any collision: an OMP config that pins the provider
1148
+ * redirect at `/launch` (via `oauth.callbackPath` or a loopback
1149
+ * `oauth.redirectUri`) must resolve the callback normally rather than
1150
+ * self-redirect. `#startCallbackServer` also suppresses `launchUrl` in that
1151
+ * case, so the launch route is never advertised when it would collide.
1152
+ */
1153
+ #handleCallback(req, expectedState) {
1154
+ const url = new URL(req.url);
1155
+ if (url.pathname !== this.callbackPath) {
1156
+ if (url.pathname === LAUNCH_PATH) {
1157
+ const pending = this.#pendingAuthUrl;
1158
+ if (!pending) {
1159
+ return new Response("OAuth launch URL is no longer active", { status: 503 });
1160
+ }
1161
+ return Response.redirect(pending, 302);
1162
+ }
1163
+ return new Response("Not Found", { status: 404 });
1164
+ }
1165
+ const code = url.searchParams.get("code");
1166
+ const state = url.searchParams.get("state") || "";
1167
+ const error = url.searchParams.get("error") || "";
1168
+ const errorDescription = url.searchParams.get("error_description") || error;
1169
+ let resultState;
1170
+ if (error) {
1171
+ resultState = { ok: false, error: `Authorization failed: ${errorDescription}` };
1172
+ } else if (!code) {
1173
+ resultState = { ok: false, error: "Missing authorization code" };
1174
+ } else if (expectedState && state !== expectedState) {
1175
+ resultState = { ok: false, error: "State mismatch - possible CSRF attack" };
1176
+ } else {
1177
+ resultState = { ok: true, code, state };
1178
+ }
1179
+ if (resultState.ok) {
1180
+ const resolve = this.#callbackResolve;
1181
+ queueMicrotask(() => {
1182
+ resolve?.({ code: resultState.code, state: resultState.state });
1183
+ });
1184
+ } else if (error && (!expectedState || state === expectedState)) {
1185
+ const reject = this.#callbackReject;
1186
+ const message = resultState.error ?? `Authorization failed: ${errorDescription}`;
1187
+ queueMicrotask(() => {
1188
+ reject?.(new OAuthError(message, { kind: "device-auth" }));
1189
+ });
1190
+ }
1191
+ return new Response(
1192
+ oauth_default.replaceAll("__OAUTH_STATE__", () => serializeCallbackState(resultState)),
1193
+ {
1194
+ status: resultState.ok ? 200 : 500,
1195
+ headers: { "Content-Type": "text/html" }
1196
+ }
1197
+ );
1198
+ }
1199
+ /**
1200
+ * Wait for OAuth callback or manual input (whichever comes first).
1201
+ */
1202
+ #waitForCallback(expectedState, nativeCallback) {
1203
+ const timeoutSignal = AbortSignal.timeout(DEFAULT_TIMEOUT);
1204
+ const settledSignal = new AbortController();
1205
+ const signals = this.ctrl.signal ? [this.ctrl.signal, timeoutSignal, settledSignal.signal] : [timeoutSignal, settledSignal.signal];
1206
+ const signal = AbortSignal.any(signals);
1207
+ if (signal.aborted) return Promise.reject(this.#loginCancelledError());
1208
+ const callback = Promise.withResolvers();
1209
+ this.#callbackResolve = callback.resolve;
1210
+ this.#callbackReject = callback.reject;
1211
+ signal.addEventListener(
1212
+ "abort",
1213
+ () => {
1214
+ this.#callbackResolve = void 0;
1215
+ this.#callbackReject = void 0;
1216
+ callback.reject(new LoginCancelledError(`OAuth callback cancelled: ${signal.reason}`));
1217
+ },
1218
+ { once: true }
1219
+ );
1220
+ const callbackPromise = callback.promise;
1221
+ const candidates = [callbackPromise];
1222
+ if (nativeCallback) candidates.push(nativeCallback);
1223
+ if (this.ctrl.onManualCodeInput) {
1224
+ const requestManualInput = this.ctrl.onManualCodeInput;
1225
+ const manualPromise = (async () => {
1226
+ while (true) {
1227
+ const result = await Promise.race([
1228
+ callbackPromise,
1229
+ requestManualInput(signal).then((input) => {
1230
+ const parsed = parseCallbackInput(input);
1231
+ if (!parsed.code) return null;
1232
+ if (expectedState && parsed.state && parsed.state !== expectedState) return null;
1233
+ return { code: parsed.code, state: parsed.state ?? "" };
1234
+ })
1235
+ ]);
1236
+ if (result) return result;
1237
+ }
1238
+ })();
1239
+ candidates.push(manualPromise);
1240
+ }
1241
+ return Promise.race(candidates).finally(() => {
1242
+ this.#callbackResolve = void 0;
1243
+ this.#callbackReject = void 0;
1244
+ settledSignal.abort("OAuth callback settled");
1245
+ });
1246
+ }
1247
+ };
1248
+ function parseCallbackInput(input) {
1249
+ const value = input.trim();
1250
+ if (!value) return {};
1251
+ try {
1252
+ const url = new URL(value);
1253
+ return {
1254
+ code: url.searchParams.get("code") ?? void 0,
1255
+ state: url.searchParams.get("state") ?? void 0
1256
+ };
1257
+ } catch {
1258
+ }
1259
+ if (value.includes("code=")) {
1260
+ const params = new URLSearchParams(value.replace(/^[?#]/, ""));
1261
+ return {
1262
+ code: params.get("code") ?? void 0,
1263
+ state: params.get("state") ?? void 0
1264
+ };
1265
+ }
1266
+ const [code, state] = value.split("#", 2);
1267
+ return { code, state };
1268
+ }
1269
+
1270
+ // node_modules/@oh-my-pi/pi-ai/src/registry/oauth/pkce.ts
1271
+ init_bun_global();
1272
+ async function generatePKCE() {
1273
+ const verifierBytes = new Uint8Array(96);
1274
+ crypto.getRandomValues(verifierBytes);
1275
+ const verifier = Buffer.from(verifierBytes).toString("base64url");
1276
+ const encoder = new TextEncoder();
1277
+ const data = encoder.encode(verifier);
1278
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
1279
+ const challenge = Buffer.from(hashBuffer).toString("base64url");
1280
+ return { verifier, challenge };
1281
+ }
1282
+
1283
+ // node_modules/@oh-my-pi/pi-ai/src/registry/engine/common.ts
1284
+ init_bun_global();
1285
+ init_pi_utils();
1286
+ init_error();
1287
+
1288
+ // scripts/omp-oauth/overrides/hooks.gen.ts
1289
+ init_bun_global();
1290
+ var HOOKS = {
1291
+ env: {},
1292
+ headers: {},
1293
+ value: {},
1294
+ login: {},
1295
+ refresh: {},
1296
+ afterExchange: {
1297
+ "zai-mint-key": () => Promise.resolve().then(() => (init_zai(), zai_exports)).then((module) => module.zaiMintKeyHook)
1298
+ }
1299
+ };
1300
+
1301
+ // node_modules/@oh-my-pi/pi-ai/src/registry/engine/common.ts
1302
+ var NEVER_EXPIRES = 864e13;
1303
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
1304
+ function missingHook(kind, name) {
1305
+ throw new ConfigurationError(`auth rules reference unknown ${kind} hook "${name}"`);
1306
+ }
1307
+ async function loadAfterExchangeHook(name) {
1308
+ return (HOOKS.afterExchange[name] ?? missingHook("after-exchange", name))();
1309
+ }
1310
+ async function loadValueHook(name) {
1311
+ return (HOOKS.value[name] ?? missingHook("value", name))();
1312
+ }
1313
+ async function resolveValue(value, signal) {
1314
+ for (const name of value.env ?? []) {
1315
+ const fromEnv = $env[name]?.trim();
1316
+ if (fromEnv) return fromEnv;
1317
+ }
1318
+ if (value.hook) return (await loadValueHook(value.hook))(signal);
1319
+ const literal = value.value ?? "";
1320
+ return value.encoding === "base64" ? atob(literal) : literal;
1321
+ }
1322
+ function template(text, vars) {
1323
+ return text.replace(/\{([a-z_]+)\}/g, (_, key) => vars[key] ?? "");
1324
+ }
1325
+ function templateMap(map, vars) {
1326
+ const out = {};
1327
+ for (const key in map) out[key] = template(map[key], vars);
1328
+ return out;
1329
+ }
1330
+ function jsonPath(body, path) {
1331
+ let current = body;
1332
+ for (const segment of path.split(".")) {
1333
+ if (current === null || typeof current !== "object") return void 0;
1334
+ current = current[segment];
1335
+ }
1336
+ return current;
1337
+ }
1338
+ function decodeJwtPayload(token) {
1339
+ const parts = token.split(".");
1340
+ if (parts.length !== 3 || !parts[1]) return null;
1341
+ try {
1342
+ const decoded = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
1343
+ return decoded !== null && typeof decoded === "object" ? decoded : null;
1344
+ } catch {
1345
+ return null;
1346
+ }
1347
+ }
1348
+ function jwtExpiryMs(token, skewMs) {
1349
+ const exp = decodeJwtPayload(token)?.exp;
1350
+ return typeof exp === "number" && Number.isFinite(exp) ? exp * 1e3 - skewMs : void 0;
1351
+ }
1352
+ function scalarString(value) {
1353
+ if (typeof value === "string") return value.length > 0 ? value : void 0;
1354
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
1355
+ return void 0;
1356
+ }
1357
+ function readField(field, body, claims) {
1358
+ if (!field) return void 0;
1359
+ if (field.path !== void 0) {
1360
+ const value = scalarString(jsonPath(body, field.path));
1361
+ if (value !== void 0) return value;
1362
+ }
1363
+ for (const claim of field.claim ?? []) {
1364
+ const value = scalarString(claims?.[claim]);
1365
+ if (value !== void 0) return value;
1366
+ }
1367
+ return field.literal;
1368
+ }
1369
+ function mapCredentials(map, body, provider, previous) {
1370
+ const accessNoClaims = readField(map.access, body, null);
1371
+ const claims = accessNoClaims ? decodeJwtPayload(accessNoClaims) : null;
1372
+ const access = accessNoClaims ?? readField(map.access, body, claims);
1373
+ if (!access) {
1374
+ const excerpt = typeof body === "string" ? body : JSON.stringify(body);
1375
+ throw new OAuthError(
1376
+ `${provider} token response missing access token: ${(excerpt ?? "").slice(0, 500)}`,
1377
+ { kind: "validation", provider }
1378
+ );
1379
+ }
1380
+ let expires;
1381
+ const expiry = map.expires;
1382
+ switch (expiry.mode) {
1383
+ case "never":
1384
+ expires = NEVER_EXPIRES;
1385
+ break;
1386
+ case "jwt":
1387
+ expires = jwtExpiryMs(access, expiry.skewMs) ?? Date.now() + (expiry.fallbackMs ?? 60 * 60 * 1e3);
1388
+ break;
1389
+ case "seconds": {
1390
+ const seconds = jsonPath(body, expiry.path);
1391
+ if (typeof seconds === "number" && Number.isFinite(seconds)) {
1392
+ const from = expiry.fromPath ? jsonPath(body, expiry.fromPath) : void 0;
1393
+ const base = typeof from === "number" && Number.isFinite(from) ? from * 1e3 : Date.now();
1394
+ expires = base + seconds * 1e3 - expiry.skewMs;
1395
+ break;
1396
+ }
1397
+ if (expiry.fallbackMs !== void 0) {
1398
+ expires = Date.now() + expiry.fallbackMs;
1399
+ break;
1400
+ }
1401
+ throw new OAuthError(`${provider} token response missing ${expiry.path}`, {
1402
+ kind: "validation",
1403
+ provider
1404
+ });
1405
+ }
1406
+ }
1407
+ const credentials = {
1408
+ access,
1409
+ refresh: readField(map.refresh, body, claims) ?? previous?.refresh ?? "",
1410
+ expires
1411
+ };
1412
+ const optional = ["email", "accountId", "orgId", "orgName", "projectId", "apiEndpoint", "enterpriseUrl"];
1413
+ for (const key of optional) {
1414
+ const value = readField(map[key], body, claims);
1415
+ if (value !== void 0) credentials[key] = value;
1416
+ }
1417
+ return credentials;
1418
+ }
1419
+ async function postTokenRequest(request, standardParams, vars, context, errorKind) {
1420
+ const url = template(await resolveValue(request.url, context.signal), vars);
1421
+ const params = {};
1422
+ if (request.standard) {
1423
+ for (const key in standardParams) {
1424
+ const value = standardParams[key];
1425
+ if (value !== void 0) params[key] = value;
1426
+ }
1427
+ }
1428
+ Object.assign(params, templateMap(request.params, vars));
1429
+ const headers = {
1430
+ ...context.headers,
1431
+ ...templateMap(request.headers, vars),
1432
+ "Content-Type": request.body === "json" ? "application/json" : "application/x-www-form-urlencoded"
1433
+ };
1434
+ const timeoutSignal = AbortSignal.timeout(request.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS);
1435
+ const signal = context.signal ? AbortSignal.any([context.signal, timeoutSignal]) : timeoutSignal;
1436
+ let response;
1437
+ try {
1438
+ response = await context.fetch(url, {
1439
+ method: "POST",
1440
+ headers,
1441
+ body: request.body === "json" ? JSON.stringify(params) : new URLSearchParams(params).toString(),
1442
+ signal
1443
+ });
1444
+ } catch (cause) {
1445
+ if (context.signal?.aborted) {
1446
+ throw new LoginCancelledError(`OAuth login cancelled: ${String(context.signal.reason)}`);
1447
+ }
1448
+ if (timeoutSignal.aborted) {
1449
+ throw new OAuthError(`Timed out waiting for ${url}`, { kind: "timeout", provider: context.provider });
1450
+ }
1451
+ throw new OAuthError(`${context.provider} request to ${url} failed: ${describeError(cause)}`, {
1452
+ kind: errorKind,
1453
+ provider: context.provider,
1454
+ cause
1455
+ });
1456
+ }
1457
+ const text = await response.text();
1458
+ let body = void 0;
1459
+ if (text.length > 0) {
1460
+ try {
1461
+ body = JSON.parse(text);
1462
+ } catch {
1463
+ body = void 0;
1464
+ }
1465
+ }
1466
+ if (!response.ok && errorKind !== "device-auth") {
1467
+ throw new OAuthError(
1468
+ `${context.provider} ${errorKind === "token-refresh" ? "token refresh" : "token exchange"} failed: ${response.status} ${text.slice(0, 500)}`,
1469
+ { kind: errorKind, provider: context.provider, status: response.status }
1470
+ );
1471
+ }
1472
+ return { body: body ?? text, response };
1473
+ }
1474
+ async function applyUserinfo(userinfo, credentials, context, vars = {}) {
1475
+ if (!userinfo) return credentials;
1476
+ try {
1477
+ const response = await context.fetch(template(userinfo.url, vars), {
1478
+ headers: { ...context.headers, Authorization: `Bearer ${credentials.access}` },
1479
+ signal: context.signal
1480
+ });
1481
+ if (!response.ok) return credentials;
1482
+ const body = await response.json();
1483
+ const email = userinfo.email ? scalarString(jsonPath(body, userinfo.email)) : void 0;
1484
+ const accountId = userinfo.accountId ? scalarString(jsonPath(body, userinfo.accountId)) : void 0;
1485
+ return {
1486
+ ...credentials,
1487
+ ...email !== void 0 ? { email } : {},
1488
+ ...accountId !== void 0 ? { accountId } : {}
1489
+ };
1490
+ } catch {
1491
+ if (context.signal?.aborted) throw new LoginCancelledError();
1492
+ return credentials;
1493
+ }
1494
+ }
1495
+ async function applyAfterExchange(hook, credentials, context) {
1496
+ if (!hook) return credentials;
1497
+ return (await loadAfterExchangeHook(hook))(credentials, context);
1498
+ }
1499
+ function describeError(error) {
1500
+ if (error instanceof Error)
1501
+ return error.cause ? `${error.message} (cause: ${describeError(error.cause)})` : error.message;
1502
+ return String(error);
1503
+ }
1504
+ function throwIfCancelled(signal) {
1505
+ if (signal?.aborted) throw new LoginCancelledError(`OAuth login cancelled: ${String(signal.reason)}`);
1506
+ }
1507
+
1508
+ // node_modules/@oh-my-pi/pi-ai/src/registry/engine/oauth-code.ts
1509
+ function isLoopbackHost(hostname) {
1510
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
1511
+ }
1512
+ async function resolveCallbackOptions(callback, provider, signal) {
1513
+ const base = {
1514
+ preferredPort: callback.port,
1515
+ callbackPath: callback.path,
1516
+ callbackHostname: callback.hostname,
1517
+ allowPortFallback: callback.portFallback,
1518
+ manualInputOnly: callback.manualOnly,
1519
+ nativeScheme: callback.nativeScheme
1520
+ };
1521
+ if (!callback.redirectUri) return base;
1522
+ const redirectUri = await resolveValue(callback.redirectUri, signal);
1523
+ if (!redirectUri) return base;
1524
+ if (redirectUri === callback.redirectUri.value) {
1525
+ return { ...base, redirectUri };
1526
+ }
1527
+ let parsed;
1528
+ try {
1529
+ parsed = new URL(redirectUri);
1530
+ } catch {
1531
+ throw new OAuthError(`Invalid redirect URI override: ${redirectUri}`, {
1532
+ kind: "configuration",
1533
+ provider
1534
+ });
1535
+ }
1536
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
1537
+ throw new OAuthError(`Redirect URI override must use http:// or https://, got: ${redirectUri}`, {
1538
+ kind: "configuration",
1539
+ provider
1540
+ });
1541
+ }
1542
+ const loopback = isLoopbackHost(parsed.hostname);
1543
+ if (loopback && parsed.protocol !== "http:") {
1544
+ throw new OAuthError(`Loopback redirect URI overrides must use http://, got: ${redirectUri}`, {
1545
+ kind: "configuration",
1546
+ provider
1547
+ });
1548
+ }
1549
+ const port = parsed.port ? Number.parseInt(parsed.port, 10) : parsed.protocol === "https:" ? 443 : 80;
1550
+ return {
1551
+ preferredPort: loopback ? port : 0,
1552
+ callbackPath: parsed.pathname || callback.path,
1553
+ callbackHostname: loopback ? parsed.hostname : callback.hostname,
1554
+ redirectUri,
1555
+ allowPortFallback: false,
1556
+ manualInputOnly: callback.manualOnly,
1557
+ nativeScheme: callback.nativeScheme
1558
+ };
1559
+ }
1560
+ var DeclarativeOAuthCodeFlow = class extends OAuthCallbackFlow {
1561
+ #rule;
1562
+ #provider;
1563
+ #label;
1564
+ #fetch;
1565
+ #verifier = "";
1566
+ #clientId;
1567
+ #clientSecret;
1568
+ #base;
1569
+ #auth;
1570
+ constructor(ctrl, rule, policy, options) {
1571
+ super(ctrl, options);
1572
+ this.#rule = rule;
1573
+ this.#provider = policy.id;
1574
+ this.#label = policy.name;
1575
+ this.#fetch = ctrl.fetch ?? fetch;
1576
+ }
1577
+ generateState() {
1578
+ switch (this.#rule.state) {
1579
+ case "none":
1580
+ return "";
1581
+ case "uuid":
1582
+ return crypto.randomUUID();
1583
+ default:
1584
+ return super.generateState();
1585
+ }
1586
+ }
1587
+ async generateAuthUrl(state, redirectUri) {
1588
+ const rule = this.#rule;
1589
+ const signal = this.ctrl.signal;
1590
+ this.#clientId = rule.clientId ? await resolveValue(rule.clientId, signal) : void 0;
1591
+ this.#clientSecret = rule.clientSecret ? await resolveValue(rule.clientSecret, signal) : void 0;
1592
+ this.#base = rule.baseUrl ? (await resolveValue(rule.baseUrl, signal)).replace(/\/+$/, "") : void 0;
1593
+ this.#auth = rule.authUrl ? (await resolveValue(rule.authUrl, signal)).replace(/\/+$/, "") : void 0;
1594
+ let challenge;
1595
+ if (rule.pkce) {
1596
+ const pkce = await generatePKCE();
1597
+ this.#verifier = pkce.verifier;
1598
+ challenge = pkce.challenge;
1599
+ }
1600
+ const scope = rule.scopes.length > 0 ? rule.scopes.join(rule.scopeSeparator) : void 0;
1601
+ const vars = {
1602
+ client_id: this.#clientId,
1603
+ redirect_uri: redirectUri,
1604
+ scope,
1605
+ state,
1606
+ code_challenge: challenge,
1607
+ base: this.#base,
1608
+ auth: this.#auth
1609
+ };
1610
+ const params = new URLSearchParams();
1611
+ if (rule.standardAuthorizeParams) {
1612
+ if (this.#clientId) params.set("client_id", this.#clientId);
1613
+ params.set("response_type", "code");
1614
+ params.set("redirect_uri", redirectUri);
1615
+ if (scope) params.set("scope", scope);
1616
+ if (challenge) {
1617
+ params.set("code_challenge", challenge);
1618
+ params.set("code_challenge_method", "S256");
1619
+ }
1620
+ if (state) params.set("state", state);
1621
+ }
1622
+ for (const key in rule.authorizeParams) params.set(key, template(rule.authorizeParams[key], vars));
1623
+ const authorizeUrl = template(await resolveValue(rule.authorizeUrl, signal), vars);
1624
+ return { url: `${authorizeUrl}?${params.toString()}`, instructions: rule.instructions };
1625
+ }
1626
+ async exchangeToken(code, state, redirectUri) {
1627
+ const rule = this.#rule;
1628
+ const signal = this.ctrl.signal;
1629
+ throwIfCancelled(signal);
1630
+ if (rule.pasteKey && code.startsWith(rule.pasteKey.prefix)) {
1631
+ await validateApiKeyAgainstModelsEndpoint({
1632
+ provider: this.#label,
1633
+ apiKey: code,
1634
+ modelsUrl: rule.pasteKey.validateUrl,
1635
+ signal,
1636
+ fetch: this.ctrl.fetch
1637
+ });
1638
+ return { access: code, refresh: "", expires: NEVER_EXPIRES };
1639
+ }
1640
+ let exchangeCode = code;
1641
+ let exchangeState = state;
1642
+ const fragment = code.indexOf("#");
1643
+ if (fragment >= 0) {
1644
+ exchangeCode = code.slice(0, fragment);
1645
+ exchangeState = code.slice(fragment + 1) || state;
1646
+ }
1647
+ const vars = {
1648
+ code: exchangeCode,
1649
+ state: exchangeState,
1650
+ redirect_uri: redirectUri,
1651
+ code_verifier: rule.pkce ? this.#verifier : void 0,
1652
+ client_id: this.#clientId,
1653
+ client_secret: this.#clientSecret,
1654
+ base: this.#base,
1655
+ auth: this.#auth
1656
+ };
1657
+ const context = { provider: this.#provider, fetch: this.#fetch, signal };
1658
+ const { body } = await postTokenRequest(
1659
+ rule.token,
1660
+ {
1661
+ grant_type: "authorization_code",
1662
+ client_id: this.#clientId,
1663
+ client_secret: this.#clientSecret,
1664
+ code: exchangeCode,
1665
+ redirect_uri: redirectUri,
1666
+ code_verifier: rule.pkce ? this.#verifier : void 0
1667
+ },
1668
+ vars,
1669
+ context,
1670
+ "token-exchange"
1671
+ );
1672
+ throwIfCancelled(signal);
1673
+ let credentials = mapCredentials(rule.credential, body, this.#provider);
1674
+ credentials = await applyUserinfo(rule.userinfo, credentials, context, vars);
1675
+ throwIfCancelled(signal);
1676
+ return applyAfterExchange(rule.afterExchange, credentials, {
1677
+ provider: this.#provider,
1678
+ phase: "login",
1679
+ raw: body,
1680
+ fetch: this.#fetch,
1681
+ signal,
1682
+ onProgress: this.ctrl.onProgress,
1683
+ onPrompt: this.ctrl.onPrompt
1684
+ });
1685
+ }
1686
+ };
1687
+ function createOAuthCodeLogin(rule, policy) {
1688
+ return async (ctrl) => {
1689
+ const options = await resolveCallbackOptions(rule.callback, policy.id, ctrl.signal);
1690
+ return new DeclarativeOAuthCodeFlow(ctrl, rule, policy, options).login();
1691
+ };
1692
+ }
1693
+
1694
+ // scripts/omp-oauth/omp-oauth-policy.ts
1695
+ init_bun_global();
1696
+ var ZAI_CODING_PLAN_POLICY = {
1697
+ "id": "zai-coding-plan",
1698
+ "apiKeyFormat": "bearer",
1699
+ "name": "Z.AI (GLM Coding Plan \xB7 Sign in)",
1700
+ "login": {
1701
+ "kind": "oauth-code",
1702
+ "scopes": [],
1703
+ "scopeSeparator": " ",
1704
+ "pkce": false,
1705
+ "state": "hex",
1706
+ "standardAuthorizeParams": true,
1707
+ "authorizeParams": {},
1708
+ "clientId": {
1709
+ "value": "client_P8X5CMWmlaRO9gyO-KSqtg",
1710
+ "env": [
1711
+ "ZAI_OAUTH_CLIENT_ID"
1712
+ ]
1713
+ },
1714
+ "authorizeUrl": {
1715
+ "value": "https://chat.z.ai/api/oauth/authorize",
1716
+ "env": [
1717
+ "ZAI_OAUTH_AUTHORIZE_URL"
1718
+ ]
1719
+ },
1720
+ "callback": {
1721
+ "port": 0,
1722
+ "path": "/callback",
1723
+ "hostname": "localhost",
1724
+ "portFallback": true,
1725
+ "manualOnly": true,
1726
+ "nativeScheme": false,
1727
+ "redirectUri": {
1728
+ "value": "zcode://zai-auth/callback",
1729
+ "env": [
1730
+ "ZAI_OAUTH_REDIRECT_URI"
1731
+ ]
1732
+ }
1733
+ },
1734
+ "instructions": "Complete Z.ai login in your browser. On supported local desktops, omp captures the zcode:// callback and restores its previous handler automatically. You can also paste the final redirect URL or authorization code when prompted.",
1735
+ "token": {
1736
+ "url": {
1737
+ "value": "https://zcode.z.ai/api/v1/oauth/token",
1738
+ "env": [
1739
+ "ZAI_OAUTH_TOKEN_URL"
1740
+ ]
1741
+ },
1742
+ "body": "json",
1743
+ "standard": false,
1744
+ "params": {
1745
+ "provider": "zai",
1746
+ "code": "{code}",
1747
+ "redirect_uri": "{redirect_uri}",
1748
+ "state": "{state}"
1749
+ },
1750
+ "headers": {}
1751
+ },
1752
+ "afterExchange": "zai-mint-key",
1753
+ "credential": {
1754
+ "access": {
1755
+ "path": "data.zai.access_token"
1756
+ },
1757
+ "refresh": {
1758
+ "path": "refresh_token"
1759
+ },
1760
+ "expires": {
1761
+ "mode": "never"
1762
+ },
1763
+ "email": {
1764
+ "path": "data.user.email"
1765
+ },
1766
+ "accountId": {
1767
+ "path": "data.user.id"
1768
+ }
1769
+ }
1770
+ },
1771
+ "storeAs": "zai",
1772
+ "refresh": {
1773
+ "kind": "none"
1774
+ },
1775
+ "callbackPort": 0,
1776
+ "pasteCode": true
1777
+ };
1778
+ var ZAI_CODING_PLAN_RULE = ZAI_CODING_PLAN_POLICY.login;
1779
+
1780
+ // scripts/omp-oauth/entry.ts
1781
+ var loginZaiCodingPlan = createOAuthCodeLogin(ZAI_CODING_PLAN_RULE, ZAI_CODING_PLAN_POLICY);
1782
+ export {
1783
+ loginKilo,
1784
+ loginZaiCodingPlan
1785
+ };