@cortexkit/pi-claustrum-auth 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1058 -266
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -138,10 +138,580 @@ function isBalanceFailure(service, body) {
138
138
  return false;
139
139
  }
140
140
  }
141
+ // ../core/src/billing.ts
142
+ import { randomUUID } from "node:crypto";
143
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/opencode2/integration.js
144
+ var PLACEHOLDER_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
145
+
146
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/opencode2/sse.js
147
+ function parseBlock(block) {
148
+ const data = [];
149
+ let event;
150
+ for (const line of block.split(/\r?\n/)) {
151
+ if (line.startsWith("data:"))
152
+ data.push(line.slice(5).replace(/^ /, ""));
153
+ else if (line.startsWith("event:"))
154
+ event = line.slice(6).trim();
155
+ }
156
+ if (data.length === 0)
157
+ return;
158
+ return event === undefined ? { data: data.join(`
159
+ `) } : { event, data: data.join(`
160
+ `) };
161
+ }
162
+ function watchServerSentEvents(onEvent, onError) {
163
+ const decoder = new TextDecoder;
164
+ let buffer = "";
165
+ const emit = (block) => {
166
+ const event = parseBlock(block);
167
+ if (!event)
168
+ return;
169
+ try {
170
+ onEvent(event);
171
+ } catch (error) {
172
+ onError(error);
173
+ }
174
+ };
175
+ const drain = () => {
176
+ for (;; ) {
177
+ const match = /\r?\n\r?\n/.exec(buffer);
178
+ if (!match)
179
+ return;
180
+ const block = buffer.slice(0, match.index);
181
+ buffer = buffer.slice(match.index + match[0].length);
182
+ emit(block);
183
+ }
184
+ };
185
+ return new TransformStream({
186
+ transform(chunk, controller) {
187
+ controller.enqueue(chunk);
188
+ buffer += decoder.decode(chunk, { stream: true });
189
+ drain();
190
+ },
191
+ flush() {
192
+ buffer += decoder.decode();
193
+ drain();
194
+ if (buffer.trim() !== "")
195
+ emit(buffer);
196
+ buffer = "";
197
+ }
198
+ });
199
+ }
200
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/routing-accessor/handle.js
201
+ function routingHandle(sessionId) {
202
+ const routing = Reflect.get(globalThis, Symbol.for("cortexkit.routing"));
203
+ if (typeof routing !== "function")
204
+ return;
205
+ const handle = routing(sessionId);
206
+ return typeof handle === "object" && handle !== null ? handle : undefined;
207
+ }
208
+
209
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/routing-accessor/cache-policy.js
210
+ var CACHE_WARM_STOP_REASONS = [
211
+ "cost-cap",
212
+ "count-cap",
213
+ "outside-hours",
214
+ "session-ended",
215
+ "unsupported"
216
+ ];
217
+ function isCacheWarmStopReason(value) {
218
+ return CACHE_WARM_STOP_REASONS.some((reason) => reason === value);
219
+ }
220
+ var warned = new Set;
221
+ function shape(value, seen = new Set) {
222
+ if (typeof value !== "object" || value === null) {
223
+ return `${typeof value}:${String(value)}`;
224
+ }
225
+ if (seen.has(value))
226
+ return "cycle";
227
+ seen.add(value);
228
+ return `${Array.isArray(value) ? "array" : "object"}:{${Object.entries(Object.getOwnPropertyDescriptors(value)).sort(([a], [b]) => a.localeCompare(b)).map(([key, descriptor]) => `${key}:${"value" in descriptor ? shape(descriptor.value, seen) : "accessor"}`).join(",")}}`;
229
+ }
230
+ function invalid(kind, value) {
231
+ let fingerprint = "unreadable";
232
+ try {
233
+ fingerprint = shape(value);
234
+ } catch {}
235
+ try {
236
+ const key = `${kind}:${fingerprint}`;
237
+ if (!warned.has(key)) {
238
+ warned.add(key);
239
+ console.warn(`[common-auth] Ignoring invalid session ${kind} policy`);
240
+ }
241
+ } catch {}
242
+ return null;
243
+ }
244
+ function record(value) {
245
+ return typeof value === "object" && value !== null && !Array.isArray(value);
246
+ }
247
+ function rejectAsync(value) {
248
+ if (typeof value.then !== "function")
249
+ return false;
250
+ Promise.resolve(value).catch(() => {});
251
+ return true;
252
+ }
253
+ function onlyKeys(value, keys) {
254
+ return Reflect.ownKeys(value).every((key) => typeof key === "string" && keys.includes(key));
255
+ }
256
+ function sessionCachePolicy(sessionId) {
257
+ let answer;
258
+ try {
259
+ const handle = routingHandle(sessionId);
260
+ if (!handle)
261
+ return null;
262
+ const read = handle.cache;
263
+ if (typeof read !== "function")
264
+ return null;
265
+ answer = read.call(handle);
266
+ if (answer === null)
267
+ return null;
268
+ if (!record(answer) || rejectAsync(answer))
269
+ return invalid("cache", answer);
270
+ const { ttl, keep_warm, hours } = answer;
271
+ if (!onlyKeys(answer, ["ttl", "keep_warm", "hours"]) || ttl !== undefined && ttl !== "none" && ttl !== "short" && ttl !== "long" || keep_warm !== undefined && keep_warm !== "off" && keep_warm !== "hours" && keep_warm !== "always" && keep_warm !== "auto" || ttl === "none" && keep_warm !== undefined && keep_warm !== "off" || keep_warm !== "hours" && "hours" in answer) {
272
+ return invalid("cache", answer);
273
+ }
274
+ const policy = {
275
+ ...ttl !== undefined ? { ttl } : {},
276
+ ...keep_warm !== undefined ? { keep_warm } : {}
277
+ };
278
+ if (keep_warm === "hours") {
279
+ if (!record(hours) || !onlyKeys(hours, ["from", "to", "tz"])) {
280
+ return invalid("cache", answer);
281
+ }
282
+ const { from, to, tz } = hours;
283
+ const time = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
284
+ if (typeof from !== "string" || !time.test(from) || typeof to !== "string" || !time.test(to) || from === to || typeof tz !== "string" || tz.length === 0) {
285
+ return invalid("cache", answer);
286
+ }
287
+ new Intl.DateTimeFormat("en", { timeZone: tz });
288
+ policy.hours = { from, to, tz };
289
+ }
290
+ return policy;
291
+ } catch {
292
+ return invalid("cache", answer);
293
+ }
294
+ }
295
+
296
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/routing-accessor/index.js
297
+ function isObject(value) {
298
+ return typeof value === "object" && value !== null;
299
+ }
300
+ function isNonEmptyString(value) {
301
+ return typeof value === "string" && value.length > 0;
302
+ }
303
+ function billingCache(value) {
304
+ if (!isObject(value) || Array.isArray(value))
305
+ return;
306
+ const { ttlMs, implicit, warming } = value;
307
+ const cache = {};
308
+ if (!(ttlMs !== undefined && implicit !== undefined)) {
309
+ if (typeof ttlMs === "number" && Number.isSafeInteger(ttlMs) && ttlMs > 0) {
310
+ cache.ttl_ms = ttlMs;
311
+ } else if (implicit === true) {
312
+ cache.implicit = true;
313
+ }
314
+ }
315
+ if (isObject(warming) && !Array.isArray(warming)) {
316
+ const { on, stopReason } = warming;
317
+ if (typeof on === "boolean") {
318
+ cache.warming = {
319
+ on,
320
+ ...!on && isCacheWarmStopReason(stopReason) ? { stop_reason: stopReason } : {}
321
+ };
322
+ }
323
+ }
324
+ return Object.keys(cache).length > 0 ? cache : undefined;
325
+ }
326
+ function billingUsage(value) {
327
+ if (!isObject(value) || Array.isArray(value))
328
+ return;
329
+ const usage = {};
330
+ for (const [inputKey, payloadKey] of [
331
+ ["input", "input"],
332
+ ["output", "output"],
333
+ ["cacheRead", "cache_read"],
334
+ ["cacheWrite", "cache_write"],
335
+ ["cacheWrite5m", "cache_write_5m"],
336
+ ["cacheWrite1h", "cache_write_1h"],
337
+ ["reasoning", "reasoning"]
338
+ ]) {
339
+ const count = value[inputKey];
340
+ if (typeof count === "number" && Number.isSafeInteger(count) && count >= 0) {
341
+ usage[payloadKey] = count;
342
+ }
343
+ }
344
+ const reasoningIncludedInOutput = value.reasoningIncludedInOutput;
345
+ if (typeof reasoningIncludedInOutput === "boolean") {
346
+ usage.reasoning_included_in_output = reasoningIncludedInOutput;
347
+ }
348
+ return Object.keys(usage).length > 0 ? usage : undefined;
349
+ }
350
+ function reportRouting(input) {
351
+ try {
352
+ const handle = routingHandle(input.sessionId);
353
+ if (!handle)
354
+ return;
355
+ const report = handle.report;
356
+ if (typeof report !== "function")
357
+ return;
358
+ let payload;
359
+ if ("kind" in input) {
360
+ switch (input.kind) {
361
+ case "billing": {
362
+ const { attemptId, requestKind, credentialId, provider, model, outcome, accountId, providerRequestId, providerResponseId, userMessageId, status, attempt, chargeBasis, usage: inputUsage, usageByModel: inputUsageByModel, cache: inputCache } = input;
363
+ if (!isNonEmptyString(attemptId) || !isNonEmptyString(credentialId) || !isNonEmptyString(provider) || !isNonEmptyString(model) || requestKind !== "primary" && requestKind !== "title" && requestKind !== "compaction" && requestKind !== "generate" && requestKind !== "keep_warm" && requestKind !== "prime" || outcome !== "completed" && outcome !== "cut" && outcome !== "failed")
364
+ return;
365
+ const usage = billingUsage(inputUsage);
366
+ const cache = billingCache(inputCache);
367
+ const usageByModel = [];
368
+ if (Array.isArray(inputUsageByModel)) {
369
+ for (const entry of inputUsageByModel) {
370
+ if (!isObject(entry) || Array.isArray(entry))
371
+ continue;
372
+ const modelUsed = entry.modelUsed;
373
+ if (!isNonEmptyString(modelUsed))
374
+ continue;
375
+ const modelUsage = billingUsage(entry.usage);
376
+ if (!modelUsage)
377
+ continue;
378
+ usageByModel.push({ model_used: modelUsed, usage: modelUsage });
379
+ }
380
+ }
381
+ payload = {
382
+ kind: "billing",
383
+ attempt_id: attemptId,
384
+ request_kind: requestKind,
385
+ credential_id: credentialId,
386
+ provider,
387
+ model,
388
+ outcome,
389
+ ...isNonEmptyString(accountId) ? { account_id: accountId } : {},
390
+ ...isNonEmptyString(providerRequestId) ? { provider_request_id: providerRequestId } : {},
391
+ ...isNonEmptyString(providerResponseId) ? { provider_response_id: providerResponseId } : {},
392
+ ...isNonEmptyString(userMessageId) ? { user_message_id: userMessageId } : {},
393
+ ...typeof status === "number" && Number.isInteger(status) && status >= 0 ? { status } : {},
394
+ ...typeof attempt === "number" && Number.isInteger(attempt) && attempt >= 1 ? { attempt } : {},
395
+ ...chargeBasis === "subscription_included" || chargeBasis === "metered_api" ? { charge_basis: chargeBasis } : {},
396
+ ...usage ? { usage } : {},
397
+ ...usageByModel.length > 0 ? { usage_by_model: usageByModel } : {},
398
+ ...cache ? { cache } : {}
399
+ };
400
+ break;
401
+ }
402
+ case "turn_notes_supported": {
403
+ const { model, supported } = input;
404
+ if (typeof model !== "string" || model.length === 0 || typeof supported !== "boolean")
405
+ return;
406
+ payload = {
407
+ kind: "turn_notes_supported",
408
+ model,
409
+ supported
410
+ };
411
+ break;
412
+ }
413
+ case "turn_note_skipped": {
414
+ const { after_tool_use_id, reason } = input;
415
+ if (typeof after_tool_use_id !== "string" || after_tool_use_id.length === 0 || reason !== "anchor_missing" && reason !== "before_user_message" && reason !== "unsupported_model" && reason !== "not_oauth")
416
+ return;
417
+ payload = {
418
+ kind: "turn_note_skipped",
419
+ after_tool_use_id,
420
+ reason
421
+ };
422
+ break;
423
+ }
424
+ default:
425
+ return;
426
+ }
427
+ } else {
428
+ const identity = {
429
+ account_id: input.accountId,
430
+ ...input.credentialId !== undefined ? { credential_id: input.credentialId } : {}
431
+ };
432
+ switch (input.outcome) {
433
+ case "served":
434
+ payload = { ...identity, outcome: "served", headers: input.headers };
435
+ break;
436
+ case "exhausted": {
437
+ const { window, pool } = input;
438
+ if (window !== "5h" && window !== "7d")
439
+ return;
440
+ if (pool !== undefined && (typeof pool !== "string" || !/^[a-z0-9._-]{1,64}$/.test(pool)))
441
+ return;
442
+ payload = {
443
+ ...identity,
444
+ outcome: "exhausted",
445
+ window,
446
+ ...pool ? { pool } : {},
447
+ ...input.resetsAt !== undefined ? { resets_at: input.resetsAt } : {}
448
+ };
449
+ break;
450
+ }
451
+ default:
452
+ return;
453
+ }
454
+ }
455
+ const pending = report.call(handle, payload);
456
+ if (isObject(pending) && typeof pending.then === "function") {
457
+ Promise.resolve(pending).catch(() => {});
458
+ }
459
+ } catch {}
460
+ }
461
+
462
+ // ../core/src/billing.ts
463
+ var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
464
+ function count(value, paths = []) {
465
+ for (const path of paths) {
466
+ let cursor = value;
467
+ for (const key of path.split("."))
468
+ cursor = object(cursor) ? cursor[key] : undefined;
469
+ if (typeof cursor === "number" && Number.isSafeInteger(cursor) && cursor >= 0)
470
+ return cursor;
471
+ }
472
+ return;
473
+ }
474
+ function rawBillingUsage(entry, value) {
475
+ const semantics = entry.billing;
476
+ if (!semantics)
477
+ return;
478
+ const usage = {};
479
+ const tokens = object(value) && object(value.usage) && object(value.usage.opencode) ? value.usage.opencode.tokens : undefined;
480
+ const opencode = !!semantics.opencodeTokens && object(tokens);
481
+ if (opencode) {
482
+ for (const [field, path] of [
483
+ ["input", "input"],
484
+ ["output", "output"],
485
+ ["cacheRead", "cache_read"],
486
+ ["cacheWrite5m", "cache_write_5m"],
487
+ ["cacheWrite1h", "cache_write_1h"],
488
+ ["reasoning", "reasoning"]
489
+ ]) {
490
+ const measured = count(tokens, [path]);
491
+ if (measured !== undefined)
492
+ usage[field] = measured;
493
+ }
494
+ } else {
495
+ for (const field of [
496
+ "input",
497
+ "output",
498
+ "cacheRead",
499
+ "cacheWrite",
500
+ "reasoning"
501
+ ]) {
502
+ const measured = count(value, semantics[field]);
503
+ if (measured !== undefined)
504
+ usage[field] = measured;
505
+ }
506
+ }
507
+ return Object.keys(usage).length ? { counts: usage, opencode } : undefined;
508
+ }
509
+ function finalizedUsage(entry, counts, opencode) {
510
+ if (!counts)
511
+ return;
512
+ const usage = { ...counts };
513
+ if (opencode) {
514
+ if (usage.cacheWrite5m !== undefined || usage.cacheWrite1h !== undefined)
515
+ usage.cacheWrite = (usage.cacheWrite5m ?? 0) + (usage.cacheWrite1h ?? 0);
516
+ usage.reasoningIncludedInOutput = true;
517
+ } else {
518
+ if (usage.input !== undefined && entry.billing?.promptIncludesCache)
519
+ usage.input = Math.max(0, usage.input - (usage.cacheRead ?? 0) - (usage.cacheWrite ?? 0));
520
+ if (entry.billing?.reasoningIncludedInOutput !== undefined)
521
+ usage.reasoningIncludedInOutput = entry.billing.reasoningIncludedInOutput;
522
+ }
523
+ return usage;
524
+ }
525
+ function hasBillingAccessor() {
526
+ try {
527
+ return typeof Reflect.get(globalThis, Symbol.for("cortexkit.routing")) === "function";
528
+ } catch {
529
+ return false;
530
+ }
531
+ }
532
+
533
+ class BillingAttempt {
534
+ entry;
535
+ provider;
536
+ sessionId;
537
+ requestKind;
538
+ model;
539
+ receipt;
540
+ attempt;
541
+ pi;
542
+ attemptId = randomUUID();
543
+ reported = false;
544
+ completed = false;
545
+ failed = false;
546
+ outputStarted = false;
547
+ responseId;
548
+ rawUsage;
549
+ rawOpenCodeUsage;
550
+ status;
551
+ ended = false;
552
+ constructor(entry, provider, sessionId, requestKind, model, receipt, attempt, pi = false) {
553
+ this.entry = entry;
554
+ this.provider = provider;
555
+ this.sessionId = sessionId;
556
+ this.requestKind = requestKind;
557
+ this.model = model;
558
+ this.receipt = receipt;
559
+ this.attempt = attempt;
560
+ this.pi = pi;
561
+ }
562
+ event(value) {
563
+ if (!object(value))
564
+ return;
565
+ if (value.type === "error" || value.type === "response.failed" || value.error)
566
+ this.failed = true;
567
+ if (value.type === "response.completed" || value.type === "response.incomplete")
568
+ this.completed = true;
569
+ if (typeof value.type === "string" && value.type.endsWith(".delta"))
570
+ this.outputStarted = true;
571
+ if (Array.isArray(value.choices)) {
572
+ for (const choice of value.choices) {
573
+ if (!object(choice))
574
+ continue;
575
+ if (choice.finish_reason != null)
576
+ this.completed = true;
577
+ if (object(choice.delta) && Object.keys(choice.delta).some((key) => key !== "role"))
578
+ this.outputStarted = true;
579
+ if (object(choice.message))
580
+ this.completed = true;
581
+ }
582
+ }
583
+ const response = object(value.response) ? value.response : value;
584
+ if (!this.pi && typeof response.id === "string")
585
+ this.responseId = response.id;
586
+ const raw = rawBillingUsage(this.entry, response);
587
+ if (raw?.opencode) {
588
+ this.rawOpenCodeUsage = { ...this.rawOpenCodeUsage, ...raw.counts };
589
+ } else if (raw) {
590
+ this.rawUsage = { ...this.rawUsage, ...raw.counts };
591
+ }
592
+ }
593
+ bodyEnd(ended, status) {
594
+ this.status = status;
595
+ this.ended = ended;
596
+ if (!this.pi || status < 200 || status >= 300)
597
+ this.end();
598
+ }
599
+ cancel(status) {
600
+ this.bodyEnd(this.completed, status);
601
+ }
602
+ json(value) {
603
+ this.event(value);
604
+ if (object(value) && !value.error)
605
+ this.completed = true;
606
+ }
607
+ done() {
608
+ this.completed = true;
609
+ }
610
+ piEnd(responseId, stopReason) {
611
+ this.responseId = responseId;
612
+ if (stopReason === "error")
613
+ this.failed = true;
614
+ if (stopReason === "aborted")
615
+ this.ended = false;
616
+ else if (stopReason && stopReason !== "error") {
617
+ this.completed = true;
618
+ this.ended = true;
619
+ }
620
+ this.end();
621
+ }
622
+ end(outputStarted = this.outputStarted, ended = this.ended, status = this.status) {
623
+ if (this.reported)
624
+ return;
625
+ this.reported = true;
626
+ const warming = sessionCachePolicy(this.sessionId)?.keep_warm;
627
+ const implicit = this.entry.billing?.implicitCache;
628
+ const usage = finalizedUsage(this.entry, this.rawOpenCodeUsage ?? this.rawUsage, this.rawOpenCodeUsage !== undefined);
629
+ reportRouting({
630
+ sessionId: this.sessionId,
631
+ kind: "billing",
632
+ attemptId: this.attemptId,
633
+ requestKind: this.requestKind,
634
+ credentialId: this.receipt.credentialId,
635
+ ...this.receipt.accountIdentity ? { accountId: this.receipt.accountIdentity } : {},
636
+ provider: this.provider,
637
+ model: this.model,
638
+ outcome: this.failed || status !== undefined && (status < 200 || status >= 300) ? "failed" : this.completed && ended ? "completed" : outputStarted ? "cut" : "failed",
639
+ ...status !== undefined ? { status } : {},
640
+ ...this.attempt !== undefined ? { attempt: this.attempt } : {},
641
+ ...this.responseId ? { providerResponseId: this.responseId } : {},
642
+ ...this.entry.chargeBasis ? { chargeBasis: this.entry.chargeBasis } : {},
643
+ ...usage ? { usage } : {},
644
+ ...implicit || warming && warming !== "off" ? {
645
+ cache: {
646
+ ...implicit ? { implicit } : {},
647
+ ...warming && warming !== "off" ? { warming: { on: false, stopReason: "unsupported" } } : {}
648
+ }
649
+ } : {}
650
+ });
651
+ }
652
+ }
653
+ function observeBillingResponse(record, response) {
654
+ if (!record)
655
+ return response;
656
+ if (!response.body) {
657
+ record.bodyEnd(true, response.status);
658
+ return response;
659
+ }
660
+ const sse = /^text\/event-stream(?:\s*;|$)/i.test(response.headers.get("content-type") ?? "");
661
+ const decoder = new TextDecoder;
662
+ let json = "";
663
+ let oversized = false;
664
+ const body = sse ? response.body.pipeThrough(watchServerSentEvents((event) => {
665
+ if (event.data === "[DONE]")
666
+ record.done();
667
+ else {
668
+ try {
669
+ record.event(JSON.parse(event.data));
670
+ } catch {}
671
+ }
672
+ }, () => {})) : response.body;
673
+ const reader = body.getReader();
674
+ return new Response(new ReadableStream({
675
+ async pull(controller) {
676
+ try {
677
+ const next = await reader.read();
678
+ if (next.done) {
679
+ if (!sse && !oversized) {
680
+ try {
681
+ record.json(JSON.parse(json + decoder.decode()));
682
+ } catch {}
683
+ }
684
+ record.bodyEnd(true, response.status);
685
+ controller.close();
686
+ } else {
687
+ if (!sse && !oversized) {
688
+ json += decoder.decode(next.value, { stream: true });
689
+ if (json.length > 1024 * 1024) {
690
+ oversized = true;
691
+ json = "";
692
+ }
693
+ }
694
+ controller.enqueue(next.value);
695
+ }
696
+ } catch (error) {
697
+ record.bodyEnd(false, response.status);
698
+ controller.error(error);
699
+ }
700
+ },
701
+ cancel(reason) {
702
+ record.cancel(response.status);
703
+ return reader.cancel(reason);
704
+ }
705
+ }, { highWaterMark: 0 }), {
706
+ status: response.status,
707
+ statusText: response.statusText,
708
+ headers: response.headers
709
+ });
710
+ }
141
711
  // ../core/src/fetch.ts
142
- import { randomUUID as randomUUID7 } from "node:crypto";
712
+ import { randomUUID as randomUUID8 } from "node:crypto";
143
713
 
144
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/request-history.js
714
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/request-history.js
145
715
  function sameAccount(a, b) {
146
716
  return a.namespace === b.namespace && a.accountId === b.accountId && a.incarnation === b.incarnation;
147
717
  }
@@ -239,7 +809,7 @@ var REQUEST_EXCLUSION_EFFECTS = Object.freeze({
239
809
  chargeSwitch: false
240
810
  });
241
811
 
242
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/activity.js
812
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/activity.js
243
813
  function effectiveCacheTtlMs(ttlMs) {
244
814
  return ttlMs !== undefined && Number.isFinite(ttlMs) && ttlMs >= 0 ? ttlMs : 300000;
245
815
  }
@@ -284,7 +854,7 @@ function createSessionActivityStore() {
284
854
  }
285
855
  };
286
856
  }
287
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/scope.js
857
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/scope.js
288
858
  function scopeCovers(scope, model, familyOf) {
289
859
  switch (scope.kind) {
290
860
  case "pool":
@@ -295,20 +865,20 @@ function scopeCovers(scope, model, familyOf) {
295
865
  return scope.model === model;
296
866
  }
297
867
  }
298
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/hold.js
868
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/hold.js
299
869
  var MAX_SAME_ACCOUNT_HOLD_MS = 3621000;
300
870
  function readMaxSameAccountWait(value) {
301
871
  return value === 0 || value === 15 || value === "max" ? value : 15;
302
872
  }
303
873
 
304
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/jitter.js
874
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/jitter.js
305
875
  import { createHash } from "node:crypto";
306
876
  function holdDelayMs(sessionId, delayMs) {
307
877
  const seconds = createHash("sha256").update(sessionId).digest().readUInt32BE(0);
308
878
  return 1000 * (Math.max(1, Math.ceil(delayMs / 1000)) + seconds % 21);
309
879
  }
310
880
 
311
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/terminal.js
881
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/terminal.js
312
882
  function scanTerminalReset(input, now) {
313
883
  if (!Number.isFinite(input.maxAgeMs) || input.maxAgeMs < 0)
314
884
  return;
@@ -409,7 +979,7 @@ function terminalRefusalDecision(facts, axes, history, metadata) {
409
979
  return { ...wait, action: "hold", account: kept.account };
410
980
  }
411
981
 
412
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/wake.js
982
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/wake.js
413
983
  function waitCheckpoint(accountKey, decidedAt, windows) {
414
984
  return {
415
985
  accountKey: { ...accountKey },
@@ -431,7 +1001,7 @@ function liftedWindowsForWake(wake, account, windows, now) {
431
1001
  return windows.filter((window) => canLift(window) && windows.filter((other) => other.confirmed && other.window === window.window).every(canLift)).map((window) => window.window);
432
1002
  }
433
1003
 
434
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/decide.js
1004
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/decide.js
435
1005
  function finiteFuture(value, now) {
436
1006
  return value !== undefined && Number.isFinite(value) && value > now;
437
1007
  }
@@ -696,7 +1266,7 @@ function decideAfterLimit(facts, axes) {
696
1266
  return refusal(facts, axes, history, "quota");
697
1267
  return pass("no-override");
698
1268
  }
699
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/duration.js
1269
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/duration.js
700
1270
  function formatDuration(ms) {
701
1271
  if (!Number.isFinite(ms))
702
1272
  return "unknown";
@@ -716,7 +1286,7 @@ function formatDuration(ms) {
716
1286
  return `${remainingMinutes}m`;
717
1287
  }
718
1288
  var formatReset = ({ resetAt, now }) => formatDuration(resetAt - now);
719
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/envelope.js
1289
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/envelope.js
720
1290
  var envelopeError = Symbol.for("@cortexkit/common-auth/limits-envelope-error");
721
1291
 
722
1292
  class LimitsEnvelopeConflictError extends Error {
@@ -738,7 +1308,7 @@ function limitsEnvelopeAbandonReason(error) {
738
1308
  const reason = error && typeof error === "object" && Reflect.get(error, envelopeError);
739
1309
  return reason === "conflict" || reason === "unsupported" ? reason : undefined;
740
1310
  }
741
- function record(value) {
1311
+ function record2(value) {
742
1312
  return value !== null && typeof value === "object" && !Array.isArray(value);
743
1313
  }
744
1314
  var revision = (value) => Number.isSafeInteger(value) && value >= 0;
@@ -746,16 +1316,16 @@ var finite = (value) => typeof value === "number" && Number.isFinite(value);
746
1316
  var cause = (value) => value === undefined || value === "rate-limit" || value === "payment-balance";
747
1317
  var arrayOf = (value, valid) => Array.isArray(value) && value.every(valid);
748
1318
  function account(value, namespace) {
749
- return record(value) && value.namespace === namespace && typeof value.accountId === "string" && typeof value.incarnation === "string";
1319
+ return record2(value) && value.namespace === namespace && typeof value.accountId === "string" && typeof value.incarnation === "string";
750
1320
  }
751
1321
  function key(value, namespace) {
752
- if (!record(value) || !record(value.scope))
1322
+ if (!record2(value) || !record2(value.scope))
753
1323
  return false;
754
1324
  const scope = value.scope;
755
1325
  return account(value.account, namespace) && typeof value.window === "string" && (scope.kind === "pool" || scope.kind === "family" && typeof scope.family === "string" || scope.kind === "model" && typeof scope.model === "string");
756
1326
  }
757
1327
  function validEnvelope(value, namespace) {
758
- return value.namespace === namespace && typeof value.generation === "string" && revision(value.revision) && revision(value.lowWatermark) && arrayOf(value.marks, (mark) => record(mark) && key(mark.key, namespace) && ["latest-evidence", "max-until", "overwrite"].includes(mark.mergeLaw) && arrayOf(mark.entries, (entry) => record(entry) && cause(entry.cause) && finite(entry.until) && finite(entry.evidenceAt) && revision(entry.baseRevision) && revision(entry.committedRevision))) && arrayOf(value.tombstones, (clear) => record(clear) && key(clear.key, namespace) && revision(clear.revision) && cause(clear.cause)) && arrayOf(value.operationIds, (op) => record(op) && typeof op.producerId === "string" && typeof op.operationId === "string" && revision(op.revision)) && arrayOf(value.access, (access) => record(access) && account(access.account, namespace) && finite(access.eligibilityStateUpdatedAt) && revision(access.committedRevision));
1328
+ return value.namespace === namespace && typeof value.generation === "string" && revision(value.revision) && revision(value.lowWatermark) && arrayOf(value.marks, (mark) => record2(mark) && key(mark.key, namespace) && ["latest-evidence", "max-until", "overwrite"].includes(mark.mergeLaw) && arrayOf(mark.entries, (entry) => record2(entry) && cause(entry.cause) && finite(entry.until) && finite(entry.evidenceAt) && revision(entry.baseRevision) && revision(entry.committedRevision))) && arrayOf(value.tombstones, (clear) => record2(clear) && key(clear.key, namespace) && revision(clear.revision) && cause(clear.cause)) && arrayOf(value.operationIds, (op) => record2(op) && typeof op.producerId === "string" && typeof op.operationId === "string" && revision(op.revision)) && arrayOf(value.access, (access) => record2(access) && account(access.account, namespace) && finite(access.eligibilityStateUpdatedAt) && revision(access.committedRevision));
759
1329
  }
760
1330
 
761
1331
  class EnvelopeGuard {
@@ -776,7 +1346,7 @@ class EnvelopeGuard {
776
1346
  if (value === undefined)
777
1347
  return {};
778
1348
  let replacement;
779
- if (!record(value))
1349
+ if (!record2(value))
780
1350
  replacement = "malformed";
781
1351
  else if (value.schemaVersion !== 1) {
782
1352
  this.terminal = new LimitsEnvelopeUnsupportedError;
@@ -803,7 +1373,7 @@ class EnvelopeGuard {
803
1373
  return true;
804
1374
  }
805
1375
  }
806
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/wording.js
1376
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/wording.js
807
1377
  var openCode1Patterns = [
808
1378
  /429|500|502|503|504|524/i,
809
1379
  /rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,
@@ -869,7 +1439,7 @@ function hasUnsafeWording(text) {
869
1439
  return openCode1Patterns.some((pattern) => pattern.test(text)) || pi140Pattern.test(text);
870
1440
  }
871
1441
 
872
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/labels.js
1442
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/labels.js
873
1443
  var emailPattern = /[^\s@]+@[^\s@]+\.[^\s@]+/;
874
1444
  function containsEmail(text) {
875
1445
  return emailPattern.test(text);
@@ -878,7 +1448,7 @@ function sanitizeRefusalLabel(label) {
878
1448
  return containsEmail(label) || hasUnsafeWording(label) ? "this account" : label;
879
1449
  }
880
1450
 
881
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/families.js
1451
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/families.js
882
1452
  class ClaudeIncompleteError extends Error {
883
1453
  code = "ECONNRESET";
884
1454
  syscall = "sticky-routing";
@@ -996,7 +1566,7 @@ function buildRefusal(input) {
996
1566
  body
997
1567
  };
998
1568
  }
999
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/identity.js
1569
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/identity.js
1000
1570
  function isIdentityCompatible(a, b) {
1001
1571
  return sameAccount(a.account, b.account) && (a.identity === undefined || b.identity === undefined || a.identity === b.identity);
1002
1572
  }
@@ -1012,7 +1582,7 @@ function validateIdentityFence(observed, authoritative, authorizeEpoch) {
1012
1582
  return "credential-epoch";
1013
1583
  return;
1014
1584
  }
1015
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/marker.js
1585
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/marker.js
1016
1586
  var ANTIGRAVITY_FAILURE_LADDER = Object.freeze({
1017
1587
  kind: "failure-ladder",
1018
1588
  mergeLaw: "max-until",
@@ -1083,7 +1653,7 @@ function markFromSignal(signal, axes, history) {
1083
1653
  ...axes.kind === "hint" && axes.causes?.some((cause) => cause === signal.kind) ? { cause: signal.kind } : {}
1084
1654
  } : undefined;
1085
1655
  }
1086
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/merge-laws.js
1656
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/merge-laws.js
1087
1657
  function mergeTimedMarkEntries(law, entries, now, clearRevision = 0) {
1088
1658
  const candidates = entries.filter((e) => e.baseRevision >= clearRevision);
1089
1659
  if (law !== "max-until") {
@@ -1105,7 +1675,7 @@ function mergeAccessState(a, b) {
1105
1675
  }
1106
1676
  return a.committedRevision > b.committedRevision ? a : b;
1107
1677
  }
1108
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/namespace.js
1678
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/namespace.js
1109
1679
  var LIMITS_HISTORY_BOUND = 1024;
1110
1680
  function storedCause(cause) {
1111
1681
  return cause === "rate-limit" || cause === "payment-balance" ? cause : undefined;
@@ -1298,7 +1868,7 @@ function applyLimitsCommands(initial, commands, context) {
1298
1868
  }
1299
1869
  return { snapshot, outcomes };
1300
1870
  }
1301
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/path.js
1871
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/path.js
1302
1872
  import { realpathSync } from "node:fs";
1303
1873
  import { basename, dirname, join, resolve } from "node:path";
1304
1874
  function canonicalLimitsPath(path) {
@@ -1320,7 +1890,7 @@ function canonicalLimitsPath(path) {
1320
1890
  }
1321
1891
  }
1322
1892
  }
1323
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/persistence.js
1893
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/persistence.js
1324
1894
  class LimitsPersistenceRefusal extends Error {
1325
1895
  code;
1326
1896
  constructor(code) {
@@ -1329,9 +1899,9 @@ class LimitsPersistenceRefusal extends Error {
1329
1899
  this.name = "LimitsPersistenceRefusal";
1330
1900
  }
1331
1901
  }
1332
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/envelope-loss.js
1902
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/envelope-loss.js
1333
1903
  import { AsyncResource } from "node:async_hooks";
1334
- import { randomUUID } from "node:crypto";
1904
+ import { randomUUID as randomUUID2 } from "node:crypto";
1335
1905
  import { isDeepStrictEqual } from "node:util";
1336
1906
  var detached = new AsyncResource("common-auth-limits-recovery");
1337
1907
 
@@ -1396,8 +1966,8 @@ class EnvelopeHistory {
1396
1966
  }
1397
1967
  recover(present, previous, namespace, now) {
1398
1968
  if (!present)
1399
- this.missingGeneration ??= randomUUID();
1400
- const current = present ?? createLimitsNamespace(namespace, this.missingGeneration ?? randomUUID());
1969
+ this.missingGeneration ??= randomUUID2();
1970
+ const current = present ?? createLimitsNamespace(namespace, this.missingGeneration ?? randomUUID2());
1401
1971
  const sources = [...this.retained(previous), current];
1402
1972
  const marks = new Map;
1403
1973
  const tombstones = new Map;
@@ -1454,7 +2024,7 @@ class EnvelopeHistory {
1454
2024
  }, now);
1455
2025
  }
1456
2026
  }
1457
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/presets.js
2027
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/presets.js
1458
2028
  function immutable(value) {
1459
2029
  if (value && typeof value === "object") {
1460
2030
  for (const child of Object.values(value))
@@ -1694,7 +2264,7 @@ var limitPresets = immutable({
1694
2264
  "window-router": windowRouter,
1695
2265
  "status-vault-order": statusVaultOrder
1696
2266
  });
1697
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/registry.js
2267
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/registry.js
1698
2268
  import { AsyncResource as AsyncResource2 } from "node:async_hooks";
1699
2269
  var LIMITS_REGISTRY_KEY = Symbol.for("@cortexkit/common-auth/limits-registry/schema-v1");
1700
2270
  var PREFIX = "@cortexkit/common-auth/limits-registry/schema-v";
@@ -2157,17 +2727,17 @@ async function acquireLimitsRegistry(options) {
2157
2727
  };
2158
2728
  }
2159
2729
  // ../core/src/limits.ts
2160
- import { randomUUID as randomUUID6 } from "node:crypto";
2730
+ import { randomUUID as randomUUID7 } from "node:crypto";
2161
2731
 
2162
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/vault-adapter.js
2163
- import { randomUUID as randomUUID5 } from "node:crypto";
2732
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/vault-adapter.js
2733
+ import { randomUUID as randomUUID6 } from "node:crypto";
2164
2734
 
2165
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/roster.js
2735
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/roster.js
2166
2736
  import { createHash as createHash2 } from "node:crypto";
2167
2737
  import { stat as stat3 } from "node:fs/promises";
2168
- import { resolve as resolve7 } from "node:path";
2738
+ import { resolve as resolve8 } from "node:path";
2169
2739
 
2170
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/fs/file-read-cache.js
2740
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/file-read-cache.js
2171
2741
  import { lstat, stat } from "node:fs/promises";
2172
2742
  import { resolve as resolve2 } from "node:path";
2173
2743
  async function identity(path, followSymlinks) {
@@ -2217,13 +2787,13 @@ class FileReadCache {
2217
2787
  }
2218
2788
  }
2219
2789
 
2220
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/fs/atomic-write.js
2221
- import { randomUUID as randomUUID3 } from "node:crypto";
2790
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/atomic-write.js
2791
+ import { randomUUID as randomUUID4 } from "node:crypto";
2222
2792
  import { mkdir, open, rename as rename2, rm } from "node:fs/promises";
2223
2793
  import { dirname as dirname3 } from "node:path";
2224
2794
 
2225
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/fs/private-files.js
2226
- import { randomUUID as randomUUID2 } from "node:crypto";
2795
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/private-files.js
2796
+ import { randomUUID as randomUUID3 } from "node:crypto";
2227
2797
  import { lstat as lstat2, readFile, rename, unlink } from "node:fs/promises";
2228
2798
  import { tmpdir } from "node:os";
2229
2799
  import { dirname as dirname2, join as join2, resolve as resolve3 } from "node:path";
@@ -2251,7 +2821,7 @@ function isUnavailable(api, error) {
2251
2821
  }
2252
2822
  async function assertNativeAddonLoads(api) {
2253
2823
  try {
2254
- await api.verifyPrivatePath(join2(tmpdir(), `.common-auth-private-files-probe-${randomUUID2()}`), "file");
2824
+ await api.verifyPrivatePath(join2(tmpdir(), `.common-auth-private-files-probe-${randomUUID3()}`), "file");
2255
2825
  } catch (error) {
2256
2826
  if (isUnavailable(api, error))
2257
2827
  throw privateFilesUnavailable(error);
@@ -2458,7 +3028,7 @@ async function writePrivateAtomic(path, bytes, options = {}) {
2458
3028
  if (error.code !== "ENOENT")
2459
3029
  throw error;
2460
3030
  }
2461
- const stage = resolve3(options.stagePath ?? `${path}.${randomUUID2()}.tmp`);
3031
+ const stage = resolve3(options.stagePath ?? `${path}.${randomUUID3()}.tmp`);
2462
3032
  if (dirname2(stage) !== dirname2(path))
2463
3033
  throw new PrivateFileError(path, "stage-directory", { code: "EXDEV" });
2464
3034
  let created = false;
@@ -2517,7 +3087,7 @@ async function writePrivateAtomic(path, bytes, options = {}) {
2517
3087
  }
2518
3088
  }
2519
3089
 
2520
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/fs/atomic-write.js
3090
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/atomic-write.js
2521
3091
  class AtomicSyncError extends Error {
2522
3092
  constructor(cause) {
2523
3093
  super("file or directory sync failed", { cause });
@@ -2532,7 +3102,7 @@ async function writeJsonAtomicTracked(path, value, options, onRenamed) {
2532
3102
  return writePrivateAtomic(path, options.serialize ? options.serialize(value) : `${JSON.stringify(value, null, 2)}
2533
3103
  `, {
2534
3104
  beforeRename: options.beforeRename,
2535
- stagePath: `${path}.${(options.stageName ?? randomUUID3)()}.tmp`,
3105
+ stagePath: `${path}.${(options.stageName ?? randomUUID4)()}.tmp`,
2536
3106
  onRenamed,
2537
3107
  durable: options.durable,
2538
3108
  durability: options.durability,
@@ -2540,7 +3110,7 @@ async function writeJsonAtomicTracked(path, value, options, onRenamed) {
2540
3110
  });
2541
3111
  }
2542
3112
  await mkdir(dirname3(path), { recursive: true });
2543
- const tempPath = `${path}.${(options.stageName ?? randomUUID3)()}.tmp`;
3113
+ const tempPath = `${path}.${(options.stageName ?? randomUUID4)()}.tmp`;
2544
3114
  let handle;
2545
3115
  let created = false;
2546
3116
  try {
@@ -2578,7 +3148,7 @@ async function writeJsonAtomicTracked(path, value, options, onRenamed) {
2578
3148
  await rm(tempPath, { force: true }).catch(() => {});
2579
3149
  }
2580
3150
  }
2581
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/fs/lock-constants.js
3151
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/lock-constants.js
2582
3152
  var WRITER_LOCK_CONSTANTS = Object.freeze({
2583
3153
  sidebar: Object.freeze({
2584
3154
  name: "sidebar-write",
@@ -2593,13 +3163,45 @@ var WRITER_LOCK_CONSTANTS = Object.freeze({
2593
3163
  renew: true
2594
3164
  })
2595
3165
  });
2596
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
2597
- import { randomUUID as randomUUID4 } from "node:crypto";
3166
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
3167
+ import { randomUUID as randomUUID5 } from "node:crypto";
2598
3168
  import { link, lstat as lstat3, mkdir as mkdir2, open as open2, readFile as readFile2, rename as rename3, rm as rm2, stat as stat2 } from "node:fs/promises";
2599
3169
  import { dirname as dirname4, join as join4 } from "node:path";
2600
3170
 
2601
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/fs/with-lock.js
2602
- import { join as join3, resolve as resolve4 } from "node:path";
3171
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/lock-record.js
3172
+ import { resolve as resolve4 } from "node:path";
3173
+ class DisappearedLockRecordError extends Error {
3174
+ path;
3175
+ code = "ENOENT";
3176
+ constructor(path, cause) {
3177
+ super(`Lock record disappeared: ${path}`, { cause });
3178
+ this.path = path;
3179
+ }
3180
+ }
3181
+ function isWindowsAccessDeniedRead(error, paths) {
3182
+ return error instanceof PrivateFileError && error.reason === "io-error" && error.win32Code === 5 && (error.stage === "read" || error.stage === "verify") && paths.some((path) => resolve4(path) === error.path);
3183
+ }
3184
+ function isWindowsAccessDeniedCreate(error, paths, stage) {
3185
+ return error instanceof PrivateFileError && error.reason === "io-error" && error.win32Code === 5 && error.stage === stage && paths.some((path) => resolve4(path) === error.path);
3186
+ }
3187
+ async function readLockRecord(path, read) {
3188
+ try {
3189
+ return await read();
3190
+ } catch (error) {
3191
+ if (!isWindowsAccessDeniedRead(error, [path]))
3192
+ throw error;
3193
+ try {
3194
+ return await read();
3195
+ } catch (recheckError) {
3196
+ if (recheckError.code === "ENOENT")
3197
+ throw new DisappearedLockRecordError(path, error);
3198
+ throw error;
3199
+ }
3200
+ }
3201
+ }
3202
+
3203
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/with-lock.js
3204
+ import { join as join3, resolve as resolve5 } from "node:path";
2603
3205
  function lockPathFor(target, name) {
2604
3206
  return `${target}.${name}.lock`;
2605
3207
  }
@@ -2621,18 +3223,17 @@ class LockOwnershipError extends Error {
2621
3223
  this.details = details;
2622
3224
  }
2623
3225
  }
2624
- function isChangingLockRead(error, target, name) {
2625
- if (!isWindowsSharingViolation(error) || error.stage !== "read" && error.stage !== "verify")
2626
- return false;
2627
- const path = resolve4(lockPathFor(target, name));
2628
- return error.path === path || error.path === join3(path, "owner.json");
3226
+ function isChangingLockRecord(error, target, name) {
3227
+ const path = resolve5(lockPathFor(target, name));
3228
+ const paths = [path, join3(path, "owner.json")];
3229
+ return (isWindowsSharingViolation(error) || isWindowsAccessDeniedRead(error, paths)) && (error.stage === "read" || error.stage === "verify") && paths.includes(error.path) || windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [path], "create") || isWindowsAccessDeniedCreate(error, [`${path}.evicting`], "directory-create"));
2629
3230
  }
2630
3231
  async function withLock(target, options, fn) {
2631
3232
  const started = performance.now();
3233
+ let changingRecordError;
2632
3234
  for (;; ) {
2633
3235
  options.signal?.throwIfAborted();
2634
3236
  let lock;
2635
- let changingReadError;
2636
3237
  try {
2637
3238
  lock = await acquireRefreshFileLock({
2638
3239
  path: target,
@@ -2642,11 +3243,12 @@ async function withLock(target, options, fn) {
2642
3243
  ...options.onStep ? { onStep: options.onStep } : {},
2643
3244
  ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
2644
3245
  });
3246
+ changingRecordError = undefined;
2645
3247
  } catch (error) {
2646
- if (!isChangingLockRead(error, target, options.name))
3248
+ if (!isChangingLockRecord(error, target, options.name))
2647
3249
  throw error;
2648
3250
  lock = null;
2649
- changingReadError = error;
3251
+ changingRecordError ??= error;
2650
3252
  }
2651
3253
  if (lock) {
2652
3254
  try {
@@ -2658,8 +3260,8 @@ async function withLock(target, options, fn) {
2658
3260
  }
2659
3261
  const remaining = options.timeoutMs - (performance.now() - started);
2660
3262
  if (remaining <= 0) {
2661
- if (changingReadError)
2662
- throw changingReadError;
3263
+ if (changingRecordError)
3264
+ throw changingRecordError;
2663
3265
  throw new LockContentionError({
2664
3266
  target,
2665
3267
  name: options.name,
@@ -2670,10 +3272,10 @@ async function withLock(target, options, fn) {
2670
3272
  }
2671
3273
  }
2672
3274
 
2673
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
3275
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
2674
3276
  var leaseCreationTestHooks;
2675
3277
  async function createExclusiveText(path, text) {
2676
- const tempPath = `${path}.${randomUUID4()}.tmp`;
3278
+ const tempPath = `${path}.${randomUUID5()}.tmp`;
2677
3279
  let handle;
2678
3280
  try {
2679
3281
  handle = await open2(tempPath, "wx", 384);
@@ -2746,7 +3348,7 @@ function acquireRefreshFileLock(options) {
2746
3348
  async function acquireRefreshFileLockWithClock(options) {
2747
3349
  const lockPath = lockPathFor(options.path, options.name);
2748
3350
  const legacyOwnerPath = join4(lockPath, "owner.json");
2749
- const ownerId = randomUUID4();
3351
+ const ownerId = randomUUID5();
2750
3352
  const now = options.now ?? Date.now;
2751
3353
  let renewTimer = null;
2752
3354
  let released = false;
@@ -2787,18 +3389,21 @@ async function acquireRefreshFileLockWithClock(options) {
2787
3389
  let renewalInFlight = null;
2788
3390
  const evictPath = `${lockPath}.evicting`;
2789
3391
  const evictOwnerPath = join4(evictPath, "owner.json");
2790
- const evictOwnerId = randomUUID4();
3392
+ const evictOwnerId = randomUUID5();
2791
3393
  const EVICT_TTL = 5000;
2792
3394
  const MAX_STEAL_ATTEMPTS = 8;
3395
+ function isChangingLockCreate(error) {
3396
+ return windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [lockPath], "create") || isWindowsAccessDeniedCreate(error, [evictPath], "directory-create"));
3397
+ }
2793
3398
  async function readOwner() {
2794
3399
  if (windowsPrivateFiles) {
2795
3400
  try {
2796
- return JSON.parse(await readPrivateText(lockPath, true));
3401
+ return JSON.parse(await readLockRecord(lockPath, () => readPrivateText(lockPath, true)));
2797
3402
  } catch (error) {
2798
3403
  if (error.code !== "EISDIR" && error.reason !== "wrong-kind")
2799
3404
  throw error;
2800
- await verifyPrivate(lockPath, "directory", true);
2801
- return JSON.parse(await readPrivateText(legacyOwnerPath, true));
3405
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
3406
+ return JSON.parse(await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true)));
2802
3407
  }
2803
3408
  }
2804
3409
  try {
@@ -2829,7 +3434,7 @@ async function acquireRefreshFileLockWithClock(options) {
2829
3434
  });
2830
3435
  return;
2831
3436
  }
2832
- const tempPath = `${lockPath}.${randomUUID4()}.tmp`;
3437
+ const tempPath = `${lockPath}.${randomUUID5()}.tmp`;
2833
3438
  let handle;
2834
3439
  let created = false;
2835
3440
  try {
@@ -2872,8 +3477,8 @@ async function acquireRefreshFileLockWithClock(options) {
2872
3477
  await options.onStep("lease-contention-read-ready");
2873
3478
  try {
2874
3479
  if (code === "EISDIR") {
2875
- await verifyPrivate(lockPath, "directory", true);
2876
- await readPrivateText(legacyOwnerPath, true);
3480
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
3481
+ await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true));
2877
3482
  } else
2878
3483
  await readOwner();
2879
3484
  } catch (readError) {
@@ -2920,6 +3525,8 @@ async function acquireRefreshFileLockWithClock(options) {
2920
3525
  try {
2921
3526
  owner = await readOwner();
2922
3527
  } catch (error) {
3528
+ if (error instanceof DisappearedLockRecordError)
3529
+ return { status: "missing" };
2923
3530
  if (windowsPrivateFiles && error.code !== "ENOENT")
2924
3531
  throw error;
2925
3532
  }
@@ -2967,7 +3574,7 @@ async function acquireRefreshFileLockWithClock(options) {
2967
3574
  }
2968
3575
  async function ownsEvictionMarker() {
2969
3576
  try {
2970
- const owner = JSON.parse(await readPrivateText(evictOwnerPath, windowsPrivateFiles));
3577
+ const owner = JSON.parse(await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, windowsPrivateFiles)));
2971
3578
  return owner?.ownerId === evictOwnerId;
2972
3579
  } catch (error) {
2973
3580
  if (windowsPrivateFiles && error.code !== "ENOENT")
@@ -3105,7 +3712,7 @@ async function acquireRefreshFileLockWithClock(options) {
3105
3712
  }
3106
3713
  if (windowsPrivateFiles) {
3107
3714
  try {
3108
- await verifyPrivate(evictPath, "directory", true);
3715
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
3109
3716
  } catch (error) {
3110
3717
  if (error.code === "ENOENT")
3111
3718
  return "missing";
@@ -3129,7 +3736,7 @@ async function acquireRefreshFileLockWithClock(options) {
3129
3736
  }
3130
3737
  if (options.onStep)
3131
3738
  await options.onStep("stale-marker-stat");
3132
- const claimedPath = `${evictPath}.${randomUUID4()}`;
3739
+ const claimedPath = `${evictPath}.${randomUUID5()}`;
3133
3740
  try {
3134
3741
  await rename3(evictPath, claimedPath);
3135
3742
  } catch (error) {
@@ -3160,8 +3767,8 @@ async function acquireRefreshFileLockWithClock(options) {
3160
3767
  if (error.code === "EEXIST") {
3161
3768
  if (windowsPrivateFiles) {
3162
3769
  try {
3163
- await verifyPrivate(evictPath, "directory", true);
3164
- await readPrivateText(evictOwnerPath, true);
3770
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
3771
+ await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, true));
3165
3772
  } catch (ownerError) {
3166
3773
  if (ownerError.code !== "ENOENT")
3167
3774
  throw ownerError;
@@ -3182,7 +3789,11 @@ async function acquireRefreshFileLockWithClock(options) {
3182
3789
  try {
3183
3790
  await releaseEvictionMarker(deadline);
3184
3791
  } catch (error) {
3185
- if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
3792
+ if ((isRetryableRemoval(actionError, lockPath) || isWindowsAccessDeniedRead(actionError, [
3793
+ lockPath,
3794
+ legacyOwnerPath,
3795
+ evictOwnerPath
3796
+ ])) && (isRetryableRemoval(error, evictPath) || isWindowsAccessDeniedRead(error, [evictOwnerPath])))
3186
3797
  throw actionError;
3187
3798
  throw error;
3188
3799
  }
@@ -3198,7 +3809,7 @@ async function acquireRefreshFileLockWithClock(options) {
3198
3809
  try {
3199
3810
  owner = await readOwner();
3200
3811
  } catch (error) {
3201
- if (windowsPrivateFiles)
3812
+ if (windowsPrivateFiles && !(error instanceof DisappearedLockRecordError))
3202
3813
  throw error;
3203
3814
  return;
3204
3815
  }
@@ -3276,7 +3887,7 @@ async function acquireRefreshFileLockWithClock(options) {
3276
3887
  await options.onStep("renewal-marker-unavailable");
3277
3888
  }
3278
3889
  } catch (error) {
3279
- if (windowsPrivateFiles && error instanceof PrivateFileError) {
3890
+ if (windowsPrivateFiles && error instanceof PrivateFileError && !isChangingLockCreate(error)) {
3280
3891
  terminalIOError = error;
3281
3892
  recordLoss("renewal-failed");
3282
3893
  shouldReschedule = false;
@@ -3319,72 +3930,90 @@ async function acquireRefreshFileLockWithClock(options) {
3319
3930
  } catch {}
3320
3931
  return null;
3321
3932
  }
3322
- let acquired = await tryAcquire();
3933
+ let acquired = false;
3934
+ let changingCreateError;
3935
+ try {
3936
+ acquired = await tryAcquire();
3937
+ } catch (error) {
3938
+ if (!isChangingLockCreate(error))
3939
+ throw error;
3940
+ changingCreateError = error;
3941
+ }
3323
3942
  if (!acquired) {
3324
3943
  for (let attempt = 0;attempt < MAX_STEAL_ATTEMPTS; attempt++) {
3325
- acquired = await tryAcquire();
3326
- if (acquired)
3327
- break;
3328
- const observed = await readLockState();
3329
- if (observed.status === "live")
3330
- return contended();
3331
- if (observed.status === "missing")
3332
- continue;
3333
- if (options.onStep)
3334
- await options.onStep("stale-lock-observed");
3335
3944
  try {
3336
- if (!await tryAcquireEvictionMarker()) {
3337
- await backoff();
3338
- continue;
3339
- }
3340
- } catch (evictError) {
3341
- const code = evictError.code;
3342
- if (code !== "EEXIST")
3343
- throw evictError;
3344
- const recovered = await recoverStaleEvictionMarker();
3345
- if (recovered === "fresh")
3346
- return null;
3347
- await backoff();
3348
- continue;
3349
- }
3350
- try {
3351
- const confirmed = await readLockState();
3352
- if (confirmed.status === "live")
3945
+ acquired = await tryAcquire();
3946
+ if (acquired)
3947
+ break;
3948
+ const observed = await readLockState();
3949
+ if (observed.status === "live")
3353
3950
  return contended();
3354
- if (!sameStaleLock(observed.identity, confirmed))
3951
+ if (observed.status === "missing")
3355
3952
  continue;
3356
- if (!await ownsEvictionMarker())
3357
- return null;
3358
3953
  if (options.onStep)
3359
- await options.onStep("stale-lock-confirmed");
3360
- if (!await ownsEvictionMarker())
3361
- return null;
3362
- const current = await readLockState(false);
3363
- if (!sameStaleLock(observed.identity, current))
3954
+ await options.onStep("stale-lock-observed");
3955
+ try {
3956
+ if (!await tryAcquireEvictionMarker()) {
3957
+ await backoff();
3958
+ continue;
3959
+ }
3960
+ } catch (evictError) {
3961
+ const code = evictError.code;
3962
+ if (code !== "EEXIST")
3963
+ throw evictError;
3964
+ const recovered = await recoverStaleEvictionMarker();
3965
+ if (recovered === "fresh")
3966
+ return null;
3967
+ await backoff();
3364
3968
  continue;
3365
- await removeLeaseObject(lockPath);
3366
- if (!await ownsEvictionMarker())
3367
- return null;
3368
- if (options.onStep)
3369
- await options.onStep("stale-lock-removed");
3370
- acquired = await tryAcquire();
3371
- if (!acquired)
3372
- return null;
3373
- if (options.onStep)
3374
- await options.onStep("stale-lock-recreated");
3375
- if (!await ownsEvictionMarker()) {
3376
- await relinquishLockAfterMarkerLoss();
3377
- acquired = false;
3378
- return null;
3379
3969
  }
3380
- break;
3381
- } finally {
3382
- await releaseEvictionMarker();
3970
+ try {
3971
+ const confirmed = await readLockState();
3972
+ if (confirmed.status === "live")
3973
+ return contended();
3974
+ if (!sameStaleLock(observed.identity, confirmed))
3975
+ continue;
3976
+ if (!await ownsEvictionMarker())
3977
+ return null;
3978
+ if (options.onStep)
3979
+ await options.onStep("stale-lock-confirmed");
3980
+ if (!await ownsEvictionMarker())
3981
+ return null;
3982
+ const current = await readLockState(false);
3983
+ if (!sameStaleLock(observed.identity, current))
3984
+ continue;
3985
+ await removeLeaseObject(lockPath);
3986
+ if (!await ownsEvictionMarker())
3987
+ return null;
3988
+ if (options.onStep)
3989
+ await options.onStep("stale-lock-removed");
3990
+ acquired = await tryAcquire();
3991
+ if (!acquired)
3992
+ return null;
3993
+ if (options.onStep)
3994
+ await options.onStep("stale-lock-recreated");
3995
+ if (!await ownsEvictionMarker()) {
3996
+ await relinquishLockAfterMarkerLoss();
3997
+ acquired = false;
3998
+ return null;
3999
+ }
4000
+ break;
4001
+ } finally {
4002
+ await releaseEvictionMarker();
4003
+ }
4004
+ } catch (error) {
4005
+ if (!isChangingLockCreate(error))
4006
+ throw error;
4007
+ changingCreateError ??= error;
4008
+ await backoff();
3383
4009
  }
3384
4010
  }
3385
4011
  }
3386
- if (!acquired)
4012
+ if (!acquired) {
4013
+ if (changingCreateError)
4014
+ throw changingCreateError;
3387
4015
  return null;
4016
+ }
3388
4017
  scheduleRenewal();
3389
4018
  return {
3390
4019
  ownerId,
@@ -3422,6 +4051,7 @@ async function acquireRefreshFileLockWithClock(options) {
3422
4051
  const deadline = performance.now() + EVICT_TTL + 1000;
3423
4052
  let delayMs = 5;
3424
4053
  let removalError;
4054
+ let changingRecordError;
3425
4055
  for (;; ) {
3426
4056
  try {
3427
4057
  let removalConfirmed = false;
@@ -3447,6 +4077,7 @@ async function acquireRefreshFileLockWithClock(options) {
3447
4077
  await removeLeaseObject(lockPath);
3448
4078
  removalConfirmed = true;
3449
4079
  }, deadline);
4080
+ changingRecordError = undefined;
3450
4081
  if (markerAcquired) {
3451
4082
  if (windowsPrivateFiles && !removalConfirmed)
3452
4083
  throw new PrivateFileError(lockPath, "release-not-confirmed", {
@@ -3459,12 +4090,21 @@ async function acquireRefreshFileLockWithClock(options) {
3459
4090
  return;
3460
4091
  await recoverStaleEvictionMarker(deadline);
3461
4092
  } catch (error) {
3462
- if (!isRetryableRemoval(error, lockPath)) {
4093
+ const changingRecord = windowsPrivateFiles && (isChangingLockCreate(error) || isWindowsAccessDeniedRead(error, [
4094
+ lockPath,
4095
+ legacyOwnerPath,
4096
+ evictPath,
4097
+ evictOwnerPath
4098
+ ]));
4099
+ if (!isRetryableRemoval(error, lockPath) && !changingRecord) {
3463
4100
  if (windowsPrivateFiles)
3464
4101
  throw error;
3465
4102
  return;
3466
4103
  }
3467
- removalError ??= error;
4104
+ if (changingRecord)
4105
+ changingRecordError ??= error;
4106
+ else
4107
+ removalError ??= error;
3468
4108
  }
3469
4109
  const remainingMs = deadline - performance.now();
3470
4110
  if (remainingMs <= 0)
@@ -3475,13 +4115,13 @@ async function acquireRefreshFileLockWithClock(options) {
3475
4115
  delayMs = Math.min(delayMs * 2, 50);
3476
4116
  }
3477
4117
  if (windowsPrivateFiles)
3478
- throw removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
4118
+ throw changingRecordError ?? removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
3479
4119
  code: "ETIMEDOUT"
3480
4120
  });
3481
4121
  }
3482
4122
  };
3483
4123
  }
3484
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/quota/map.js
4124
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/quota/map.js
3485
4125
  var ALL_SCOPE = "all";
3486
4126
  var DEFAULT_REQUIRED_LABELS = Object.freeze([
3487
4127
  "primary"
@@ -3581,7 +4221,7 @@ function isQuotaMap(value) {
3581
4221
  return optional(value, "budget", isCreditBudgetEntry) && optional(value, "counters", isQuotaCounters) && optional(value, "credits", isQuotaCredits);
3582
4222
  }
3583
4223
 
3584
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/quota/merge.js
4224
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/quota/merge.js
3585
4225
  class QuotaCodecError extends TypeError {
3586
4226
  constructor(message) {
3587
4227
  super(message);
@@ -3727,15 +4367,15 @@ function mergeQuotaObservation(stored, observation) {
3727
4367
  };
3728
4368
  }
3729
4369
 
3730
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/quota/codec.js
4370
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/quota/codec.js
3731
4371
  var quotaCodec = Object.freeze({
3732
4372
  validate: isQuotaMap,
3733
4373
  decode: decodeQuotaMap,
3734
4374
  merge: mergeQuotaObservation
3735
4375
  });
3736
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/quota/format.js
4376
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/quota/format.js
3737
4377
  var QUOTA_STALE_AFTER_MS = 15 * 60000;
3738
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/errors.js
4378
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/errors.js
3739
4379
  class ClaustrumConsumerError extends Error {
3740
4380
  kind;
3741
4381
  constructor(kind, message) {
@@ -3745,7 +4385,7 @@ class ClaustrumConsumerError extends Error {
3745
4385
  }
3746
4386
  }
3747
4387
 
3748
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/interlock.js
4388
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/interlock.js
3749
4389
  function matches(entry, credentialId, accountIdentity) {
3750
4390
  if (entry.accountIdentity !== undefined && accountIdentity !== undefined)
3751
4391
  return entry.accountIdentity === accountIdentity;
@@ -3768,14 +4408,14 @@ function acceptAccount(entries, credentialIds, accountIdentity) {
3768
4408
  return entries.filter((entry) => !credentialIds.some((id) => matches(entry, id, accountIdentity)));
3769
4409
  }
3770
4410
 
3771
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/quota-writer.js
3772
- import { resolve as resolve6 } from "node:path";
3773
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/logger/engine.js
4411
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/quota-writer.js
4412
+ import { resolve as resolve7 } from "node:path";
4413
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/logger/engine.js
3774
4414
  import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
3775
4415
  import { open as open3 } from "node:fs/promises";
3776
- import { dirname as dirname5, resolve as resolve5 } from "node:path";
4416
+ import { dirname as dirname5, resolve as resolve6 } from "node:path";
3777
4417
 
3778
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/logger/redact.js
4418
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/logger/redact.js
3779
4419
  var SECRET_KEY_EXACT = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
3780
4420
  var TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;
3781
4421
  var MASK = "***REDACTED***";
@@ -3838,7 +4478,7 @@ var defaultRedactor = createRedactor();
3838
4478
  var redact = defaultRedactor.redact;
3839
4479
  var redactStrings = defaultRedactor.redactStrings;
3840
4480
 
3841
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/logger/engine.js
4481
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/logger/engine.js
3842
4482
  var ORDER = {
3843
4483
  error: 0,
3844
4484
  warn: 1,
@@ -3896,7 +4536,7 @@ async function openWindowsFile(sink, file) {
3896
4536
  return sink.handle;
3897
4537
  }
3898
4538
  async function flushWindowsFile(sink, file, text) {
3899
- file = resolve5(file);
4539
+ file = resolve6(file);
3900
4540
  try {
3901
4541
  if (sink.file !== file)
3902
4542
  await closeWindowsFile(sink);
@@ -4105,7 +4745,7 @@ var defaultEngine = createEngine();
4105
4745
  function createLogger(channel) {
4106
4746
  return defaultEngine.createLogger(channel);
4107
4747
  }
4108
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/quota/commit-interval.js
4748
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/quota/commit-interval.js
4109
4749
  var QUOTA_COMMIT_INTERVAL_MS = 30000;
4110
4750
  var quotaCommitTimer = {
4111
4751
  now: () => performance.now(),
@@ -4118,7 +4758,7 @@ var quotaCommitTimer = {
4118
4758
  }
4119
4759
  };
4120
4760
 
4121
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/quota/pending.js
4761
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/quota/pending.js
4122
4762
  function quotaFields(publication, witness = "") {
4123
4763
  const result = new Map;
4124
4764
  const { observation } = publication;
@@ -4166,12 +4806,12 @@ function quotaFields(publication, witness = "") {
4166
4806
  return result;
4167
4807
  }
4168
4808
 
4169
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/quota-writer.js
4809
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/quota-writer.js
4170
4810
  var writers = new Map;
4171
4811
  var logger = createLogger("claustrum");
4172
4812
  var COALESCE_MS = 100;
4173
4813
  function writerFor(path, clock = quotaCommitTimer) {
4174
- const key = resolve6(path);
4814
+ const key = resolve7(path);
4175
4815
  let writer = writers.get(key);
4176
4816
  if (!writer) {
4177
4817
  writer = {
@@ -4235,7 +4875,7 @@ function orderedFields(pending) {
4235
4875
  return [...pending.values()].flatMap((account) => [...account.values()]).sort((a, b) => a.order - b.order);
4236
4876
  }
4237
4877
  function pendingVaultQuota(path, roster) {
4238
- const writer = writers.get(resolve6(path));
4878
+ const writer = writers.get(resolve7(path));
4239
4879
  if (writer) {
4240
4880
  for (const field of orderedFields(writer.pending)) {
4241
4881
  if (field.priorReading)
@@ -4246,7 +4886,7 @@ function pendingVaultQuota(path, roster) {
4246
4886
  return roster;
4247
4887
  }
4248
4888
  function hasPendingVaultQuota(path) {
4249
- return !!writers.get(resolve6(path))?.pending.size;
4889
+ return !!writers.get(resolve7(path))?.pending.size;
4250
4890
  }
4251
4891
  function schedule(writer, delay) {
4252
4892
  if (writer.running || writer.timer || !writer.pending.size || writer.abort.signal.aborted)
@@ -4311,7 +4951,7 @@ function flush(writer) {
4311
4951
  return writer.running;
4312
4952
  }
4313
4953
  async function drainVaultQuota(path, timeoutMs = 1000) {
4314
- const key = resolve6(path);
4954
+ const key = resolve7(path);
4315
4955
  const writer = writers.get(key);
4316
4956
  if (!writer)
4317
4957
  return;
@@ -4351,7 +4991,7 @@ async function drainVaultQuota(path, timeoutMs = 1000) {
4351
4991
  }
4352
4992
  }
4353
4993
 
4354
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/roster.js
4994
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/roster.js
4355
4995
  function vaultRosterSeed(roster) {
4356
4996
  return {
4357
4997
  declined: roster.declined.map((entry) => ({ ...entry })),
@@ -4769,16 +5409,16 @@ function applyVaultQuota(current, input) {
4769
5409
  }
4770
5410
  var pendingDiscoveries = new Map;
4771
5411
  function forgetPendingVaultDiscovery(path) {
4772
- pendingDiscoveries.delete(resolve7(path));
5412
+ pendingDiscoveries.delete(resolve8(path));
4773
5413
  }
4774
5414
  function isVaultRosterLockRefusal(path, error) {
4775
- const target = resolve7(path);
5415
+ const target = resolve8(path);
4776
5416
  if (error instanceof ClaustrumConsumerError)
4777
5417
  return error.kind === "roster-busy";
4778
5418
  if (error instanceof LockContentionError || error instanceof LockOwnershipError)
4779
- return resolve7(error.details.target) === target;
5419
+ return resolve8(error.details.target) === target;
4780
5420
  if (error instanceof PrivateFileError) {
4781
- const failed = resolve7(error.path);
5421
+ const failed = resolve8(error.path);
4782
5422
  return [WRITE_LOCK.name, DISCOVERY_LEASE.name].some((name) => {
4783
5423
  const lock = lockPathFor(target, name);
4784
5424
  return failed === lock || failed.startsWith(`${lock}.`);
@@ -4839,7 +5479,7 @@ async function refreshVaultRoster(options) {
4839
5479
  throw new ClaustrumConsumerError("roster-busy", "Claustrum account discovery is already in progress");
4840
5480
  return persisted;
4841
5481
  }
4842
- const key = resolve7(options.path);
5482
+ const key = resolve8(options.path);
4843
5483
  const listedOver = options.listedOver;
4844
5484
  let discovered;
4845
5485
  try {
@@ -4897,7 +5537,7 @@ async function refreshVaultRoster(options) {
4897
5537
  }
4898
5538
  }
4899
5539
 
4900
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/limits/vault-adapter.js
5540
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/vault-adapter.js
4901
5541
  function bindingsOf(namespace, roster) {
4902
5542
  return (roster?.rows ?? []).map((row) => ({
4903
5543
  account: {
@@ -4911,7 +5551,7 @@ function bindingsOf(namespace, roster) {
4911
5551
  }
4912
5552
  async function createVaultLimitsAdapter(options) {
4913
5553
  const { namespace, path } = options;
4914
- const generation = randomUUID5();
5554
+ const generation = randomUUID6();
4915
5555
  let history = new EnvelopeHistory;
4916
5556
  const guard = new EnvelopeGuard(namespace, options.logger);
4917
5557
  const repair = new EnvelopeRepair(options.logger);
@@ -4992,7 +5632,7 @@ async function createVaultLimitsAdapter(options) {
4992
5632
  await read();
4993
5633
  return adapter;
4994
5634
  }
4995
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/redaction/index.js
5635
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/redaction/index.js
4996
5636
  import { types } from "node:util";
4997
5637
  var escapedErrorField = /"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i;
4998
5638
  var escapedErrorType = /"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;
@@ -5585,7 +6225,7 @@ async function createAccountLimits(options, acquire = acquireLimitsRegistry, war
5585
6225
  options.provider,
5586
6226
  canonicalLimitsPath(options.path)
5587
6227
  ]);
5588
- const producerId = randomUUID6();
6228
+ const producerId = randomUUID7();
5589
6229
  let adapter;
5590
6230
  let hydrated;
5591
6231
  let registry;
@@ -5801,7 +6441,7 @@ async function createAccountLimits(options, acquire = acquireLimitsRegistry, war
5801
6441
  registry.enqueue({
5802
6442
  ...observation,
5803
6443
  producerId,
5804
- operationId: randomUUID6(),
6444
+ operationId: randomUUID7(),
5805
6445
  type: "mark",
5806
6446
  ...target,
5807
6447
  until: mark.until,
@@ -5820,7 +6460,7 @@ async function createAccountLimits(options, acquire = acquireLimitsRegistry, war
5820
6460
  clearLimitsAfterProbe(registry, {
5821
6461
  ...observation,
5822
6462
  producerId,
5823
- operationId: randomUUID6(),
6463
+ operationId: randomUUID7(),
5824
6464
  keys: [target],
5825
6465
  evidenceAt: observation.observedAt,
5826
6466
  cause
@@ -5847,7 +6487,7 @@ function limitRefusal(decision, host, now) {
5847
6487
  throw new Error("claustrum-auth: unsupported limit refusal");
5848
6488
  return localLimitRefusal(new Response(wire.body, { status: wire.status, headers: wire.headers }), wire.hostRetry);
5849
6489
  }
5850
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/routing/sticky.js
6490
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/routing/sticky.js
5851
6491
  var QUOTA_STALENESS_MS = 15 * 60000;
5852
6492
  var MIN_RESET_HOURS = 1 / 60;
5853
6493
  // ../core/src/serving.ts
@@ -5921,9 +6561,10 @@ function createFetch(options) {
5921
6561
  const tried = new Set;
5922
6562
  const rejected = new Set;
5923
6563
  const secrets = [];
6564
+ let redirectBilling;
5924
6565
  let pending;
5925
6566
  let history = createRequestHistory({
5926
- requestId: randomUUID7(),
6567
+ requestId: randomUUID8(),
5927
6568
  originalUrl: url.href,
5928
6569
  clockNow: now()
5929
6570
  });
@@ -6030,7 +6671,20 @@ function createFetch(options) {
6030
6671
  credentials: template.credentials,
6031
6672
  cache: template.cache
6032
6673
  });
6033
- return options.fetch(outbound);
6674
+ let billing;
6675
+ try {
6676
+ const reply = await options.fetch(outbound);
6677
+ if (options.billing && [301, 302, 303, 307, 308].includes(reply.status) && reply.headers.has("location")) {
6678
+ redirectBilling = { receipt, status: reply.status };
6679
+ return reply;
6680
+ }
6681
+ billing = options.billing?.(receipt);
6682
+ return observeBillingResponse(billing, reply);
6683
+ } catch (error) {
6684
+ const failedBilling = billing ?? options.billing?.(receipt);
6685
+ failedBilling?.end(false, false);
6686
+ throw error;
6687
+ }
6034
6688
  }, { site: "claustrum-auth", signal });
6035
6689
  signal.throwIfAborted();
6036
6690
  const location = response.headers.get("location");
@@ -6046,6 +6700,7 @@ function createFetch(options) {
6046
6700
  await response.body?.cancel().catch(() => {});
6047
6701
  throw new ClaustrumAuthError("redirect-limit");
6048
6702
  }
6703
+ redirectBilling = undefined;
6049
6704
  await response.body?.cancel().catch(() => {});
6050
6705
  if (response.status === 303 && method !== "HEAD" || [301, 302].includes(response.status) && method === "POST") {
6051
6706
  method = "GET";
@@ -6053,6 +6708,11 @@ function createFetch(options) {
6053
6708
  }
6054
6709
  target = next;
6055
6710
  }
6711
+ if (redirectBilling) {
6712
+ const billing = options.billing?.(redirectBilling.receipt);
6713
+ redirectBilling = undefined;
6714
+ response = observeBillingResponse(billing, response);
6715
+ }
6056
6716
  const parsed = await limitFromReply({
6057
6717
  account: observation?.binding.account ?? initial.account,
6058
6718
  service: options.entry.service,
@@ -6090,15 +6750,17 @@ function createFetch(options) {
6090
6750
  };
6091
6751
  }
6092
6752
  } catch (error) {
6753
+ if (redirectBilling)
6754
+ options.billing?.(redirectBilling.receipt)?.end(false, false, redirectBilling.status);
6093
6755
  await pending?.response.body?.cancel().catch(() => {});
6094
6756
  throw redactError(error, secrets);
6095
6757
  }
6096
6758
  };
6097
6759
  }
6098
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/index.js
6760
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/index.js
6099
6761
  import { ClaustrumClient } from "@cortexkit/claustrum-client";
6100
6762
 
6101
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/availability.js
6763
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/availability.js
6102
6764
  import { ClaustrumCredentialError } from "@cortexkit/claustrum-client";
6103
6765
  import { SocketClosedError, SocketTimeoutError, SubcCallError } from "@cortexkit/subc-client";
6104
6766
  var VAULT_FAILURE_CLASSES = Object.freeze({
@@ -6175,9 +6837,12 @@ var VAULT_FAILURE_CLASSES = Object.freeze({
6175
6837
  });
6176
6838
 
6177
6839
  class ClaustrumUnreachableError extends ClaustrumConsumerError {
6178
- constructor() {
6840
+ reason;
6841
+ constructor(reason) {
6179
6842
  super("unavailable", "Claustrum scoped operation unavailable");
6180
6843
  this.name = "ClaustrumUnreachableError";
6844
+ if (reason === "host-accessor-missing" || reason === "host-accessor-failed")
6845
+ this.reason = reason;
6181
6846
  }
6182
6847
  }
6183
6848
  function classifyVaultFailure(error) {
@@ -6189,12 +6854,12 @@ function classifyVaultFailure(error) {
6189
6854
  return VAULT_FAILURE_CLASSES[code];
6190
6855
  }
6191
6856
 
6192
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/insula.js
6193
- import { resolve as resolve8 } from "node:path";
6857
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/insula.js
6858
+ import { resolve as resolve9 } from "node:path";
6194
6859
  import { storeIdentity } from "@cortexkit/claustrum-client";
6195
6860
  import { SubcClient } from "@cortexkit/subc-client";
6196
6861
 
6197
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/watch.js
6862
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/watch.js
6198
6863
  var SAFETY_POLL_MS = 5 * 60000;
6199
6864
  var WATCH_RETRY_MS = 5 * 60000;
6200
6865
  var RESUBSCRIBE_BACKOFF_MS = 1000;
@@ -6390,7 +7055,7 @@ class ScopedRosterWatch {
6390
7055
  }
6391
7056
  }
6392
7057
 
6393
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/insula.js
7058
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/insula.js
6394
7059
  function insulaUsageTransport(options) {
6395
7060
  const identity = options.identity ?? storeIdentity(options.projectRoot ?? process.cwd(), options.storagePath ?? process.cwd());
6396
7061
  return {
@@ -6491,7 +7156,7 @@ var MAX_AGE = 4 * MINUTE;
6491
7156
  var COLD_WAIT = 2 * MINUTE;
6492
7157
  var sources = new Map;
6493
7158
  var attempts = new Map;
6494
- function record2(value) {
7159
+ function record3(value) {
6495
7160
  return typeof value === "object" && value !== null && !Array.isArray(value);
6496
7161
  }
6497
7162
  function decodeUsageNotice(body) {
@@ -6501,7 +7166,7 @@ function decodeUsageNotice(body) {
6501
7166
  } catch {
6502
7167
  return;
6503
7168
  }
6504
- if (!record2(value) || typeof value.kind !== "string" || typeof value.epoch !== "string" || value.epoch.length === 0 || typeof value.seq !== "number" || !Number.isSafeInteger(value.seq) || value.seq < 1 || value.provider !== undefined && typeof value.provider !== "string")
7169
+ if (!record3(value) || typeof value.kind !== "string" || typeof value.epoch !== "string" || value.epoch.length === 0 || typeof value.seq !== "number" || !Number.isSafeInteger(value.seq) || value.seq < 1 || value.provider !== undefined && typeof value.provider !== "string")
6505
7170
  return;
6506
7171
  return {
6507
7172
  kind: value.kind,
@@ -6524,9 +7189,9 @@ class InsulaQuotaSource {
6524
7189
  #reads = new CoalescedRead(async () => {
6525
7190
  try {
6526
7191
  const reply = await this.transport.getUsage();
6527
- if (!record2(reply) || !Array.isArray(reply.result) || reply.error !== undefined)
7192
+ if (!record3(reply) || !Array.isArray(reply.result) || reply.error !== undefined)
6528
7193
  throw new Error("unavailable insula usage");
6529
- this.#entries = reply.result.filter((entry) => record2(entry) && typeof entry.provider === "string");
7194
+ this.#entries = reply.result.filter((entry) => record3(entry) && typeof entry.provider === "string");
6530
7195
  this.#available = this.#entries.length === reply.result.length && (reply.completeProviders === undefined || Array.isArray(reply.completeProviders) && reply.completeProviders.every((value) => typeof value === "string"));
6531
7196
  this.#completeProviders = new Set(this.#available && Array.isArray(reply.completeProviders) ? reply.completeProviders : []);
6532
7197
  for (const provider of this.#completeProviders)
@@ -6674,7 +7339,7 @@ class InsulaQuotaSource {
6674
7339
  for (const entry of this.#entries) {
6675
7340
  if (entry.provider !== provider || typeof entry.account !== "string" || entry.account.trim() !== accountId)
6676
7341
  continue;
6677
- if (entry.stale !== undefined || entry.errorClass !== undefined || !record2(entry.usage))
7342
+ if (entry.stale !== undefined || entry.errorClass !== undefined || !record3(entry.usage))
6678
7343
  continue;
6679
7344
  const fetchedAt = typeof entry.fetchedAt === "string" ? Date.parse(entry.fetchedAt) : Number.NaN;
6680
7345
  if (!Number.isFinite(fetchedAt) || now - fetchedAt >= MAX_AGE)
@@ -6702,7 +7367,7 @@ class InsulaQuotaSource {
6702
7367
  return { miss: "unreachable" };
6703
7368
  if (entry) {
6704
7369
  const fetchedAt = typeof entry.fetchedAt === "string" ? Date.parse(entry.fetchedAt) : Number.NaN;
6705
- if (!record2(entry.usage) || !Number.isFinite(fetchedAt))
7370
+ if (!record3(entry.usage) || !Number.isFinite(fetchedAt))
6706
7371
  return { miss: "unreachable" };
6707
7372
  const reading = {
6708
7373
  entry,
@@ -6711,7 +7376,7 @@ class InsulaQuotaSource {
6711
7376
  ...typeof entry.source === "string" && { source: entry.source }
6712
7377
  }
6713
7378
  };
6714
- if (entry.stale !== undefined && (!record2(entry.stale) || entry.stale.class !== "local_source_unavailable"))
7379
+ if (entry.stale !== undefined && (!record3(entry.stale) || entry.stale.class !== "local_source_unavailable"))
6715
7380
  return { miss: "upstream-failed", reading };
6716
7381
  return now >= fetchedAt + MAX_AGE || entry.stale !== undefined ? { miss: "stale", reading } : { reading };
6717
7382
  }
@@ -6724,8 +7389,8 @@ class InsulaQuotaSource {
6724
7389
  }
6725
7390
  function acquireInsulaQuotaSource(transport, tokenPath) {
6726
7391
  const key = JSON.stringify([
6727
- resolve8(transport.connectionFile),
6728
- resolve8(tokenPath)
7392
+ resolve9(transport.connectionFile),
7393
+ resolve9(tokenPath)
6729
7394
  ]);
6730
7395
  let shared = sources.get(key);
6731
7396
  if (!shared) {
@@ -6746,10 +7411,10 @@ function acquireInsulaQuotaSource(transport, tokenPath) {
6746
7411
  };
6747
7412
  }
6748
7413
 
6749
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/index.js
7414
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/index.js
6750
7415
  import { ClaustrumCredentialError as ClaustrumCredentialError6 } from "@cortexkit/claustrum-client";
6751
7416
 
6752
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/util/any-signal.js
7417
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/util/any-signal.js
6753
7418
  function combineAbortSignals(signals) {
6754
7419
  const controller = new AbortController;
6755
7420
  const listeners = [];
@@ -6786,17 +7451,17 @@ function combineAbortSignals(signals) {
6786
7451
  return { signal: controller.signal, dispose };
6787
7452
  }
6788
7453
 
6789
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/custody.js
7454
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/custody.js
6790
7455
  import { channel } from "node:diagnostics_channel";
6791
7456
  import { ClaustrumCredentialError as ClaustrumCredentialError5 } from "@cortexkit/claustrum-client";
6792
7457
 
6793
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.js
7458
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.js
6794
7459
  import { constants as fsConstants } from "node:fs";
6795
7460
  import { chmod, mkdir as mkdir3, open as open4, readFile as readFile3, realpath, rename as rename4, stat as stat4, unlink as unlink2 } from "node:fs/promises";
6796
- import { basename as basename2, dirname as dirname6, extname, isAbsolute, join as join5, resolve as resolve9 } from "node:path";
7461
+ import { basename as basename2, dirname as dirname6, extname, isAbsolute, join as join5, resolve as resolve10 } from "node:path";
6797
7462
  import { ClaustrumCredentialError as ClaustrumCredentialError3, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
6798
7463
 
6799
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/host.js
7464
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/host.js
6800
7465
  import { ClaustrumCredentialError as ClaustrumCredentialError2 } from "@cortexkit/claustrum-client";
6801
7466
  var VAULT_HOST_STATUS = "Served by Thalamus";
6802
7467
  var hostClients = new WeakSet;
@@ -6813,7 +7478,7 @@ function hostError(error) {
6813
7478
  if (typeof value.code === "string" && (value.class === "transient" || value.class === "permanent" || value.class === "auth_required" || value.class === "context_overflow") && (value.action === "gone" || value.action === "reauth" || value.action === "retry" || value.action === "reduce_and_retry"))
6814
7479
  return new ClaustrumCredentialError2(value.code, value.class, value.action);
6815
7480
  if (value.name === "ClaustrumUnreachableError" || typeof value.code === "string" && classifyVaultFailure(Object.assign(new Error, { code: value.code })) === "unreachable")
6816
- return new ClaustrumUnreachableError;
7481
+ return new ClaustrumUnreachableError(value.reason === "host-accessor-missing" || value.reason === "host-accessor-failed" ? value.reason : undefined);
6817
7482
  return error;
6818
7483
  }
6819
7484
  function call(operation) {
@@ -6879,17 +7544,18 @@ function connectVaultHost(pluginId) {
6879
7544
  throw new ClaustrumUnreachableError;
6880
7545
  try {
6881
7546
  const accessor = globalThis[Symbol.for("cortexkit.vault")];
6882
- if (typeof accessor !== "function")
6883
- throw new ClaustrumUnreachableError;
6884
- const client = wrapHostClient(accessor(pluginId));
6885
- hostClients.add(client);
6886
- return client;
7547
+ if (typeof accessor === "function") {
7548
+ const client = wrapHostClient(accessor(pluginId));
7549
+ hostClients.add(client);
7550
+ return client;
7551
+ }
6887
7552
  } catch {
6888
- throw new ClaustrumUnreachableError;
7553
+ throw new ClaustrumUnreachableError("host-accessor-failed");
6889
7554
  }
7555
+ throw new ClaustrumUnreachableError("host-accessor-missing");
6890
7556
  }
6891
7557
 
6892
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.js
7558
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.js
6893
7559
  var ENROLLMENT_SCHEMA = 1;
6894
7560
  var ENROLLMENT_FILE_MAX_BYTES = 16 * 1024;
6895
7561
  var TOKEN_RE = /^[0-9a-f]{64}$/;
@@ -6918,7 +7584,7 @@ function hostEnrollmentPaths(input) {
6918
7584
  const override = input.override?.trim();
6919
7585
  if (override && !isAbsolute(override) && !input.cwd)
6920
7586
  throw new ClaustrumConsumerError("invalid-state", "A relative Claustrum enrollment override needs a base directory");
6921
- const tokenPath = override ? isAbsolute(override) ? override : resolve9(input.cwd, override) : join5(input.stateDir, `${input.host}-enrollment.json`);
7587
+ const tokenPath = override ? isAbsolute(override) ? override : resolve10(input.cwd, override) : join5(input.stateDir, `${input.host}-enrollment.json`);
6922
7588
  return getClaustrumEnrollmentPaths(tokenPath);
6923
7589
  }
6924
7590
  function isRecord4(value) {
@@ -7177,10 +7843,10 @@ function statusFromState(state) {
7177
7843
  };
7178
7844
  }
7179
7845
 
7180
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/host-slot.js
7846
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/host-slot.js
7181
7847
  var CUSTODY_PLACEHOLDER_PREFIX = "claustrum-tombstone:v1:";
7182
7848
 
7183
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/shutdown.js
7849
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/shutdown.js
7184
7850
  function shutdownWarning(logger, shutdown) {
7185
7851
  let warned = false;
7186
7852
  return (pendingOperations) => {
@@ -7218,7 +7884,7 @@ async function drainShutdown(pending, onTimeout) {
7218
7884
  }
7219
7885
  }
7220
7886
 
7221
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/usage.js
7887
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/usage.js
7222
7888
  import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
7223
7889
  function plain(value) {
7224
7890
  return value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
@@ -7346,7 +8012,7 @@ class ScopedUsageReporter {
7346
8012
  }
7347
8013
  }
7348
8014
 
7349
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/custody.js
8015
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/custody.js
7350
8016
  function isScopedCredentialRotation(served, current) {
7351
8017
  return current !== undefined && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
7352
8018
  }
@@ -7523,8 +8189,14 @@ class ClaustrumScopedCustody {
7523
8189
  this.#warnShutdown = shutdownWarning(this.#logger);
7524
8190
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
7525
8191
  this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
8192
+ const currentClient = () => this.#client;
7526
8193
  this.#usage = new ScopedUsageReporter({
7527
- client: this.#client,
8194
+ client: {
8195
+ get reportUsageScoped() {
8196
+ const client = currentClient();
8197
+ return client.reportUsageScoped?.bind(client);
8198
+ }
8199
+ },
7528
8200
  owns: (id) => this.#usageServed.has(id),
7529
8201
  token: async () => hasVaultHost() ? "" : checkedEnrollmentToken(await this.#readToken()),
7530
8202
  logger: this.#logger,
@@ -7532,11 +8204,21 @@ class ClaustrumScopedCustody {
7532
8204
  clearTimeout: this.#clearTimeout
7533
8205
  });
7534
8206
  }
8207
+ replaceClient(next) {
8208
+ this.#check();
8209
+ if (next === this.#client)
8210
+ return;
8211
+ if (hasVaultHost() && !isVaultHostClient(next))
8212
+ throw new ClaustrumUnreachableError;
8213
+ this.#client = next;
8214
+ for (const watch of this.#watches)
8215
+ watch.restart();
8216
+ }
7535
8217
  transportLost(error) {
7536
8218
  if (this.#closed || this.#outage)
7537
8219
  return;
7538
8220
  this.#outage = true;
7539
- this.#outageError = error instanceof ClaustrumCredentialError5 ? error : new ClaustrumUnreachableError;
8221
+ this.#outageError = error instanceof ClaustrumCredentialError5 ? error : new ClaustrumUnreachableError(error instanceof ClaustrumUnreachableError ? error.reason : undefined);
7540
8222
  this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
7541
8223
  this.#scheduleProbe();
7542
8224
  }
@@ -7633,7 +8315,7 @@ class ClaustrumScopedCustody {
7633
8315
  if (error instanceof ClaustrumCredentialError5)
7634
8316
  throw error;
7635
8317
  if (classifyVaultFailure(error) === "unreachable")
7636
- throw new ClaustrumUnreachableError;
8318
+ throw new ClaustrumUnreachableError(error instanceof ClaustrumUnreachableError ? error.reason : undefined);
7637
8319
  throw new ClaustrumConsumerError("unavailable", "Claustrum scoped operation unavailable");
7638
8320
  } finally {
7639
8321
  removeAbortListener?.();
@@ -7833,7 +8515,7 @@ class ClaustrumScopedCustody {
7833
8515
  if (kept.since === null)
7834
8516
  kept.since = this.#now();
7835
8517
  const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, "accessToken", { value: kept.attempt.accessToken, enumerable: false }));
7836
- this.#provenance.set(attempt, this.#provenance.get(kept.attempt) ?? { token, client: this.#client });
8518
+ this.#provenance.set(attempt, this.#provenance.get(kept.attempt) ?? { token });
7837
8519
  this.#keptAttempts.set(attempt, routeId);
7838
8520
  return attempt;
7839
8521
  }
@@ -7888,7 +8570,7 @@ class ClaustrumScopedCustody {
7888
8570
  recordVersion: served.recordVersion,
7889
8571
  expiresAtMs
7890
8572
  }, "accessToken", { value: accessToken, enumerable: false }));
7891
- this.#provenance.set(attempt, { token, client: this.#client });
8573
+ this.#provenance.set(attempt, { token });
7892
8574
  return attempt;
7893
8575
  }
7894
8576
  async reportFailure(attempt, status, reporterSource) {
@@ -7913,7 +8595,7 @@ class ClaustrumScopedCustody {
7913
8595
  const pending = this.#reports.get(attempt);
7914
8596
  if (pending)
7915
8597
  return pending;
7916
- const report = this.#call(() => provenance.client.reportAuthFailureScoped({
8598
+ const report = this.#call(() => this.#client.reportAuthFailureScoped({
7917
8599
  credentialId: attempt.credentialId,
7918
8600
  enrollmentToken: provenance.token,
7919
8601
  providerStatus: 401,
@@ -7935,34 +8617,62 @@ class ClaustrumScopedCustody {
7935
8617
  }
7936
8618
  watchRoster(options) {
7937
8619
  this.#check();
7938
- const watch = new ScopedRosterWatch({
7939
- client: this.#client,
7940
- enrollmentToken: () => this.#token(),
7941
- view: options.view ?? (() => this.#discoveredView),
7942
- discover: async (view) => {
7943
- await options.onView(view);
7944
- },
7945
- onRefused: (error) => {
7946
- this.listFailed(error);
7947
- options.onRefused?.(error);
8620
+ const currentView = options.view ?? (() => this.#discoveredView);
8621
+ let discovering;
8622
+ let watch;
8623
+ const create = (resubscribed = false) => {
8624
+ const opened = new ScopedRosterWatch({
8625
+ client: this.#client,
8626
+ enrollmentToken: () => this.#token(),
8627
+ view: () => resubscribed ? undefined : currentView(),
8628
+ discover: async (view) => {
8629
+ while (discovering)
8630
+ await discovering.catch(() => {});
8631
+ if (watch !== opened)
8632
+ return;
8633
+ resubscribed = false;
8634
+ discovering = Promise.resolve().then(() => options.onView(view));
8635
+ try {
8636
+ await discovering;
8637
+ } finally {
8638
+ discovering = undefined;
8639
+ }
8640
+ },
8641
+ onRefused: (error) => {
8642
+ this.listFailed(error);
8643
+ options.onRefused?.(error);
8644
+ },
8645
+ onTransportLost: () => this.transportLost(),
8646
+ onReachable: () => this.reachable(),
8647
+ onError: options.onError,
8648
+ onMode: options.onMode,
8649
+ logger: this.#logger,
8650
+ now: this.#now,
8651
+ setTimeoutImpl: this.#setTimeout,
8652
+ clearTimeoutImpl: this.#clearTimeout
8653
+ });
8654
+ return opened;
8655
+ };
8656
+ watch = create();
8657
+ const tracked = {
8658
+ restart: () => {
8659
+ const previousMode = watch.mode;
8660
+ watch.stop();
8661
+ watch = create(true);
8662
+ if (previousMode !== watch.mode)
8663
+ options.onMode?.(watch.mode);
8664
+ watch.start();
7948
8665
  },
7949
- onTransportLost: () => this.transportLost(),
7950
- onReachable: () => this.reachable(),
7951
- onError: options.onError,
7952
- onMode: options.onMode,
7953
- logger: this.#logger,
7954
- now: this.#now,
7955
- setTimeoutImpl: this.#setTimeout,
7956
- clearTimeoutImpl: this.#clearTimeout
7957
- });
7958
- this.#watches.add(watch);
8666
+ stop: () => watch.stop()
8667
+ };
8668
+ this.#watches.add(tracked);
7959
8669
  watch.start();
7960
8670
  return {
7961
8671
  get mode() {
7962
8672
  return watch.mode;
7963
8673
  },
7964
8674
  close: () => {
7965
- this.#watches.delete(watch);
8675
+ this.#watches.delete(tracked);
7966
8676
  watch.stop();
7967
8677
  }
7968
8678
  };
@@ -8008,7 +8718,7 @@ class ClaustrumScopedCustody {
8008
8718
  }
8009
8719
  }
8010
8720
 
8011
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/consumer.js
8721
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/consumer.js
8012
8722
  var DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
8013
8723
  function unreachableConnect() {
8014
8724
  return new ClaustrumUnreachableError;
@@ -8719,11 +9429,11 @@ class ClaustrumConsumer {
8719
9429
  await this.#disposing;
8720
9430
  }
8721
9431
  }
8722
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/hub.js
9432
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/hub.js
8723
9433
  import { createHash as createHash3 } from "node:crypto";
8724
9434
  import { channel as channel2 } from "node:diagnostics_channel";
8725
9435
  import { readdir, stat as stat5 } from "node:fs/promises";
8726
- import { dirname as dirname7, join as join6, resolve as resolve10 } from "node:path";
9436
+ import { dirname as dirname7, join as join6, resolve as resolve11 } from "node:path";
8727
9437
  var sharedRosters = new Map;
8728
9438
  var FILE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
8729
9439
  var WINDOWS_DEVICE = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/;
@@ -8919,7 +9629,7 @@ class ClaustrumDiscoveryHub {
8919
9629
  };
8920
9630
  const { consumer, hooks } = createHubMember(port, consumerOptions);
8921
9631
  entry.hooks = hooks;
8922
- const path = resolve10(entry.path);
9632
+ const path = resolve11(entry.path);
8923
9633
  const subscribers = sharedRosters.get(path) ?? new Set;
8924
9634
  const install = (roster) => {
8925
9635
  if (entry.closed || this.#active !== true || !this.#current || !this.#live(this.#current) || !hooks.roster() || this.#collides(hooks, roster))
@@ -8950,7 +9660,7 @@ class ClaustrumDiscoveryHub {
8950
9660
  return;
8951
9661
  entry.seen = JSON.stringify(decodedVaultRoster(roster));
8952
9662
  entry.hooks?.install(roster);
8953
- for (const install of sharedRosters.get(resolve10(entry.path)) ?? []) {
9663
+ for (const install of sharedRosters.get(resolve11(entry.path)) ?? []) {
8954
9664
  if (!this.#live(generation))
8955
9665
  return;
8956
9666
  if (install !== entry.receiveRoster)
@@ -9567,7 +10277,7 @@ class ClaustrumDiscoveryHub {
9567
10277
  }
9568
10278
  }
9569
10279
 
9570
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/claustrum/index.js
10280
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/index.js
9571
10281
  var SCOPED_CONNECT_TIMEOUT_MS = 1e4;
9572
10282
  async function connectClaustrumScopedClient(options) {
9573
10283
  const { connectTimeoutMs, ...client } = options;
@@ -9595,12 +10305,12 @@ async function connectClaustrumScopedClient(options) {
9595
10305
  }
9596
10306
  // ../core/src/menu.ts
9597
10307
  import { Readable, Writable } from "node:stream";
9598
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/store/hooks.js
10308
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/store/hooks.js
9599
10309
  import { AsyncLocalStorage } from "node:async_hooks";
9600
10310
  var insideHook = new AsyncLocalStorage;
9601
10311
  var insideCodec = new AsyncLocalStorage;
9602
10312
 
9603
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/store/refresh-lock.js
10313
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/store/refresh-lock.js
9604
10314
  var POOL_LOCK_DEFAULTS = Object.freeze({
9605
10315
  ttlMs: 1e4,
9606
10316
  timeoutMs: 15000,
@@ -9608,15 +10318,15 @@ var POOL_LOCK_DEFAULTS = Object.freeze({
9608
10318
  renew: true
9609
10319
  });
9610
10320
 
9611
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/store/schema.js
10321
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/store/schema.js
9612
10322
  var POOL_KEY = "commonAuthPool";
9613
10323
  var REFRESH_STAMP_TOLERANCE_MS = 5 * 60000;
9614
10324
  var UNSAFE_IDS = new Set(["__proto__", "constructor", "prototype"]);
9615
10325
 
9616
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/store/provider-state.js
10326
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/store/provider-state.js
9617
10327
  var DECLINE_TRANSITION = Symbol.for("@cortexkit/common-auth/store/decline-transition");
9618
10328
 
9619
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/store/settings.js
10329
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/store/settings.js
9620
10330
  var POOL_OWNED_KEYS = Object.freeze([
9621
10331
  "version",
9622
10332
  "accounts",
@@ -9624,9 +10334,9 @@ var POOL_OWNED_KEYS = Object.freeze([
9624
10334
  ]);
9625
10335
  var settingsCache = new FileReadCache;
9626
10336
 
9627
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/store/pool.js
10337
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/store/pool.js
9628
10338
  var processMemory = new Map;
9629
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/auth-menu/ansi.js
10339
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/auth-menu/ansi.js
9630
10340
  var ANSI = {
9631
10341
  hide: "\x1B[?25l",
9632
10342
  show: "\x1B[?25h",
@@ -9708,7 +10418,7 @@ function truncateAnsi(input, maxVisibleChars) {
9708
10418
  return output.includes("\x1B[") ? `${output}${ANSI.reset}${suffix}` : output + suffix;
9709
10419
  }
9710
10420
 
9711
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/auth-menu/terminal.js
10421
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/auth-menu/terminal.js
9712
10422
  function processTerminal() {
9713
10423
  return {
9714
10424
  input: process.stdin,
@@ -9724,7 +10434,7 @@ function printLine(terminal, line = "") {
9724
10434
  `);
9725
10435
  }
9726
10436
 
9727
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/auth-menu/select.js
10437
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/auth-menu/select.js
9728
10438
  var ESCAPE_TIMEOUT_MS = 50;
9729
10439
  function colorCode(color) {
9730
10440
  if (color === "red")
@@ -9862,7 +10572,7 @@ async function select(terminal, items, options) {
9862
10572
  });
9863
10573
  }
9864
10574
 
9865
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/auth-menu/confirm.js
10575
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/auth-menu/confirm.js
9866
10576
  async function confirm(terminal, message, defaultYes = false) {
9867
10577
  if (!isInteractive(terminal))
9868
10578
  return false;
@@ -9876,7 +10586,7 @@ async function confirm(terminal, message, defaultYes = false) {
9876
10586
  return await select(terminal, items, { message }) ?? false;
9877
10587
  }
9878
10588
 
9879
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/auth-menu/menu.js
10589
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/auth-menu/menu.js
9880
10590
  function menuContext(terminal) {
9881
10591
  const interactive = isInteractive(terminal);
9882
10592
  return {
@@ -10046,9 +10756,24 @@ async function vaultMenuText(options, args = "") {
10046
10756
  return text.trimEnd();
10047
10757
  }
10048
10758
  // ../core/src/providers.ts
10759
+ var openAIUsage = {
10760
+ input: ["usage.prompt_tokens", "usage.input_tokens"],
10761
+ output: ["usage.completion_tokens", "usage.output_tokens"],
10762
+ cacheRead: [
10763
+ "usage.prompt_tokens_details.cached_tokens",
10764
+ "usage.input_tokens_details.cached_tokens"
10765
+ ],
10766
+ reasoning: [
10767
+ "usage.completion_tokens_details.reasoning_tokens",
10768
+ "usage.output_tokens_details.reasoning_tokens"
10769
+ ],
10770
+ promptIncludesCache: true,
10771
+ reasoningIncludedInOutput: true
10772
+ };
10049
10773
  var supportedProviders = [
10050
10774
  {
10051
10775
  service: "cerebras",
10776
+ billing: { ...openAIUsage, implicitCache: true },
10052
10777
  ids: ["cerebras"],
10053
10778
  hosts: { opencode1: "cerebras", opencode2: "cerebras", pi: "cerebras" },
10054
10779
  class: "A",
@@ -10056,6 +10781,8 @@ var supportedProviders = [
10056
10781
  },
10057
10782
  {
10058
10783
  service: "cline-pass",
10784
+ chargeBasis: "subscription_included",
10785
+ billing: { ...openAIUsage },
10059
10786
  ids: ["cline-pass"],
10060
10787
  credentialIds: ["apikey:cline-pass"],
10061
10788
  hosts: { opencode1: "cline-pass", opencode2: "cline-pass" },
@@ -10064,6 +10791,12 @@ var supportedProviders = [
10064
10791
  },
10065
10792
  {
10066
10793
  service: "deepseek",
10794
+ chargeBasis: "metered_api",
10795
+ billing: {
10796
+ ...openAIUsage,
10797
+ cacheRead: ["usage.prompt_cache_hit_tokens", ...openAIUsage.cacheRead],
10798
+ implicitCache: true
10799
+ },
10067
10800
  ids: ["deepseek"],
10068
10801
  hosts: { opencode1: "deepseek", opencode2: "deepseek", pi: "deepseek" },
10069
10802
  class: "A",
@@ -10071,6 +10804,15 @@ var supportedProviders = [
10071
10804
  },
10072
10805
  {
10073
10806
  service: "fireworks",
10807
+ chargeBasis: "metered_api",
10808
+ billing: {
10809
+ ...openAIUsage,
10810
+ cacheRead: [
10811
+ "perf_metrics.cached-prompt-tokens",
10812
+ ...openAIUsage.cacheRead
10813
+ ],
10814
+ implicitCache: true
10815
+ },
10074
10816
  ids: ["fireworks-ai"],
10075
10817
  hosts: {
10076
10818
  opencode1: "fireworks-ai",
@@ -10082,6 +10824,12 @@ var supportedProviders = [
10082
10824
  },
10083
10825
  {
10084
10826
  service: "inception",
10827
+ chargeBasis: "metered_api",
10828
+ billing: {
10829
+ ...openAIUsage,
10830
+ cacheRead: ["usage.cached_input_tokens", ...openAIUsage.cacheRead],
10831
+ reasoning: ["usage.reasoning_tokens", ...openAIUsage.reasoning]
10832
+ },
10085
10833
  ids: ["inception"],
10086
10834
  hosts: { opencode1: "inception", opencode2: "inception" },
10087
10835
  class: "A",
@@ -10089,6 +10837,12 @@ var supportedProviders = [
10089
10837
  },
10090
10838
  {
10091
10839
  service: "kimi-coding",
10840
+ chargeBasis: "subscription_included",
10841
+ billing: {
10842
+ ...openAIUsage,
10843
+ cacheWrite: ["usage.prompt_tokens_details.cache_write_tokens"],
10844
+ implicitCache: true
10845
+ },
10092
10846
  ids: ["kimi-code-plan-global"],
10093
10847
  hosts: {
10094
10848
  opencode1: "kimi-code-plan-global",
@@ -10100,6 +10854,8 @@ var supportedProviders = [
10100
10854
  },
10101
10855
  {
10102
10856
  service: "minimax-coding-plan",
10857
+ chargeBasis: "subscription_included",
10858
+ billing: { ...openAIUsage, implicitCache: true },
10103
10859
  ids: ["minimax-coding-plan"],
10104
10860
  hosts: { opencode2: "minimax-coding-plan" },
10105
10861
  class: "A",
@@ -10107,6 +10863,7 @@ var supportedProviders = [
10107
10863
  },
10108
10864
  {
10109
10865
  service: "ollama-cloud",
10866
+ billing: { ...openAIUsage },
10110
10867
  ids: ["ollama-cloud"],
10111
10868
  hosts: { opencode1: "ollama-cloud", opencode2: "ollama-cloud" },
10112
10869
  class: "A",
@@ -10114,6 +10871,11 @@ var supportedProviders = [
10114
10871
  },
10115
10872
  {
10116
10873
  service: "openrouter",
10874
+ chargeBasis: "metered_api",
10875
+ billing: {
10876
+ ...openAIUsage,
10877
+ cacheWrite: ["usage.prompt_tokens_details.cache_write_tokens"]
10878
+ },
10117
10879
  ids: ["openrouter"],
10118
10880
  hosts: {
10119
10881
  opencode1: "openrouter",
@@ -10125,6 +10887,7 @@ var supportedProviders = [
10125
10887
  },
10126
10888
  {
10127
10889
  service: "synthetic",
10890
+ billing: { ...openAIUsage },
10128
10891
  ids: ["synthetic"],
10129
10892
  hosts: { opencode1: "synthetic", opencode2: "synthetic" },
10130
10893
  class: "A",
@@ -10132,6 +10895,12 @@ var supportedProviders = [
10132
10895
  },
10133
10896
  {
10134
10897
  service: "typesafe",
10898
+ chargeBasis: "metered_api",
10899
+ billing: {
10900
+ input: ["usage.input_tokens"],
10901
+ output: ["usage.output_tokens"],
10902
+ promptIncludesCache: false
10903
+ },
10135
10904
  ids: ["typesafe"],
10136
10905
  hosts: { opencode1: "typesafe", opencode2: "typesafe" },
10137
10906
  class: "A",
@@ -10139,6 +10908,8 @@ var supportedProviders = [
10139
10908
  },
10140
10909
  {
10141
10910
  service: "meta",
10911
+ chargeBasis: "metered_api",
10912
+ billing: { ...openAIUsage, implicitCache: true },
10142
10913
  ids: ["meta"],
10143
10914
  hosts: { opencode1: "meta", opencode2: "meta", pi: "meta" },
10144
10915
  class: "A",
@@ -10146,6 +10917,8 @@ var supportedProviders = [
10146
10917
  },
10147
10918
  {
10148
10919
  service: "xai",
10920
+ chargeBasis: "metered_api",
10921
+ billing: { ...openAIUsage, implicitCache: true },
10149
10922
  ids: ["xai"],
10150
10923
  hosts: { opencode1: "xai", opencode2: "xai", pi: "xai" },
10151
10924
  class: "A",
@@ -10154,6 +10927,7 @@ var supportedProviders = [
10154
10927
  },
10155
10928
  {
10156
10929
  service: "opencode-go",
10930
+ billing: { ...openAIUsage, opencodeTokens: true },
10157
10931
  ids: ["opencode-go"],
10158
10932
  hosts: {
10159
10933
  opencode1: "opencode-go",
@@ -10165,6 +10939,8 @@ var supportedProviders = [
10165
10939
  },
10166
10940
  {
10167
10941
  service: "opencode-zen",
10942
+ chargeBasis: "metered_api",
10943
+ billing: { ...openAIUsage, opencodeTokens: true },
10168
10944
  ids: ["opencode"],
10169
10945
  hosts: { opencode1: "opencode", pi: "opencode" },
10170
10946
  class: "A",
@@ -10400,14 +11176,14 @@ async function startupStep(step, action) {
10400
11176
  import path2 from "node:path";
10401
11177
  import { resolveClaustrumConnectionPath } from "@cortexkit/claustrum-client";
10402
11178
 
10403
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
11179
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
10404
11180
  import { createHash as createHash4 } from "node:crypto";
10405
11181
  import { constants } from "node:fs";
10406
11182
  import { lstat as lstat4, mkdir as mkdir5, open as open5, unlink as unlink3 } from "node:fs/promises";
10407
- import { dirname as dirname8, resolve as resolve11 } from "node:path";
11183
+ import { dirname as dirname8, resolve as resolve12 } from "node:path";
10408
11184
  import { setTimeout as sleep } from "node:timers/promises";
10409
11185
 
10410
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/pi-slot/lock.js
11186
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/pi-slot/lock.js
10411
11187
  import { rmdirSync, statSync as statSync2, utimesSync } from "node:fs";
10412
11188
  import { mkdir as mkdir4, rmdir, stat as stat6, utimes } from "node:fs/promises";
10413
11189
  var STALE = 30000;
@@ -10599,7 +11375,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
10599
11375
  };
10600
11376
  }
10601
11377
 
10602
- // ../../node_modules/.bun/@cortexkit+common-auth@0.41.1+693d25d9c0e91d8a/node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
11378
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
10603
11379
  class PiSlotError extends Error {
10604
11380
  code;
10605
11381
  constructor(code) {
@@ -10668,13 +11444,13 @@ function rootSpans(text) {
10668
11444
  }
10669
11445
  return root;
10670
11446
  }
10671
- function object(value) {
11447
+ function object2(value) {
10672
11448
  return typeof value === "object" && value !== null && !Array.isArray(value);
10673
11449
  }
10674
11450
  function canonical(value) {
10675
11451
  if (Array.isArray(value))
10676
11452
  return `[${value.map(canonical).join(",")}]`;
10677
- if (object(value)) {
11453
+ if (object2(value)) {
10678
11454
  return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
10679
11455
  }
10680
11456
  return JSON.stringify(value);
@@ -10683,7 +11459,7 @@ function digest(value) {
10683
11459
  return createHash4("sha256").update(canonical(value)).digest("hex");
10684
11460
  }
10685
11461
  function code(error) {
10686
- return object(error) ? error.code : undefined;
11462
+ return object2(error) ? error.code : undefined;
10687
11463
  }
10688
11464
  async function safeRead(path, privateFile = false, afterReadCheck) {
10689
11465
  if (windowsPrivateFiles) {
@@ -10732,7 +11508,7 @@ async function safeRead(path, privateFile = false, afterReadCheck) {
10732
11508
  function parseAuth(text, provider) {
10733
11509
  try {
10734
11510
  const data = JSON.parse(text);
10735
- if (!object(data))
11511
+ if (!object2(data))
10736
11512
  throw new Error;
10737
11513
  const root = rootSpans(text);
10738
11514
  const properties = root.children;
@@ -10741,7 +11517,7 @@ function parseAuth(text, provider) {
10741
11517
  throw new Error;
10742
11518
  const property = properties.find((node) => node.key === provider);
10743
11519
  const entry = property ? data[provider] : null;
10744
- if (entry !== null && !object(entry))
11520
+ if (entry !== null && !object2(entry))
10745
11521
  throw new Error;
10746
11522
  if (property && entry === null)
10747
11523
  throw new Error;
@@ -10807,8 +11583,8 @@ function createPiSlot(options, onStep, hooks) {
10807
11583
  if (!provider || !options.authPath || !options.stashPath || !placeholderKey || placeholderKey.startsWith("!") || placeholderKey.includes("$") || !Number.isFinite(timeout) || timeout < 0) {
10808
11584
  throw new PiSlotError("invalid-options");
10809
11585
  }
10810
- const authPath = resolve11(options.authPath);
10811
- const stashPath = resolve11(options.stashPath);
11586
+ const authPath = resolve12(options.authPath);
11587
+ const stashPath = resolve12(options.stashPath);
10812
11588
  if (authPath === stashPath || stashPath === `${authPath}.lock`) {
10813
11589
  throw new PiSlotError("invalid-options");
10814
11590
  }
@@ -10822,7 +11598,7 @@ function createPiSlot(options, onStep, hooks) {
10822
11598
  return;
10823
11599
  try {
10824
11600
  const stash = JSON.parse(text);
10825
- if (stash.version !== 1 || stash.provider !== provider || stash.authIdentity !== authIdentity || stash.placeholderIdentity !== placeholderIdentity || stash.entry !== null && !object(stash.entry) || stash.sha256 !== digest(stash.entry) || (stash.entry === null ? stash.entryJson !== null : typeof stash.entryJson !== "string" || digest(JSON.parse(stash.entryJson)) !== stash.sha256)) {
11601
+ if (stash.version !== 1 || stash.provider !== provider || stash.authIdentity !== authIdentity || stash.placeholderIdentity !== placeholderIdentity || stash.entry !== null && !object2(stash.entry) || stash.sha256 !== digest(stash.entry) || (stash.entry === null ? stash.entryJson !== null : typeof stash.entryJson !== "string" || digest(JSON.parse(stash.entryJson)) !== stash.sha256)) {
10826
11602
  throw new Error;
10827
11603
  }
10828
11604
  return stash;
@@ -11232,12 +12008,27 @@ class PiRuntime {
11232
12008
  if (options?.apiKey !== served.placeholder)
11233
12009
  return streamSimple(model, context, options);
11234
12010
  const inner = options.fetch ?? globalThis.fetch;
11235
- return streamSimple(model, context, {
12011
+ if (!hasBillingAccessor())
12012
+ return streamSimple(model, context, {
12013
+ ...options,
12014
+ fetch: this.ownedFetch(served, inner)
12015
+ });
12016
+ let current;
12017
+ let attempt = 0;
12018
+ const stream = streamSimple(model, context, {
11236
12019
  ...options,
11237
- fetch: this.ownedFetch(served, inner)
12020
+ fetch: this.ownedFetch(served, inner, (receipt) => {
12021
+ current?.end();
12022
+ if (!hasBillingAccessor())
12023
+ return;
12024
+ current = new BillingAttempt(served.entry, model.provider, options.sessionId ?? this.#ctx.sessionManager.getSessionId(), "primary", model.id, receipt, ++attempt, true);
12025
+ return current;
12026
+ })
11238
12027
  });
12028
+ stream.result().then((message) => current?.piEnd(message.responseId, message.stopReason), () => current?.end());
12029
+ return stream;
11239
12030
  }
11240
- ownedFetch(served, inner) {
12031
+ ownedFetch(served, inner, billing) {
11241
12032
  const serve = createFetch({
11242
12033
  entry: served.entry,
11243
12034
  placeholder: served.placeholder,
@@ -11245,7 +12036,8 @@ class PiRuntime {
11245
12036
  host: "pi",
11246
12037
  fetch: inner,
11247
12038
  rateLimitMarks: served.marks,
11248
- limits: () => this.#core.limits(served.provider)
12039
+ limits: () => this.#core.limits(served.provider),
12040
+ billing
11249
12041
  });
11250
12042
  return async (input, init) => {
11251
12043
  try {