@oxagen/cli 3.0.1-817 → 3.0.1-818

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/oxagen.mjs +1627 -198
  2. package/package.json +1 -1
package/oxagen.mjs CHANGED
@@ -5722,7 +5722,7 @@ function bundleSkillChars(skill) {
5722
5722
  chars += file.path.length + file.content.length;
5723
5723
  return chars;
5724
5724
  }
5725
- var protocolTimestampSchema, machineGroupSchema, TACHO_BATCH_SCHEMA, TACHO_BUNDLE_SCHEMA, TACHO_COMMANDS_SCHEMA, TACHO_ENROLLMENT_CLAIMS_SCHEMA, TACHO_ENROLLMENT_CERTIFICATE_DOMAIN, ENROLLMENT_KEY_SET_SCHEMA, ENROLLMENT_KEY_SET_DOMAIN, TACHO_ENFORCEMENT_TIER_ATTR, TACHO_GATEWAY_TIER, TACHO_GATEWAY_SESSION_HEADER, TACHO_GATEWAY_GENESIS_HEADER, REFUSAL_META_KEY, DECISION_META_KEY, MCP_STREAMABLE_HTTP_ACCEPT, TACHO_METERING_ATTR, TACHO_METERING_OBSERVED, TACHO_MODEL_SESSION_HEADER, TACHO_CREDENTIAL_BASIS_ATTR, TACHO_CREDENTIAL_GATEWAY_BROKERED, TACHO_CREDENTIAL_HARNESS_HELD, TACHO_CREDENTIAL_BASES, TACHO_RUN_TOKEN_ATTR, BUNDLE_FEATURE_GATEWAY_TOOLS, BUNDLE_FEATURE_MODEL_PRICES, BUNDLE_FEATURE_MODEL_PRICES_LONG_CONTEXT, BUNDLE_FEATURE_MODEL_ALLOWLIST, BUNDLE_FEATURE_INDEPENDENT_MODELS, BUNDLE_FEATURE_HOOK_FAIL_OPEN, BUNDLE_FEATURE_STEERING_MANIFEST, BUNDLE_FEATURE_STEERING_INCOMPLETE, BUNDLE_FEATURE_STEERING_LOAD, BUNDLE_FEATURE_CONTAINMENT, BUNDLE_FEATURE_DAILY_BUDGET, BUNDLE_FEATURE_STEER_NEXT_STEP, BUNDLE_FEATURE_UNBOUND_REPO, BUNDLE_FEATURE_CEDAR, BUNDLE_FEATURE_CEDAR_TOOLBELT, BUNDLE_FEATURE_SKILLS, BUNDLE_FEATURE_CACHE_KEEP_ALIVE, BUNDLE_FEATURE_WORK_ORDERS, BUNDLE_FEATURE_WORK_ORDER_START, BUNDLE_FEATURE_WORK_ORDER_STAFFING, BUNDLE_FEATURE_MCP_RULE_SETS, BUNDLE_FEATURE_GATEWAY_POLICY, BUNDLE_FEATURE_TENANT_SCOPE, BUNDLE_FEATURE_MEMORY_SCOPE, MEMORY_SCOPE_DIGESTS_MAX, GATEWAY_MIN_TIERS, SENSITIVE_SCREEN_ACTIONS, PROMPT_REDACTION_PATTERNS_MAX, PROMPT_REDACTION_PATTERN_MAX, gatewayPolicySchema, TACHO_BUNDLE_FEATURES, bundleFeaturesSchema, hostEnrollmentIdSchema, MEMBER_PUBLIC_ID, tachoPlatformSchema, tachoHarnessSchema, TACHO_HARNESS_LABELS, TACHO_HARNESS_TIERS, WRAPPED_HARNESSES, CONNECTED_HARNESSES, HARNESS_BINARY, MODEL_HARNESS_ROUTES, MODEL_ROUTED_HARNESSES, BROKERABLE_HARNESSES, BROKERABLE_HARNESS_PROVIDER, TACHO_TIER_SUMMARY, CUSTOM_AGENT_NAME_PATTERN, RESERVED_AGENT_NAMES, tachoHostStatusSchema, tachoBundleModeSchema, tachoCommandSchema, tachoCommandStatusSchema, tachoCommandAckStatusSchema, tachoDeliveryModeSchema, denyGenerationSchema, deliveredCommandSchema, deliveredCommandResponseSchema, WORK_ORDER_ID_PATTERN, WORK_ORDER_TOKEN_PATTERN, WORK_ITEM_ID_PATTERN, workOrderCommandPayloadSchema, HOST_WORK_ORDERS_PATH, WORK_ORDER_CLAIM_PATH, CERTIFICATE_RENEW_PATH, ENROLLMENT_KEYS_PATH, WORK_ORDER_REJECT_PATH, workOrderClaimResponseSchema, workOrderRejectResponseSchema, WORK_CRITERION_CLAIM_PATH, WORK_CRITERION_ID_PATTERN, WORK_HEAD_SHA_PATTERN, WORK_CRITERION_CLAIM_TEXT_MAX, workCriterionClaimResponseSchema, WORK_ORDER_PROGRESS_PATH, WORK_PROGRESS_TEXT_MAX, WORK_PROGRESS_STEP_MAX, workProgressResponseSchema, WORK_ORDER_ENV, WORK_ORDER_TOKEN_ENV, WORK_ORDER_TOKEN_HEADER, WORK_ORDER_ATTR, steeringForceSchema, steeringItemKindSchema, steeringCutReasonSchema, steeringHeldLoadSchema, steeringManifestItemSchema, STEERING_MANIFEST_SCHEMA, steeringManifestSchema, steeringManifestFrameSchema, workOrderSteeringReasonSchema, workOrderSteeringItemSchema, workOrderSteeringManifestSchema, cedarIdSchema, cedarPrincipalSchema, cedarToolSchema, cedarBundleSchema, BUNDLE_SKILLS_MAX, BUNDLE_SKILL_FILES_MAX, BUNDLE_SKILLS_CHARS_MAX, BASE64_PATTERN, bundleSkillFileSchema, bundleSkillSchema, policyBundleSchema, enrollmentClaimsSchema, ed25519SignatureSchema, enrollmentCertificateSchema, enrollmentKeySchema, enrollmentKeySetSchema, tachoEventWireSchema, TACHO_MAX_HELD_SESSIONS, daemonHealthSchema, TACHO_MAX_BATCH, TACHO_MAX_BODY_BYTES, TACHO_MAX_REQUEST_BYTES, TACHO_REQUEST_ENVELOPE_BYTES, SANDBOX_GIT_RELAY_PATH, SANDBOX_GITLAB_RELAY_PATH, SANDBOX_GIT_RELAY_MAX_REQUEST_BYTES, SANDBOX_GIT_RELAY_TIMEOUT_MS, tachoBodySchema, tachoBatchSchema, agentDaySpendSchema, controlEnvelopeSchema, ingestResponseSchema, bundleResponseSchema, commandAcknowledgementSchema, commandsResponseSchema, certificateRenewalResponseSchema, enrollmentKeysResponseSchema, enrollmentResponseSchema, tokenEnrollmentResponseSchema;
5725
+ var protocolTimestampSchema, machineGroupSchema, TACHO_BATCH_SCHEMA, TACHO_BUNDLE_SCHEMA, TACHO_COMMANDS_SCHEMA, TACHO_ENROLLMENT_CLAIMS_SCHEMA, TACHO_ENROLLMENT_CERTIFICATE_DOMAIN, ENROLLMENT_KEY_SET_SCHEMA, ENROLLMENT_KEY_SET_DOMAIN, TACHO_ENFORCEMENT_TIER_ATTR, TACHO_GATEWAY_TIER, TACHO_GATEWAY_SESSION_HEADER, TACHO_GATEWAY_GENESIS_HEADER, REFUSAL_META_KEY, DECISION_META_KEY, MCP_STREAMABLE_HTTP_ACCEPT, TACHO_METERING_ATTR, TACHO_METERING_OBSERVED, TACHO_MODEL_SESSION_HEADER, TACHO_CREDENTIAL_BASIS_ATTR, TACHO_CREDENTIAL_GATEWAY_BROKERED, TACHO_CREDENTIAL_HARNESS_HELD, TACHO_CREDENTIAL_BASES, TACHO_RUN_TOKEN_ATTR, BUNDLE_FEATURE_GATEWAY_TOOLS, BUNDLE_FEATURE_MODEL_PRICES, BUNDLE_FEATURE_MODEL_PRICES_LONG_CONTEXT, BUNDLE_FEATURE_MODEL_ALLOWLIST, BUNDLE_FEATURE_INDEPENDENT_MODELS, BUNDLE_FEATURE_HOOK_FAIL_OPEN, BUNDLE_FEATURE_STEERING_MANIFEST, BUNDLE_FEATURE_STEERING_INCOMPLETE, BUNDLE_FEATURE_STEERING_LOAD, BUNDLE_FEATURE_CONTAINMENT, BUNDLE_FEATURE_DAILY_BUDGET, BUNDLE_FEATURE_STEER_NEXT_STEP, BUNDLE_FEATURE_UNBOUND_REPO, BUNDLE_FEATURE_CEDAR, BUNDLE_FEATURE_CEDAR_TOOLBELT, BUNDLE_FEATURE_SKILLS, BUNDLE_FEATURE_CACHE_KEEP_ALIVE, BUNDLE_FEATURE_WORK_ORDERS, BUNDLE_FEATURE_WORK_ORDER_START, BUNDLE_FEATURE_WORK_ORDER_STAFFING, BUNDLE_FEATURE_MCP_RULE_SETS, BUNDLE_FEATURE_GATEWAY_POLICY, BUNDLE_FEATURE_TENANT_SCOPE, BUNDLE_FEATURE_MEMORY_SCOPE, MEMORY_SCOPE_DIGESTS_MAX, GATEWAY_MIN_TIERS, SENSITIVE_SCREEN_ACTIONS, PROMPT_REDACTION_PATTERNS_MAX, PROMPT_REDACTION_PATTERN_MAX, gatewayPolicySchema, TACHO_BUNDLE_FEATURES, bundleFeaturesSchema, hostEnrollmentIdSchema, MEMBER_PUBLIC_ID, tachoPlatformSchema, tachoHarnessSchema, TACHO_HARNESS_LABELS, TACHO_HARNESS_TIERS, WRAPPED_HARNESSES, CONNECTED_HARNESSES, HARNESS_BINARY, MODEL_HARNESS_ROUTES, MODEL_ROUTED_HARNESSES, BROKERABLE_HARNESSES, BROKERABLE_HARNESS_PROVIDER, TACHO_TIER_SUMMARY, CUSTOM_AGENT_NAME_PATTERN, RESERVED_AGENT_NAMES, tachoHostStatusSchema, tachoBundleModeSchema, tachoCommandSchema, tachoCommandStatusSchema, tachoCommandAckStatusSchema, tachoDeliveryModeSchema, denyGenerationSchema, deliveredCommandSchema, deliveredCommandResponseSchema, WORK_ORDER_ID_PATTERN, WORK_ORDER_TOKEN_PATTERN, WORK_ITEM_ID_PATTERN, workOrderCommandPayloadSchema, HOST_WORK_ORDERS_PATH, WORK_ORDER_CLAIM_PATH, CERTIFICATE_RENEW_PATH, ENROLLMENT_KEYS_PATH, WORK_ORDER_REJECT_PATH, HOST_MODEL_CREDENTIALS_PATH, HOST_MODEL_CREDENTIAL_STATE_PATH, VAULT_CREDENTIAL_ID_PATTERN, hostModelCredentialSchema, hostModelCredentialsResponseSchema, hostModelCredentialStateResponseSchema, workOrderClaimResponseSchema, workOrderRejectResponseSchema, WORK_CRITERION_CLAIM_PATH, WORK_CRITERION_ID_PATTERN, WORK_HEAD_SHA_PATTERN, WORK_CRITERION_CLAIM_TEXT_MAX, workCriterionClaimResponseSchema, WORK_ORDER_PROGRESS_PATH, WORK_PROGRESS_TEXT_MAX, WORK_PROGRESS_STEP_MAX, workProgressResponseSchema, WORK_ORDER_ENV, WORK_ORDER_TOKEN_ENV, WORK_ORDER_TOKEN_HEADER, WORK_ORDER_ATTR, steeringForceSchema, steeringItemKindSchema, steeringCutReasonSchema, steeringHeldLoadSchema, steeringManifestItemSchema, STEERING_MANIFEST_SCHEMA, steeringManifestSchema, steeringManifestFrameSchema, workOrderSteeringReasonSchema, workOrderSteeringItemSchema, workOrderSteeringManifestSchema, cedarIdSchema, cedarPrincipalSchema, cedarToolSchema, cedarBundleSchema, BUNDLE_SKILLS_MAX, BUNDLE_SKILL_FILES_MAX, BUNDLE_SKILLS_CHARS_MAX, BASE64_PATTERN, bundleSkillFileSchema, bundleSkillSchema, policyBundleSchema, enrollmentClaimsSchema, ed25519SignatureSchema, enrollmentCertificateSchema, enrollmentKeySchema, enrollmentKeySetSchema, tachoEventWireSchema, TACHO_MAX_HELD_SESSIONS, daemonHealthSchema, TACHO_MAX_BATCH, TACHO_MAX_BODY_BYTES, TACHO_MAX_REQUEST_BYTES, TACHO_REQUEST_ENVELOPE_BYTES, SANDBOX_GIT_RELAY_PATH, SANDBOX_GITLAB_RELAY_PATH, SANDBOX_GIT_RELAY_MAX_REQUEST_BYTES, SANDBOX_GIT_RELAY_TIMEOUT_MS, tachoBodySchema, tachoBatchSchema, agentDaySpendSchema, controlEnvelopeSchema, ingestResponseSchema, bundleResponseSchema, commandAcknowledgementSchema, commandsResponseSchema, certificateRenewalResponseSchema, enrollmentKeysResponseSchema, enrollmentResponseSchema, tokenEnrollmentResponseSchema;
5726
5726
  var init_wire = __esm({
5727
5727
  "../../packages/tacho/src/wire.ts"() {
5728
5728
  "use strict";
@@ -5994,6 +5994,27 @@ var init_wire = __esm({
5994
5994
  CERTIFICATE_RENEW_PATH = "/v1/tacho/certificate";
5995
5995
  ENROLLMENT_KEYS_PATH = "/v1/enrollment/keys";
5996
5996
  WORK_ORDER_REJECT_PATH = `${HOST_WORK_ORDERS_PATH}/reject`;
5997
+ HOST_MODEL_CREDENTIALS_PATH = "/v1/tacho/model-credentials";
5998
+ HOST_MODEL_CREDENTIAL_STATE_PATH = `${HOST_MODEL_CREDENTIALS_PATH}/state`;
5999
+ VAULT_CREDENTIAL_ID_PATTERN = /^vlt_[0-9a-z]+$/;
6000
+ hostModelCredentialSchema = external_exports.object({
6001
+ id: external_exports.string().regex(VAULT_CREDENTIAL_ID_PATTERN),
6002
+ provider: external_exports.string(),
6003
+ authType: external_exports.string(),
6004
+ harness: external_exports.string().nullable(),
6005
+ hint: external_exports.string(),
6006
+ label: external_exports.string().nullable(),
6007
+ status: external_exports.string(),
6008
+ limitedUntil: external_exports.string().nullable(),
6009
+ rotatedAt: external_exports.string().nullable(),
6010
+ createdAt: external_exports.string(),
6011
+ secret: external_exports.string().min(1)
6012
+ }).passthrough();
6013
+ hostModelCredentialsResponseSchema = external_exports.object({
6014
+ harness: external_exports.string(),
6015
+ credentials: external_exports.array(hostModelCredentialSchema)
6016
+ }).passthrough();
6017
+ hostModelCredentialStateResponseSchema = external_exports.object({ credential_id: external_exports.string(), recorded: external_exports.boolean() }).passthrough();
5997
6018
  workOrderClaimResponseSchema = external_exports.object({
5998
6019
  repeat: external_exports.boolean(),
5999
6020
  work_order: external_exports.object({
@@ -18362,11 +18383,11 @@ function requestOf(content) {
18362
18383
  if (content === void 0) return void 0;
18363
18384
  if (!content.content_type.startsWith("application/json")) return void 0;
18364
18385
  try {
18365
- const exchange = JSON.parse(
18386
+ const exchange2 = JSON.parse(
18366
18387
  Buffer.from(content.bytes).toString("utf8")
18367
18388
  );
18368
- if (!isObject(exchange)) return "unreadable";
18369
- const text6 = exchange["request"];
18389
+ if (!isObject(exchange2)) return "unreadable";
18390
+ const text6 = exchange2["request"];
18370
18391
  if (typeof text6 !== "string") return "unreadable";
18371
18392
  const request3 = JSON.parse(text6);
18372
18393
  return isObject(request3) ? { text: text6, request: request3 } : "unreadable";
@@ -26189,6 +26210,207 @@ var init_claude_code_mcp = __esm({
26189
26210
  }
26190
26211
  });
26191
26212
 
26213
+ // ../../packages/tacho/src/collector/model-failure.ts
26214
+ function isUsageLimit(failure4) {
26215
+ return failure4.kind === "rate_limit" || failure4.kind === "usage_limit" || failure4.kind === "credit_exhausted";
26216
+ }
26217
+ function mayBeModelFailure(provider, status2) {
26218
+ return status2 === 401 || status2 === 403 || status2 === 429 || provider === "anthropic" && status2 === 400;
26219
+ }
26220
+ function clampUntil(now, waitMs) {
26221
+ const wait = Math.min(Math.max(waitMs, MIN_LIMIT_WAIT_MS), MAX_LIMIT_WAIT_MS);
26222
+ return new Date(now.getTime() + wait);
26223
+ }
26224
+ function retryAfterMs(value, now) {
26225
+ if (value === null) return null;
26226
+ const trimmed = value.trim();
26227
+ if (/^\d+(\.\d+)?$/.test(trimmed)) return Number(trimmed) * 1e3;
26228
+ const at2 = Date.parse(trimmed);
26229
+ return Number.isFinite(at2) ? at2 - now.getTime() : null;
26230
+ }
26231
+ function durationMs(value) {
26232
+ if (value === null) return null;
26233
+ const trimmed = value.trim();
26234
+ if (trimmed.length === 0) return null;
26235
+ const units = {
26236
+ h: 36e5,
26237
+ m: 6e4,
26238
+ s: 1e3,
26239
+ ms: 1
26240
+ };
26241
+ let total2 = 0;
26242
+ let rest = trimmed;
26243
+ while (rest.length > 0) {
26244
+ const match = /^(\d+(?:\.\d+)?)(ms|h|m|s)/.exec(rest);
26245
+ if (!match) return null;
26246
+ total2 += Number(match[1]) * units[match[2]];
26247
+ rest = rest.slice(match[0].length);
26248
+ }
26249
+ return total2;
26250
+ }
26251
+ function latestResetMs(headers, names2, now) {
26252
+ let latest2 = null;
26253
+ for (const name2 of names2) {
26254
+ const at2 = Date.parse(headers.get(name2) ?? "");
26255
+ if (!Number.isFinite(at2)) continue;
26256
+ const wait = at2 - now.getTime();
26257
+ if (latest2 === null || wait > latest2) latest2 = wait;
26258
+ }
26259
+ return latest2;
26260
+ }
26261
+ function longestDurationMs(headers, names2) {
26262
+ let longest = null;
26263
+ for (const name2 of names2) {
26264
+ const wait = durationMs(headers.get(name2));
26265
+ if (wait !== null && (longest === null || wait > longest)) longest = wait;
26266
+ }
26267
+ return longest;
26268
+ }
26269
+ function errorOf(body2) {
26270
+ if (body2 === null) return null;
26271
+ let parsed2;
26272
+ try {
26273
+ parsed2 = JSON.parse(body2);
26274
+ } catch {
26275
+ return null;
26276
+ }
26277
+ if (parsed2 === null || typeof parsed2 !== "object") return null;
26278
+ const error2 = parsed2.error;
26279
+ return error2 !== null && typeof error2 === "object" ? error2 : null;
26280
+ }
26281
+ function stringField(error2, key) {
26282
+ const value = error2?.[key];
26283
+ return typeof value === "string" ? value : null;
26284
+ }
26285
+ function numberField(error2, key) {
26286
+ const value = error2?.[key];
26287
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
26288
+ }
26289
+ function namesShutAccount(error2) {
26290
+ const message2 = stringField(error2, "message");
26291
+ if (message2 === null) return false;
26292
+ return message2.toLowerCase().split(/(?<=[.!?])\s+/).some(
26293
+ (sentence2) => SHUT_ACCOUNT_PHRASES.some(
26294
+ (phrase) => sentence2.trimStart().startsWith(phrase)
26295
+ )
26296
+ );
26297
+ }
26298
+ function anthropicFailure(status2, headers, body2, now) {
26299
+ const error2 = errorOf(body2);
26300
+ if (status2 === 401) return INVALID_TOKEN;
26301
+ if (status2 === 403) return namesShutAccount(error2) ? DEACTIVATED : null;
26302
+ if (status2 === 400) {
26303
+ if (stringField(error2, "type") !== "invalid_request_error") return null;
26304
+ const message2 = stringField(error2, "message")?.toLowerCase() ?? "";
26305
+ if (message2.includes("credit balance")) {
26306
+ return {
26307
+ kind: "credit_exhausted",
26308
+ until: clampUntil(now, DEFAULT_LIMIT_WAIT_MS.credit_exhausted)
26309
+ };
26310
+ }
26311
+ return namesShutAccount(error2) ? DEACTIVATED : null;
26312
+ }
26313
+ if (status2 !== 429) return null;
26314
+ if (headers.get("anthropic-ratelimit-unified-status") === "rejected") {
26315
+ const reset = Number(headers.get("anthropic-ratelimit-unified-reset"));
26316
+ const wait2 = Number.isFinite(reset) && reset > 0 ? reset * 1e3 - now.getTime() : DEFAULT_LIMIT_WAIT_MS.usage_limit;
26317
+ const claim = headers.get("anthropic-ratelimit-unified-representative-claim") ?? "";
26318
+ const modelScoped = /opus|sonnet|haiku/i.test(claim);
26319
+ return {
26320
+ kind: "usage_limit",
26321
+ until: clampUntil(
26322
+ now,
26323
+ modelScoped ? Math.min(wait2, MODEL_SCOPED_HOLD_MS) : wait2
26324
+ )
26325
+ };
26326
+ }
26327
+ const wait = retryAfterMs(headers.get("retry-after"), now) ?? latestResetMs(headers, ANTHROPIC_RESETS, now) ?? DEFAULT_LIMIT_WAIT_MS.rate_limit;
26328
+ return { kind: "rate_limit", until: clampUntil(now, wait) };
26329
+ }
26330
+ function openaiFailure(status2, headers, body2, now) {
26331
+ if (status2 !== 401 && status2 !== 403 && status2 !== 429) return null;
26332
+ const error2 = errorOf(body2);
26333
+ const code = stringField(error2, "code");
26334
+ const type = stringField(error2, "type");
26335
+ if (code !== null && OPENAI_SHUT_CODES.has(code) || type !== null && OPENAI_SHUT_CODES.has(type)) {
26336
+ return DEACTIVATED;
26337
+ }
26338
+ if (status2 === 401) return INVALID_TOKEN;
26339
+ if (status2 === 403) return namesShutAccount(error2) ? DEACTIVATED : null;
26340
+ if (code === "insufficient_quota" || type === "insufficient_quota") {
26341
+ return {
26342
+ kind: "credit_exhausted",
26343
+ until: clampUntil(now, DEFAULT_LIMIT_WAIT_MS.credit_exhausted)
26344
+ };
26345
+ }
26346
+ if (code === "usage_limit_reached" || type === "usage_limit_reached") {
26347
+ const resetsAt = numberField(error2, "resets_at");
26348
+ const resetsIn = numberField(error2, "resets_in_seconds");
26349
+ const wait2 = resetsAt !== null && resetsAt > 0 ? resetsAt * 1e3 - now.getTime() : resetsIn !== null ? resetsIn * 1e3 : DEFAULT_LIMIT_WAIT_MS.usage_limit;
26350
+ return { kind: "usage_limit", until: clampUntil(now, wait2) };
26351
+ }
26352
+ const retryAfterMsHeader = Number(headers.get("retry-after-ms"));
26353
+ const wait = (Number.isFinite(retryAfterMsHeader) && retryAfterMsHeader > 0 ? retryAfterMsHeader : null) ?? retryAfterMs(headers.get("retry-after"), now) ?? longestDurationMs(headers, OPENAI_RESETS) ?? DEFAULT_LIMIT_WAIT_MS.rate_limit;
26354
+ return { kind: "rate_limit", until: clampUntil(now, wait) };
26355
+ }
26356
+ function classifyModelFailure(provider, status2, headers, body2, now) {
26357
+ return provider === "anthropic" ? anthropicFailure(status2, headers, body2, now) : openaiFailure(status2, headers, body2, now);
26358
+ }
26359
+ var MODEL_FAILURE_KINDS, DEFAULT_LIMIT_WAIT_MS, DEAD_CREDENTIAL_HOLD_MS, MODEL_SCOPED_HOLD_MS, MIN_LIMIT_WAIT_MS, MAX_LIMIT_WAIT_MS, MODEL_FAILURE_BODY_MAX_BYTES, SHUT_ACCOUNT_PHRASES, ANTHROPIC_RESETS, OPENAI_RESETS, OPENAI_SHUT_CODES, INVALID_TOKEN, DEACTIVATED;
26360
+ var init_model_failure = __esm({
26361
+ "../../packages/tacho/src/collector/model-failure.ts"() {
26362
+ "use strict";
26363
+ MODEL_FAILURE_KINDS = [
26364
+ "rate_limit",
26365
+ "usage_limit",
26366
+ "credit_exhausted",
26367
+ "invalid_token",
26368
+ "account_deactivated"
26369
+ ];
26370
+ DEFAULT_LIMIT_WAIT_MS = Object.freeze({
26371
+ // A subscription's limit that names no reset is held for an hour, then
26372
+ // asked again.
26373
+ usage_limit: 60 * 6e4,
26374
+ rate_limit: 6e4,
26375
+ // Credit comes back only when someone pays, so an hour between asks.
26376
+ credit_exhausted: 60 * 6e4
26377
+ });
26378
+ DEAD_CREDENTIAL_HOLD_MS = 60 * 6e4;
26379
+ MODEL_SCOPED_HOLD_MS = 60 * 6e4;
26380
+ MIN_LIMIT_WAIT_MS = 1e3;
26381
+ MAX_LIMIT_WAIT_MS = 8 * 24 * 60 * 6e4;
26382
+ MODEL_FAILURE_BODY_MAX_BYTES = 64 * 1024;
26383
+ SHUT_ACCOUNT_PHRASES = Object.freeze([
26384
+ ...["this", "your"].flatMap(
26385
+ (owner) => ["organization", "account"].flatMap(
26386
+ (holder) => ["disabled", "deactivated", "suspended"].map(
26387
+ (state) => `${owner} ${holder} has been ${state}`
26388
+ )
26389
+ )
26390
+ ),
26391
+ "this key is associated with a deactivated account"
26392
+ ]);
26393
+ ANTHROPIC_RESETS = [
26394
+ "anthropic-ratelimit-requests-reset",
26395
+ "anthropic-ratelimit-tokens-reset",
26396
+ "anthropic-ratelimit-input-tokens-reset",
26397
+ "anthropic-ratelimit-output-tokens-reset"
26398
+ ];
26399
+ OPENAI_RESETS = [
26400
+ "x-ratelimit-reset-requests",
26401
+ "x-ratelimit-reset-tokens"
26402
+ ];
26403
+ OPENAI_SHUT_CODES = /* @__PURE__ */ new Set([
26404
+ "account_deactivated",
26405
+ "billing_not_active"
26406
+ ]);
26407
+ INVALID_TOKEN = Object.freeze({ kind: "invalid_token" });
26408
+ DEACTIVATED = Object.freeze({
26409
+ kind: "account_deactivated"
26410
+ });
26411
+ }
26412
+ });
26413
+
26192
26414
  // ../../packages/tacho/src/host/run-token.ts
26193
26415
  import { createHmac, randomBytes as randomBytes4, timingSafeEqual } from "node:crypto";
26194
26416
  import { readFileSync as readFileSync6 } from "node:fs";
@@ -26378,6 +26600,9 @@ import {
26378
26600
  unlinkSync as unlinkSync4,
26379
26601
  writeSync as writeSync3
26380
26602
  } from "node:fs";
26603
+ function isLoginKind(kind) {
26604
+ return kind === "oauth" || kind === "chatgpt";
26605
+ }
26381
26606
  function anthropicCredentialKind(secret, fallback) {
26382
26607
  return secret.trim().startsWith(CLAUDE_OAUTH_TOKEN_PREFIX) ? "oauth" : fallback;
26383
26608
  }
@@ -26390,6 +26615,59 @@ function sealingContext(provider, harness) {
26390
26615
  function matches(entry2, provider, harness) {
26391
26616
  return entry2.provider === provider && harnessOf(entry2) === harness;
26392
26617
  }
26618
+ function isVaultCopy(entry2) {
26619
+ return entry2.source === VAULT_POOL_SOURCE;
26620
+ }
26621
+ function memberIdOf(entry2) {
26622
+ return entry2.credential_id ?? HELD_MEMBER_ID;
26623
+ }
26624
+ function entryContext(entry2) {
26625
+ const slot = sealingContext(entry2.provider, harnessOf(entry2));
26626
+ return isVaultCopy(entry2) ? `${slot}:${entry2.credential_id ?? ""}` : slot;
26627
+ }
26628
+ function slotEntries(entries2, provider, harness) {
26629
+ const slot = entries2.filter((e) => matches(e, provider, harness));
26630
+ return [
26631
+ ...slot.filter((e) => !isVaultCopy(e)),
26632
+ ...slot.filter((e) => isVaultCopy(e))
26633
+ ];
26634
+ }
26635
+ function withSlot(entries2, provider, harness, slot) {
26636
+ const first = entries2.findIndex((e) => matches(e, provider, harness));
26637
+ const rest = entries2.filter((e) => !matches(e, provider, harness));
26638
+ if (first < 0) return [...rest, ...slot];
26639
+ const before = entries2.slice(0, first).filter((e) => !matches(e, provider, harness)).length;
26640
+ return [...rest.slice(0, before), ...slot, ...rest.slice(before)];
26641
+ }
26642
+ function hintOf(kind, secret) {
26643
+ if (kind === "chatgpt") {
26644
+ const account = chatGptAccountOf(secret);
26645
+ return account !== void 0 && account.length >= 8 ? account.slice(-4) : void 0;
26646
+ }
26647
+ const trimmed = secret.trim();
26648
+ return trimmed.length >= 8 ? trimmed.slice(-4) : void 0;
26649
+ }
26650
+ function chatGptAccountOf(secret) {
26651
+ let parsed2;
26652
+ try {
26653
+ parsed2 = JSON.parse(secret);
26654
+ } catch {
26655
+ return void 0;
26656
+ }
26657
+ if (parsed2 === null || typeof parsed2 !== "object") return void 0;
26658
+ const account = parsed2["account_id"];
26659
+ return typeof account === "string" && account.length > 0 ? account : void 0;
26660
+ }
26661
+ function identityOf(kind, secret) {
26662
+ if (kind === "chatgpt") {
26663
+ const account = chatGptAccountOf(secret);
26664
+ if (account !== void 0) return `chatgpt:${account}`;
26665
+ }
26666
+ return `${kind === "chatgpt" ? "chatgpt" : "secret"}:${secret.trim()}`;
26667
+ }
26668
+ function heldBackAt(failure4, now) {
26669
+ return failure4 !== void 0 && Date.parse(failure4.until) > now;
26670
+ }
26393
26671
  function readKey(path2) {
26394
26672
  try {
26395
26673
  const hex = readFileSync7(path2, "utf8").trim();
@@ -26471,6 +26749,40 @@ function custodyOf(entry2) {
26471
26749
  prefix: entry2.prefix
26472
26750
  };
26473
26751
  }
26752
+ function memberOf(entry2) {
26753
+ return {
26754
+ id: memberIdOf(entry2),
26755
+ kind: entry2.kind,
26756
+ source: entry2.source,
26757
+ prefix: entry2.prefix,
26758
+ taken_at: entry2.taken_at,
26759
+ ...entry2.credential_id !== void 0 ? { credential_id: entry2.credential_id } : {},
26760
+ ...entry2.hint !== void 0 ? { hint: entry2.hint } : {},
26761
+ ...entry2.label !== void 0 ? { label: entry2.label } : {},
26762
+ ...entry2.refreshed_at !== void 0 ? { refreshed_at: entry2.refreshed_at } : {},
26763
+ ...entry2.refresh_refused !== void 0 ? { refresh_refused: entry2.refresh_refused } : {},
26764
+ ...entry2.failure !== void 0 ? { failure: { ...entry2.failure } } : {}
26765
+ };
26766
+ }
26767
+ function refreshedSince(entry2, vaultChangedAt) {
26768
+ if (entry2.refreshed_at === void 0) return false;
26769
+ const refreshed = Date.parse(entry2.refreshed_at);
26770
+ const changed = Date.parse(vaultChangedAt);
26771
+ return Number.isFinite(refreshed) && Number.isFinite(changed) && refreshed > changed;
26772
+ }
26773
+ function prefixOf(kind, secret) {
26774
+ return kind === "chatgpt" ? "login" : credentialPrefix(secret);
26775
+ }
26776
+ function mergedFailure(local, limitedUntil, now) {
26777
+ if (limitedUntil === void 0 || limitedUntil <= now) return local;
26778
+ if (local !== void 0 && Date.parse(local.until) >= limitedUntil)
26779
+ return local;
26780
+ return {
26781
+ kind: local?.kind ?? "usage_limit",
26782
+ at: new Date(now).toISOString(),
26783
+ until: new Date(limitedUntil).toISOString()
26784
+ };
26785
+ }
26474
26786
  function openCredentialStore(paths) {
26475
26787
  let entriesSeen;
26476
26788
  let keySeen;
@@ -26531,6 +26843,22 @@ function openCredentialStore(paths) {
26531
26843
  );
26532
26844
  }
26533
26845
  const ownerOf = (provider, harness) => harness ?? defaultHarnessForProvider(provider);
26846
+ const openEntry = (entry2) => ({
26847
+ kind: entry2.kind,
26848
+ secret: open(keyForRead(), entry2.sealed, entryContext(entry2))
26849
+ });
26850
+ function updateMember(provider, harness, id2, change) {
26851
+ const entries2 = readAll();
26852
+ const slot = slotEntries(entries2, provider, harness);
26853
+ const at2 = slot.findIndex((e) => memberIdOf(e) === id2);
26854
+ const current = slot[at2];
26855
+ if (current === void 0) return false;
26856
+ const next = change(current);
26857
+ if (next === void 0) return false;
26858
+ const rewritten = slot.map((e, i2) => i2 === at2 ? next : e);
26859
+ writeAll3(withSlot(entries2, provider, harness, rewritten));
26860
+ return true;
26861
+ }
26534
26862
  return {
26535
26863
  has: (provider, harness) => {
26536
26864
  const owner = ownerOf(provider, harness);
@@ -26538,21 +26866,14 @@ function openCredentialStore(paths) {
26538
26866
  },
26539
26867
  read: (provider, harness) => {
26540
26868
  const owner = ownerOf(provider, harness);
26541
- const entry2 = readAll().find((e) => matches(e, provider, owner));
26542
- if (entry2 === void 0) return void 0;
26543
- return {
26544
- kind: entry2.kind,
26545
- secret: open(
26546
- keyForRead(),
26547
- entry2.sealed,
26548
- sealingContext(provider, owner)
26549
- )
26550
- };
26869
+ const entry2 = slotEntries(readAll(), provider, owner)[0];
26870
+ return entry2 === void 0 ? void 0 : openEntry(entry2);
26551
26871
  },
26552
26872
  take: (provider, { kind, secret }, source, now, harness) => {
26553
26873
  if (secret.trim().length === 0)
26554
26874
  throw new Error("refusing to take an empty credential into custody");
26555
26875
  const owner = ownerOf(provider, harness);
26876
+ const hint = hintOf(kind, secret);
26556
26877
  const entry2 = {
26557
26878
  provider,
26558
26879
  harness: owner,
@@ -26560,29 +26881,201 @@ function openCredentialStore(paths) {
26560
26881
  source,
26561
26882
  taken_at: new Date(now).toISOString(),
26562
26883
  // A ChatGPT login is JSON, whose head says nothing; it is named.
26563
- prefix: kind === "chatgpt" ? "login" : credentialPrefix(secret),
26564
- sealed: seal(keyForWrite(), secret, sealingContext(provider, owner))
26884
+ prefix: prefixOf(kind, secret),
26885
+ sealed: seal(keyForWrite(), secret, sealingContext(provider, owner)),
26886
+ ...hint !== void 0 ? { hint } : {}
26565
26887
  };
26888
+ const entries2 = readAll();
26889
+ const copies = slotEntries(entries2, provider, owner).filter(isVaultCopy);
26566
26890
  writeAll3([
26567
- ...readAll().filter((e) => !matches(e, provider, owner)),
26568
- entry2
26891
+ ...entries2.filter((e) => !matches(e, provider, owner)),
26892
+ entry2,
26893
+ ...copies
26569
26894
  ]);
26570
26895
  return custodyOf(entry2);
26571
26896
  },
26572
26897
  release: (provider, harness) => {
26573
26898
  const owner = ownerOf(provider, harness);
26574
26899
  const entries2 = readAll();
26575
- const entry2 = entries2.find((e) => matches(e, provider, owner));
26576
- if (entry2 === void 0) return void 0;
26577
- const secret = open(
26578
- keyForRead(),
26579
- entry2.sealed,
26580
- sealingContext(provider, owner)
26581
- );
26900
+ const slot = slotEntries(entries2, provider, owner);
26901
+ if (slot.length === 0) return void 0;
26902
+ const own = slot.find((e) => !isVaultCopy(e));
26903
+ const held = own === void 0 ? void 0 : openEntry(own);
26582
26904
  writeAll3(entries2.filter((e) => !matches(e, provider, owner)));
26583
- return { kind: entry2.kind, secret };
26905
+ return held;
26906
+ },
26907
+ status: () => {
26908
+ const entries2 = readAll();
26909
+ const seen = /* @__PURE__ */ new Set();
26910
+ const rows = [];
26911
+ for (const entry2 of entries2) {
26912
+ const harness = harnessOf(entry2);
26913
+ const slot = `${entry2.provider}:${harness}`;
26914
+ if (seen.has(slot)) continue;
26915
+ seen.add(slot);
26916
+ const first = slotEntries(entries2, entry2.provider, harness)[0];
26917
+ if (first !== void 0) rows.push(custodyOf(first));
26918
+ }
26919
+ return rows;
26920
+ },
26921
+ pool: (provider, harness) => slotEntries(readAll(), provider, ownerOf(provider, harness)).map(
26922
+ memberOf
26923
+ ),
26924
+ open: (provider, harness, id2) => {
26925
+ const entry2 = slotEntries(readAll(), provider, harness).find(
26926
+ (e) => memberIdOf(e) === id2
26927
+ );
26928
+ return entry2 === void 0 ? void 0 : openEntry(entry2);
26929
+ },
26930
+ nextUntried: (provider, harness, options) => {
26931
+ const eligible = slotEntries(readAll(), provider, harness).map(memberOf).filter(
26932
+ (member4) => !(options.tried?.has(member4.id) ?? false) && (options.loginsOnly !== true || isLoginKind(member4.kind)) && (options.fits?.(member4) ?? true)
26933
+ );
26934
+ const ready = eligible.find(
26935
+ (member4) => !heldBackAt(member4.failure, options.now)
26936
+ );
26937
+ if (options.allowHeldBack !== true) return ready;
26938
+ if (ready !== void 0) {
26939
+ const loginReady = eligible.some(
26940
+ (member4) => isLoginKind(member4.kind) && !heldBackAt(member4.failure, options.now)
26941
+ );
26942
+ const waiting = loginReady ? void 0 : eligible.find(
26943
+ (member4) => isLoginKind(member4.kind) && member4.failure?.kind === "rate_limit" && heldBackAt(member4.failure, options.now)
26944
+ );
26945
+ return waiting ?? ready;
26946
+ }
26947
+ let soonest;
26948
+ for (const member4 of eligible) {
26949
+ if (soonest === void 0 || Date.parse(member4.failure?.until ?? "") < Date.parse(soonest.failure?.until ?? ""))
26950
+ soonest = member4;
26951
+ }
26952
+ return soonest;
26953
+ },
26954
+ markFailed: (provider, harness, id2, failure4, now) => updateMember(provider, harness, id2, (entry2) => ({
26955
+ ...entry2,
26956
+ ...failure4.refreshRefused !== void 0 ? { refresh_refused: failure4.refreshRefused } : {},
26957
+ failure: {
26958
+ kind: failure4.kind,
26959
+ at: new Date(now).toISOString(),
26960
+ until: new Date(failure4.until).toISOString()
26961
+ }
26962
+ })),
26963
+ clearFailure: (provider, harness, id2) => updateMember(provider, harness, id2, (entry2) => {
26964
+ if (entry2.failure === void 0) return void 0;
26965
+ const { failure: _cleared, ...rest } = entry2;
26966
+ return rest;
26967
+ }),
26968
+ replaceSecret: (provider, harness, id2, { kind, secret }, source, now) => {
26969
+ if (secret.trim().length === 0)
26970
+ throw new Error("refusing to take an empty credential into custody");
26971
+ return updateMember(provider, harness, id2, (entry2) => {
26972
+ const { failure: failure4, refresh_refused: _refused, ...rest } = entry2;
26973
+ const at2 = new Date(now).toISOString();
26974
+ const next = {
26975
+ ...rest,
26976
+ kind,
26977
+ // A vault copy stays one, so the next sync still knows it; the
26978
+ // machine's own takes the source it was refreshed from.
26979
+ source: isVaultCopy(entry2) ? VAULT_POOL_SOURCE : source,
26980
+ taken_at: at2,
26981
+ refreshed_at: at2,
26982
+ prefix: prefixOf(kind, secret),
26983
+ ...failure4 !== void 0 && failure4.kind !== "invalid_token" ? { failure: failure4 } : {},
26984
+ sealed: entry2.sealed
26985
+ };
26986
+ return {
26987
+ ...next,
26988
+ sealed: seal(keyForWrite(), secret, entryContext(next))
26989
+ };
26990
+ });
26991
+ },
26992
+ syncPool: (provider, harness, members2, now) => {
26993
+ const entries2 = readAll();
26994
+ const slot = slotEntries(entries2, provider, harness);
26995
+ const own = slot.find((e) => !isVaultCopy(e));
26996
+ if (own === void 0) return { synced: false, reason: "not_brokered" };
26997
+ if (own.source === "sandbox:launch")
26998
+ return { synced: false, reason: "sandbox" };
26999
+ const ownIdentity = identityOf(own.kind, openEntry(own).secret);
27000
+ const local = new Map(
27001
+ slot.filter(isVaultCopy).map((e) => [memberIdOf(e), e])
27002
+ );
27003
+ const identities = /* @__PURE__ */ new Set([ownIdentity]);
27004
+ let ownCopy;
27005
+ const copies = [];
27006
+ let added = 0;
27007
+ let kept = 0;
27008
+ for (const member4 of members2) {
27009
+ if (member4.secret.trim().length === 0) continue;
27010
+ if (!VAULT_CREDENTIAL_ID_PATTERN.test(member4.credential_id)) continue;
27011
+ const identity = identityOf(member4.kind, member4.secret);
27012
+ if (identity === ownIdentity) {
27013
+ ownCopy ??= member4;
27014
+ continue;
27015
+ }
27016
+ if (identities.has(identity)) continue;
27017
+ identities.add(identity);
27018
+ const before = local.get(member4.credential_id);
27019
+ const label = member4.label?.slice(0, 80);
27020
+ const unchanged = before !== void 0 && before.kind === member4.kind && (before.vault_changed_at === member4.changed_at || refreshedSince(before, member4.changed_at));
27021
+ if (before !== void 0) kept += 1;
27022
+ else added += 1;
27023
+ const base2 = unchanged ? { ...before } : {
27024
+ provider,
27025
+ harness,
27026
+ kind: member4.kind,
27027
+ source: VAULT_POOL_SOURCE,
27028
+ taken_at: new Date(now).toISOString(),
27029
+ prefix: prefixOf(member4.kind, member4.secret),
27030
+ credential_id: member4.credential_id,
27031
+ vault_changed_at: member4.changed_at,
27032
+ // Replaced below, once the row's context is known.
27033
+ sealed: own.sealed
27034
+ };
27035
+ const { label: _label, failure: _failure, ...rest } = base2;
27036
+ const failure4 = mergedFailure(
27037
+ unchanged ? before.failure : void 0,
27038
+ member4.limited_until,
27039
+ now
27040
+ );
27041
+ const copy = {
27042
+ ...rest,
27043
+ hint: member4.hint.slice(-4),
27044
+ ...label !== void 0 && label.length > 0 ? { label } : {},
27045
+ ...failure4 !== void 0 ? { failure: failure4 } : {}
27046
+ };
27047
+ copies.push(
27048
+ unchanged ? copy : {
27049
+ ...copy,
27050
+ sealed: seal(keyForWrite(), member4.secret, entryContext(copy))
27051
+ }
27052
+ );
27053
+ }
27054
+ const removed = [...local.keys()].filter(
27055
+ (id2) => !members2.some((m) => m.credential_id === id2)
27056
+ ).length;
27057
+ const {
27058
+ credential_id: _id,
27059
+ label: _ownLabel,
27060
+ failure: _ownFailure,
27061
+ ...ownBare
27062
+ } = own;
27063
+ const ownLabel = ownCopy?.label?.slice(0, 80);
27064
+ const ownFailure = mergedFailure(
27065
+ own.failure,
27066
+ ownCopy?.limited_until,
27067
+ now
27068
+ );
27069
+ const ownNext = {
27070
+ ...ownBare,
27071
+ ...ownCopy !== void 0 ? { credential_id: ownCopy.credential_id } : {},
27072
+ ...ownLabel !== void 0 && ownLabel.length > 0 ? { label: ownLabel } : {},
27073
+ ...own.hint === void 0 && ownCopy !== void 0 ? { hint: ownCopy.hint.slice(-4) } : {},
27074
+ ...ownFailure !== void 0 ? { failure: ownFailure } : {}
27075
+ };
27076
+ writeAll3(withSlot(entries2, provider, harness, [ownNext, ...copies]));
27077
+ return { synced: true, added, kept, removed };
26584
27078
  },
26585
- status: () => readAll().map(custodyOf),
26586
27079
  shred: () => {
26587
27080
  let overwrite;
26588
27081
  try {
@@ -26601,11 +27094,12 @@ function openCredentialStore(paths) {
26601
27094
  }
26602
27095
  };
26603
27096
  }
26604
- var CREDENTIAL_STORE_SCHEMA, CREDENTIAL_SOURCES, CREDENTIAL_KINDS, CLAUDE_OAUTH_TOKEN_PREFIX, sealedSchema, entrySchema, fileSchema, KEY_BYTES2;
27097
+ var CREDENTIAL_STORE_SCHEMA, CREDENTIAL_SOURCES, VAULT_POOL_SOURCE, HELD_MEMBER_ID, CREDENTIAL_KINDS, CLAUDE_OAUTH_TOKEN_PREFIX, LOGIN_REFRESH_REFUSALS, sealedSchema, failureSchema, entrySchema, fileSchema, KEY_BYTES2;
26605
27098
  var init_credential_store = __esm({
26606
27099
  "../../packages/tacho/src/host/credential-store.ts"() {
26607
27100
  "use strict";
26608
27101
  init_zod();
27102
+ init_model_failure();
26609
27103
  init_wire();
26610
27104
  init_fs();
26611
27105
  init_run_token();
@@ -26634,8 +27128,15 @@ var init_credential_store = __esm({
26634
27128
  * is spent at the cloud gateway, which attaches the operator's model
26635
27129
  * credential. It is not a model credential itself.
26636
27130
  */
26637
- "sandbox:launch"
27131
+ "sandbox:launch",
27132
+ /**
27133
+ * One of the person's credentials saved in Oxagen, copied from the vault
27134
+ * by a pool sync (`list_host_model_credentials`).
27135
+ */
27136
+ "vault:pool"
26638
27137
  ];
27138
+ VAULT_POOL_SOURCE = "vault:pool";
27139
+ HELD_MEMBER_ID = "held";
26639
27140
  CREDENTIAL_KINDS = [
26640
27141
  "api_key",
26641
27142
  "bearer",
@@ -26643,12 +27144,20 @@ var init_credential_store = __esm({
26643
27144
  "chatgpt"
26644
27145
  ];
26645
27146
  CLAUDE_OAUTH_TOKEN_PREFIX = "sk-ant-oat";
27147
+ LOGIN_REFRESH_REFUSALS = ["rotated", "refused"];
26646
27148
  sealedSchema = external_exports.object({
26647
27149
  /** AES-256-GCM: 12-byte nonce, ciphertext, 16-byte tag, all base64. */
26648
27150
  nonce: external_exports.string().min(1),
26649
27151
  ciphertext: external_exports.string().min(1),
26650
27152
  tag: external_exports.string().min(1)
26651
27153
  }).strict();
27154
+ failureSchema = external_exports.object({
27155
+ kind: external_exports.enum(MODEL_FAILURE_KINDS),
27156
+ /** When the provider answered, ISO-8601. */
27157
+ at: external_exports.string(),
27158
+ /** When the gateway asks it again, ISO-8601. */
27159
+ until: external_exports.string()
27160
+ }).strict();
26652
27161
  entrySchema = external_exports.object({
26653
27162
  provider: external_exports.enum(RUN_TOKEN_PROVIDERS),
26654
27163
  /**
@@ -26662,7 +27171,34 @@ var init_credential_store = __esm({
26662
27171
  taken_at: external_exports.string(),
26663
27172
  /** The first few characters, the way a vendor console shows a key. */
26664
27173
  prefix: external_exports.string().max(12),
26665
- sealed: sealedSchema
27174
+ sealed: sealedSchema,
27175
+ /**
27176
+ * The vault's id for this credential, when the vault holds it: every
27177
+ * `vault:pool` member, and the machine's own credential when the person
27178
+ * saved the same one in Oxagen.
27179
+ */
27180
+ credential_id: external_exports.string().regex(VAULT_CREDENTIAL_ID_PATTERN).optional(),
27181
+ /** The secret's last four characters, for a message that names it. */
27182
+ hint: external_exports.string().max(4).optional(),
27183
+ /** The name the person gave it in Oxagen, such as the account's email. */
27184
+ label: external_exports.string().max(80).optional(),
27185
+ /**
27186
+ * When the vault last changed the secret, for a `vault:pool` member. A
27187
+ * ChatGPT login this machine refreshed after that time keeps its own,
27188
+ * newer tokens on the next sync.
27189
+ */
27190
+ vault_changed_at: external_exports.string().optional(),
27191
+ /** When this machine last refreshed the secret (`replaceSecret`), ISO-8601. */
27192
+ refreshed_at: external_exports.string().optional(),
27193
+ /**
27194
+ * The OpenAI issuer refused to refresh the tokens this row holds:
27195
+ * `rotated` when another machine already used the refresh token, and
27196
+ * `refused` for any other refusal. No refresh is asked for again until
27197
+ * the secret changes, because a refresh token sent twice can make the
27198
+ * issuer revoke the login on every machine.
27199
+ */
27200
+ refresh_refused: external_exports.enum(LOGIN_REFRESH_REFUSALS).optional(),
27201
+ failure: failureSchema.optional()
26666
27202
  }).strict();
26667
27203
  fileSchema = external_exports.object({
26668
27204
  schema: external_exports.literal(CREDENTIAL_STORE_SCHEMA),
@@ -28624,14 +29160,35 @@ async function credentialStatus(options, deps) {
28624
29160
  deps,
28625
29161
  ...others.map((agent) => depsForAgent(deps, agent))
28626
29162
  ].flatMap(
28627
- (agent) => (agent.credentialStore?.status() ?? []).map((c) => ({
28628
- provider: c.provider,
28629
- harness: c.harness,
28630
- kind: c.kind,
28631
- source: c.source,
28632
- taken_at: c.taken_at,
28633
- prefix: c.prefix
28634
- }))
29163
+ (agent) => (agent.credentialStore?.status() ?? []).map((c) => {
29164
+ const members2 = agent.credentialStore?.pool(c.provider, c.harness) ?? [];
29165
+ const now = deps.now();
29166
+ const shown3 = members2.length > 1 || members2.some(
29167
+ (m) => m.failure !== void 0 && Date.parse(m.failure.until) > now
29168
+ );
29169
+ return {
29170
+ provider: c.provider,
29171
+ harness: c.harness,
29172
+ kind: c.kind,
29173
+ source: c.source,
29174
+ taken_at: c.taken_at,
29175
+ prefix: c.prefix,
29176
+ ...shown3 ? {
29177
+ pool: members2.map((m) => ({
29178
+ id: m.id,
29179
+ kind: m.kind,
29180
+ ...m.hint !== void 0 ? { hint: m.hint } : {},
29181
+ ...m.label !== void 0 ? { label: m.label } : {},
29182
+ ...m.failure !== void 0 && Date.parse(m.failure.until) > now ? {
29183
+ held_back: {
29184
+ kind: m.failure.kind,
29185
+ until: m.failure.until
29186
+ }
29187
+ } : {}
29188
+ }))
29189
+ } : {}
29190
+ };
29191
+ })
28635
29192
  );
28636
29193
  const enrolled = host === void 0 && others.length === 0 ? MODEL_CREDENTIAL_HARNESSES : [
28637
29194
  ...host?.harnesses ?? [],
@@ -28653,13 +29210,92 @@ async function credentialStatus(options, deps) {
28653
29210
  deps.out(
28654
29211
  "Custody nothing: every harness holds its own model credential and the gateway forwards it"
28655
29212
  );
28656
- for (const entry2 of custody)
29213
+ for (const entry2 of custody) {
28657
29214
  deps.out(
28658
29215
  `Custody ${entry2.provider}${entry2.harness === defaultHarnessForProvider(entry2.provider) ? "" : ` (${TACHO_HARNESS_LABELS[entry2.harness]})`}: ${entry2.kind} ${entry2.prefix} from ${entry2.source}, taken ${entry2.taken_at}`
28659
29216
  );
29217
+ for (const [at2, member4] of (entry2.pool ?? []).entries())
29218
+ deps.out(
29219
+ ` ${at2 + 1}. ${member4.hint !== void 0 ? `\u2026${member4.hint}` : member4.id} ${member4.kind}${member4.label !== void 0 ? ` (${member4.label})` : ""}${member4.held_back !== void 0 ? `, held back until ${member4.held_back.until} (${member4.held_back.kind})` : ""}`
29220
+ );
29221
+ }
28660
29222
  for (const entry2 of state) deps.out(` ${describeHarness(entry2)}`);
28661
29223
  return report;
28662
29224
  }
29225
+ function harnessLabel(harness) {
29226
+ return isBrokerableHarness(harness) ? TACHO_HARNESS_LABELS[harness] : harness;
29227
+ }
29228
+ function describePoolSync(line) {
29229
+ const label = harnessLabel(line.harness);
29230
+ if (line.synced) {
29231
+ const held = (line.added ?? 0) + (line.kept ?? 0);
29232
+ return `${label}: ${held} saved credential${held === 1 ? "" : "s"} after this machine's own (${line.added ?? 0} added, ${line.removed ?? 0} removed)`;
29233
+ }
29234
+ if (line.reason === "not_brokered")
29235
+ return `${label}: holds its own credential, so the gateway uses no saved one (run \`oxagen agent enroll\` to broker it)`;
29236
+ if (line.reason === "sandbox")
29237
+ return `${label}: a sandbox's calls use the cloud gateway's credentials`;
29238
+ return `${label}: not synced, so custody keeps what it held: ${line.detail ?? "the daemon gave no reason"}`;
29239
+ }
29240
+ async function syncCredentialPoolsNow(deps) {
29241
+ const read2 = readHostFileLenient(deps.paths.hostFile);
29242
+ if (read2.error !== void 0)
29243
+ return {
29244
+ ok: false,
29245
+ detail: `${read2.error}, so nothing was synced. Run \`oxagen agent status\` to see what is wrong with it`,
29246
+ pools: []
29247
+ };
29248
+ const others = otherLiveAgents(deps.paths, deps.paths.dir);
29249
+ if (read2.host === void 0 && others.length === 0)
29250
+ return {
29251
+ ok: false,
29252
+ detail: "this machine is not enrolled; run `oxagen agent enroll`",
29253
+ pools: []
29254
+ };
29255
+ const agents = [
29256
+ ...read2.host !== void 0 ? [deps] : [],
29257
+ ...others.map((agent) => depsForAgent(deps, agent))
29258
+ ];
29259
+ const pools = [];
29260
+ let answered = 0;
29261
+ for (const agent of agents) {
29262
+ const answer = await agent.daemonPost?.("/credential/sync", {});
29263
+ if (answer === void 0 || answer.status !== 200) continue;
29264
+ let body2;
29265
+ try {
29266
+ body2 = JSON.parse(answer.body);
29267
+ } catch {
29268
+ continue;
29269
+ }
29270
+ const parsed2 = poolSyncAnswerSchema.safeParse(body2);
29271
+ if (!parsed2.success) continue;
29272
+ answered += 1;
29273
+ pools.push(...parsed2.data.pools);
29274
+ }
29275
+ if (answered === 0)
29276
+ return {
29277
+ ok: false,
29278
+ detail: "the recorder's daemon did not answer, so nothing was synced. It syncs by itself when it starts; run `oxagen agent status`",
29279
+ pools
29280
+ };
29281
+ return {
29282
+ ok: pools.every((line) => line.synced || line.reason !== "fetch_failed"),
29283
+ pools
29284
+ };
29285
+ }
29286
+ async function credentialSync(options, deps) {
29287
+ const outcome = await syncCredentialPoolsNow(deps);
29288
+ if (options.json === true) {
29289
+ deps.out(JSON.stringify(outcome, null, 2));
29290
+ return outcome;
29291
+ }
29292
+ if (outcome.detail !== void 0) deps.err(outcome.detail);
29293
+ for (const line of outcome.pools)
29294
+ (line.reason === "fetch_failed" ? deps.err : deps.out)(
29295
+ describePoolSync(line)
29296
+ );
29297
+ return outcome;
29298
+ }
28663
29299
  function describeHarness(entry2) {
28664
29300
  const label = TACHO_HARNESS_LABELS[entry2.harness];
28665
29301
  if (entry2.brokered) {
@@ -29125,10 +29761,11 @@ async function credentialLogin(options, deps) {
29125
29761
  detail: outcome.harnesses.some((h) => h.brokered) ? "Claude Code now holds a run token, and the gateway sends your subscription with every call" : "The subscription is in custody. Run `oxagen agent enroll` to route Claude Code through the gateway"
29126
29762
  };
29127
29763
  }
29128
- var MODEL_CREDENTIAL_HARNESSES, CREDENTIAL_MODES, STELLA_ANTHROPIC_KEY_ENV, CLAUDE_OAUTH_TOKEN_ENV;
29764
+ var MODEL_CREDENTIAL_HARNESSES, CREDENTIAL_MODES, poolSyncAnswerSchema, STELLA_ANTHROPIC_KEY_ENV, CLAUDE_OAUTH_TOKEN_ENV;
29129
29765
  var init_credential = __esm({
29130
29766
  "../../packages/tacho/src/cli/credential.ts"() {
29131
29767
  "use strict";
29768
+ init_zod();
29132
29769
  init_claude_setup_token();
29133
29770
  init_credential_store();
29134
29771
  init_host_file();
@@ -29140,6 +29777,19 @@ var init_credential = __esm({
29140
29777
  ...BROKERABLE_HARNESSES
29141
29778
  ];
29142
29779
  CREDENTIAL_MODES = ["brokered", "passthrough"];
29780
+ poolSyncAnswerSchema = external_exports.object({
29781
+ pools: external_exports.array(
29782
+ external_exports.object({
29783
+ harness: external_exports.string(),
29784
+ synced: external_exports.boolean(),
29785
+ reason: external_exports.string().optional(),
29786
+ detail: external_exports.string().optional(),
29787
+ added: external_exports.number().optional(),
29788
+ kept: external_exports.number().optional(),
29789
+ removed: external_exports.number().optional()
29790
+ }).passthrough()
29791
+ )
29792
+ });
29143
29793
  STELLA_ANTHROPIC_KEY_ENV = "ANTHROPIC_API_KEY";
29144
29794
  CLAUDE_OAUTH_TOKEN_ENV = "CLAUDE_CODE_OAUTH_TOKEN";
29145
29795
  }
@@ -29915,7 +30565,7 @@ import { readFileSync as readFileSync10 } from "node:fs";
29915
30565
  import { dirname as dirname9, resolve as resolve3 } from "node:path";
29916
30566
  import { fileURLToPath } from "node:url";
29917
30567
  function readVersion() {
29918
- if (true) return "3.0.1-817";
30568
+ if (true) return "3.0.1-818";
29919
30569
  try {
29920
30570
  const here = dirname9(fileURLToPath(import.meta.url));
29921
30571
  const pkg = JSON.parse(
@@ -31289,7 +31939,9 @@ function workOrderEndpointsFor(apiUrl) {
31289
31939
  workCriterionClaim: `${base2}${WORK_CRITERION_CLAIM_PATH}`,
31290
31940
  workOrderProgress: `${base2}${WORK_ORDER_PROGRESS_PATH}`,
31291
31941
  certificate: `${base2}${CERTIFICATE_RENEW_PATH}`,
31292
- enrollmentKeys: `${base2}${ENROLLMENT_KEYS_PATH}`
31942
+ enrollmentKeys: `${base2}${ENROLLMENT_KEYS_PATH}`,
31943
+ modelCredentials: `${base2}${HOST_MODEL_CREDENTIALS_PATH}`,
31944
+ modelCredentialState: `${base2}${HOST_MODEL_CREDENTIAL_STATE_PATH}`
31293
31945
  };
31294
31946
  }
31295
31947
  function createControlClient(options) {
@@ -31414,6 +32066,23 @@ function createControlClient(options) {
31414
32066
  void 0,
31415
32067
  "GET"
31416
32068
  ),
32069
+ modelCredentials: async (harness) => call2(
32070
+ endpoint(options.endpoints.modelCredentials, "model credentials"),
32071
+ hostModelCredentialsResponseSchema,
32072
+ { host_enrollment_id: options.hostEnrollmentId, harness }
32073
+ ),
32074
+ reportModelCredential: async (credentialId, report) => call2(
32075
+ endpoint(
32076
+ options.endpoints.modelCredentialState,
32077
+ "model credential report"
32078
+ ),
32079
+ hostModelCredentialStateResponseSchema,
32080
+ {
32081
+ host_enrollment_id: options.hostEnrollmentId,
32082
+ credential_id: credentialId,
32083
+ report
32084
+ }
32085
+ ),
31417
32086
  // The body names exactly the contract's fields. It carries no enrollment
31418
32087
  // id: the server reads the host from the key. The run's token goes in a
31419
32088
  // header, so it stays out of the input the kernel hashes and audits.
@@ -37815,6 +38484,16 @@ ${problems.map((problem) => ` ${problem}`).join("\n")}`
37815
38484
  ` ${harness === "stella" ? "Stella's " : ""}${provider} credential taken into the gateway's custody (${deps.paths.credentials})`
37816
38485
  );
37817
38486
  warnings.push(...outcome.warnings);
38487
+ try {
38488
+ const pools = await syncCredentialPoolsNow(deps);
38489
+ for (const line of pools.pools)
38490
+ if (line.synced && (line.added ?? 0) + (line.kept ?? 0) > 0)
38491
+ deps.out(` ${describePoolSync(line)}`);
38492
+ } catch (error2) {
38493
+ warnings.push(
38494
+ `the model credentials saved in Oxagen were not synced yet: ${error2 instanceof Error ? error2.message : String(error2)}. The daemon syncs them when it starts, or run \`oxagen credential sync\``
38495
+ );
38496
+ }
37818
38497
  const unrouted = writable2.filter((h) => !reaching.includes(h));
37819
38498
  if (unrouted.length > 0) {
37820
38499
  const given = await restoreCredentials(
@@ -41047,7 +41726,7 @@ function createMcpGateway(deps) {
41047
41726
  return response;
41048
41727
  }
41049
41728
  };
41050
- function recordCall(request3, context, status2, durationMs, refusedReason, rpc) {
41729
+ function recordCall(request3, context, status2, durationMs2, refusedReason, rpc) {
41051
41730
  if (deps.record === void 0) return;
41052
41731
  const isCall = request3.method === "tools/call";
41053
41732
  if (!isCall && status2 !== "rejected") return;
@@ -41064,7 +41743,7 @@ function createMcpGateway(deps) {
41064
41743
  ...isCall && request3.params?.["arguments"] !== void 0 ? { arguments: request3.params["arguments"] } : {},
41065
41744
  ...toolUseId === void 0 ? {} : { toolUseId },
41066
41745
  status: status2,
41067
- durationMs,
41746
+ durationMs: durationMs2,
41068
41747
  ...refusedReason === void 0 ? {} : { refusedReason },
41069
41748
  ...ruleIds === void 0 ? {} : { ruleIds },
41070
41749
  ...taint === void 0 ? {} : { taint },
@@ -43570,67 +44249,359 @@ function chatGptLoginDue(login, takenAt, now) {
43570
44249
  if (exp !== void 0) return exp - now < CHATGPT_REFRESH_MARGIN_MS;
43571
44250
  return now - takenAt > CHATGPT_REFRESH_MAX_AGE_MS;
43572
44251
  }
43573
- async function refreshChatGptLogin(login, fetchImpl) {
44252
+ function refusalCode(text6) {
44253
+ let parsed2;
44254
+ try {
44255
+ parsed2 = JSON.parse(text6);
44256
+ } catch {
44257
+ return void 0;
44258
+ }
44259
+ if (parsed2 === null || typeof parsed2 !== "object") return void 0;
44260
+ const body2 = parsed2;
44261
+ const error2 = body2["error"];
44262
+ if (typeof error2 === "string") return error2;
44263
+ if (error2 !== null && typeof error2 === "object") {
44264
+ const code = error2["code"];
44265
+ if (typeof code === "string") return code;
44266
+ }
44267
+ const topCode = body2["code"];
44268
+ return typeof topCode === "string" ? topCode : void 0;
44269
+ }
44270
+ async function exchange(login, fetchImpl, timeoutMs) {
43574
44271
  if (login.refresh_token.length === 0)
43575
- throw new Error("the ChatGPT login in custody has no refresh token");
43576
- const response = await fetchImpl(CHATGPT_TOKEN_URL, {
43577
- method: "POST",
43578
- headers: { "Content-Type": "application/json" },
43579
- body: JSON.stringify({
43580
- client_id: CODEX_OAUTH_CLIENT_ID,
43581
- grant_type: "refresh_token",
43582
- refresh_token: login.refresh_token,
43583
- scope: "openid profile email"
43584
- })
43585
- });
43586
- if (!response.ok)
43587
- throw new Error(
43588
- `auth.openai.com refused to refresh the ChatGPT login (${response.status}); run \`codex login\`, then \`oxagen agent enroll\``
43589
- );
44272
+ return {
44273
+ outcome: "refused",
44274
+ detail: `the ChatGPT login in custody has no refresh token; ${RELOGIN}`
44275
+ };
44276
+ let status2;
44277
+ let ok;
44278
+ let text6;
44279
+ try {
44280
+ const response = await fetchImpl(CHATGPT_TOKEN_URL, {
44281
+ method: "POST",
44282
+ headers: { "Content-Type": "application/json" },
44283
+ body: JSON.stringify({
44284
+ client_id: CODEX_OAUTH_CLIENT_ID,
44285
+ grant_type: "refresh_token",
44286
+ refresh_token: login.refresh_token,
44287
+ scope: "openid profile email"
44288
+ }),
44289
+ signal: AbortSignal.timeout(timeoutMs)
44290
+ });
44291
+ status2 = response.status;
44292
+ ok = response.ok;
44293
+ text6 = await response.text();
44294
+ } catch (error2) {
44295
+ return {
44296
+ outcome: "failed",
44297
+ detail: `could not reach auth.openai.com: ${error2 instanceof Error ? error2.message : String(error2)}`
44298
+ };
44299
+ }
44300
+ if (!ok) {
44301
+ if (status2 === 429 || status2 >= 500)
44302
+ return {
44303
+ outcome: "failed",
44304
+ detail: `auth.openai.com answered ${status2} to a refresh`
44305
+ };
44306
+ const code = refusalCode(text6);
44307
+ return {
44308
+ outcome: code !== void 0 && ROTATED_REFRESH_CODES.has(code) ? "rotated" : "refused",
44309
+ detail: `auth.openai.com refused to refresh the ChatGPT login (${status2}${code !== void 0 ? `, ${code.slice(0, 64)}` : ""}); ${RELOGIN}`
44310
+ };
44311
+ }
43590
44312
  let body2;
43591
44313
  try {
43592
- body2 = JSON.parse(await response.text());
44314
+ body2 = JSON.parse(text6);
43593
44315
  } catch {
43594
- throw new Error("auth.openai.com answered with something other than JSON");
44316
+ return {
44317
+ outcome: "failed",
44318
+ detail: "auth.openai.com answered with something other than JSON"
44319
+ };
43595
44320
  }
43596
44321
  if (typeof body2.access_token !== "string" || body2.access_token.length === 0)
43597
- throw new Error("auth.openai.com answered without an access token");
44322
+ return {
44323
+ outcome: "failed",
44324
+ detail: "auth.openai.com answered without an access token"
44325
+ };
43598
44326
  return {
43599
- ...login,
43600
- access_token: body2.access_token,
43601
- refresh_token: typeof body2.refresh_token === "string" ? body2.refresh_token : login.refresh_token,
43602
- ...typeof body2.id_token === "string" ? { id_token: body2.id_token } : {}
43603
- };
43604
- }
43605
- async function refreshChatGptCustody(store, fetchImpl, now) {
43606
- const entry2 = store.status().find((c) => c.provider === "openai" && c.kind === "chatgpt");
43607
- if (entry2 === void 0) return "none";
43608
- const held = store.read("openai");
43609
- const login = held?.kind === "chatgpt" ? decodeChatGptLogin(held.secret) : void 0;
43610
- if (login === void 0) return { failed: "custody holds no ChatGPT login" };
43611
- if (!chatGptLoginDue(login, Date.parse(entry2.taken_at), now)) return "fresh";
43612
- try {
43613
- const next = await refreshChatGptLogin(login, fetchImpl);
43614
- store.take(
43615
- "openai",
43616
- { kind: "chatgpt", secret: JSON.stringify(next) },
44327
+ login: {
44328
+ ...login,
44329
+ access_token: body2.access_token,
44330
+ refresh_token: typeof body2.refresh_token === "string" ? body2.refresh_token : login.refresh_token,
44331
+ ...typeof body2.id_token === "string" ? { id_token: body2.id_token } : {}
44332
+ }
44333
+ };
44334
+ }
44335
+ function createChatGptRefresher(deps) {
44336
+ const { store } = deps;
44337
+ const timeoutMs = deps.timeoutMs ?? CHATGPT_REFRESH_TIMEOUT_MS;
44338
+ const running = /* @__PURE__ */ new Map();
44339
+ const memberOf2 = (id2) => store.pool(...SLOT).find((member4) => member4.id === id2);
44340
+ async function refreshOnce(id2) {
44341
+ const member4 = memberOf2(id2);
44342
+ if (member4 === void 0 || member4.kind !== "chatgpt")
44343
+ return {
44344
+ outcome: "failed",
44345
+ detail: "custody holds no such ChatGPT login"
44346
+ };
44347
+ if (member4.refresh_refused !== void 0)
44348
+ return {
44349
+ outcome: member4.refresh_refused,
44350
+ detail: `auth.openai.com already refused to refresh these tokens; ${RELOGIN}`
44351
+ };
44352
+ const held = store.open(...SLOT, id2);
44353
+ const login = held?.kind === "chatgpt" ? decodeChatGptLogin(held.secret) : void 0;
44354
+ if (login === void 0)
44355
+ return { outcome: "failed", detail: "custody holds no ChatGPT login" };
44356
+ const answer = await exchange(login, deps.fetch, timeoutMs);
44357
+ if (!("login" in answer)) {
44358
+ if (answer.outcome !== "failed")
44359
+ store.markFailed(
44360
+ ...SLOT,
44361
+ id2,
44362
+ {
44363
+ kind: "invalid_token",
44364
+ until: deps.now() + DEAD_CREDENTIAL_HOLD_MS,
44365
+ refreshRefused: answer.outcome
44366
+ },
44367
+ deps.now()
44368
+ );
44369
+ return answer;
44370
+ }
44371
+ store.replaceSecret(
44372
+ ...SLOT,
44373
+ id2,
44374
+ { kind: "chatgpt", secret: JSON.stringify(answer.login) },
43617
44375
  "chatgpt:refresh",
43618
- now
43619
- );
43620
- return "refreshed";
43621
- } catch (error2) {
43622
- return { failed: error2 instanceof Error ? error2.message : String(error2) };
44376
+ deps.now()
44377
+ );
44378
+ deps.refreshed?.(memberOf2(id2) ?? member4);
44379
+ return { outcome: "refreshed" };
44380
+ }
44381
+ function refresh(id2) {
44382
+ const under2 = running.get(id2);
44383
+ if (under2 !== void 0) return under2;
44384
+ const started = refreshOnce(id2).catch(
44385
+ (error2) => ({
44386
+ outcome: "failed",
44387
+ detail: `custody could not be read or written: ${error2 instanceof Error ? error2.message : String(error2)}`
44388
+ })
44389
+ ).finally(() => running.delete(id2));
44390
+ running.set(id2, started);
44391
+ return started;
44392
+ }
44393
+ async function refreshDue() {
44394
+ const logins = store.pool(...SLOT).filter((member4) => member4.kind === "chatgpt");
44395
+ if (logins.length === 0) return "none";
44396
+ let refreshed = 0;
44397
+ const failed5 = [];
44398
+ for (const member4 of logins) {
44399
+ const name2 = logins.length === 1 ? "" : `${member4.hint !== void 0 ? `\u2026${member4.hint}` : member4.id}: `;
44400
+ if (member4.refresh_refused !== void 0) continue;
44401
+ const held = store.open(...SLOT, member4.id);
44402
+ const login = held?.kind === "chatgpt" ? decodeChatGptLogin(held.secret) : void 0;
44403
+ if (login === void 0) {
44404
+ failed5.push(`${name2}custody holds no ChatGPT login`);
44405
+ continue;
44406
+ }
44407
+ const due = member4.failure?.kind === "invalid_token" || chatGptLoginDue(login, Date.parse(member4.taken_at), deps.now());
44408
+ if (!due) continue;
44409
+ const result2 = await refresh(member4.id);
44410
+ if (result2.outcome === "refreshed") refreshed += 1;
44411
+ else failed5.push(`${name2}${result2.detail}`);
44412
+ }
44413
+ if (failed5.length > 0) return { failed: failed5.join("; ") };
44414
+ return refreshed > 0 ? "refreshed" : "fresh";
43623
44415
  }
44416
+ return { refresh, refreshDue };
43624
44417
  }
43625
- var CODEX_OAUTH_CLIENT_ID, CHATGPT_TOKEN_URL, CHATGPT_REFRESH_MARGIN_MS, CHATGPT_REFRESH_MAX_AGE_MS;
44418
+ var CODEX_OAUTH_CLIENT_ID, CHATGPT_TOKEN_URL, CHATGPT_REFRESH_MARGIN_MS, CHATGPT_REFRESH_MAX_AGE_MS, CHATGPT_REFRESH_TIMEOUT_MS, ROTATED_REFRESH_CODES, RELOGIN, SLOT;
43626
44419
  var init_chatgpt_refresh = __esm({
43627
44420
  "../../packages/tacho/src/host/chatgpt-refresh.ts"() {
43628
44421
  "use strict";
44422
+ init_model_failure();
43629
44423
  init_model_credential();
43630
44424
  CODEX_OAUTH_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
43631
44425
  CHATGPT_TOKEN_URL = "https://auth.openai.com/oauth/token";
43632
44426
  CHATGPT_REFRESH_MARGIN_MS = 60 * 6e4;
43633
44427
  CHATGPT_REFRESH_MAX_AGE_MS = 7 * 24 * 60 * 6e4;
44428
+ CHATGPT_REFRESH_TIMEOUT_MS = 1e4;
44429
+ ROTATED_REFRESH_CODES = /* @__PURE__ */ new Set([
44430
+ "refresh_token_reused",
44431
+ "refresh_token_invalidated"
44432
+ ]);
44433
+ RELOGIN = "run `codex login`, then `oxagen agent enroll`";
44434
+ SLOT = ["openai", "codex"];
44435
+ }
44436
+ });
44437
+
44438
+ // ../../packages/tacho/src/host/credential-pool.ts
44439
+ function chatGptTokensFromVault(saved) {
44440
+ let parsed2;
44441
+ try {
44442
+ parsed2 = JSON.parse(saved);
44443
+ } catch {
44444
+ return void 0;
44445
+ }
44446
+ if (parsed2 === null || typeof parsed2 !== "object") return void 0;
44447
+ const outer = parsed2;
44448
+ const inner = outer["tokens"];
44449
+ const tokens = inner !== null && typeof inner === "object" ? inner : outer;
44450
+ const text6 = (key) => {
44451
+ const value = tokens[key];
44452
+ return typeof value === "string" && value.length > 0 ? value : void 0;
44453
+ };
44454
+ const access2 = text6("access_token");
44455
+ if (access2 === void 0) return void 0;
44456
+ const idToken = text6("id_token");
44457
+ const accountId = text6("account_id") ?? accountOfIdToken(idToken);
44458
+ return JSON.stringify({
44459
+ access_token: access2,
44460
+ refresh_token: text6("refresh_token") ?? "",
44461
+ ...idToken !== void 0 ? { id_token: idToken } : {},
44462
+ ...accountId !== void 0 ? { account_id: accountId } : {}
44463
+ });
44464
+ }
44465
+ function accountOfIdToken(idToken) {
44466
+ const payload = idToken?.split(".")[1];
44467
+ if (payload === void 0 || payload.length === 0) return void 0;
44468
+ let claims;
44469
+ try {
44470
+ claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
44471
+ } catch {
44472
+ return void 0;
44473
+ }
44474
+ if (claims === null || typeof claims !== "object") return void 0;
44475
+ const auth2 = claims["https://api.openai.com/auth"];
44476
+ if (auth2 === null || typeof auth2 !== "object") return void 0;
44477
+ const account = auth2["chatgpt_account_id"];
44478
+ return typeof account === "string" && account.length > 0 ? account : void 0;
44479
+ }
44480
+ function poolMemberOf(credential, provider, harness) {
44481
+ if (credential.provider !== provider)
44482
+ return { skipped: `it is a ${credential.provider} credential` };
44483
+ if (credential.status !== "active")
44484
+ return { skipped: `it is ${credential.status}` };
44485
+ let kind;
44486
+ let secret = credential.secret.trim();
44487
+ if (credential.authType === "api_key" && credential.harness === null) {
44488
+ kind = provider === "anthropic" ? anthropicCredentialKind(secret, "api_key") : "bearer";
44489
+ } else if (credential.authType === "subscription_token" && credential.harness === harness && harness === "claude-code" && provider === "anthropic") {
44490
+ kind = "oauth";
44491
+ } else if (credential.authType === "subscription_token" && credential.harness === harness && harness === "codex" && provider === "openai") {
44492
+ const tokens = chatGptTokensFromVault(secret);
44493
+ if (tokens === void 0)
44494
+ return { skipped: "its ChatGPT login holds no access token" };
44495
+ kind = "chatgpt";
44496
+ secret = tokens;
44497
+ } else {
44498
+ return { skipped: `a ${credential.authType} does not serve ${harness}` };
44499
+ }
44500
+ const limitedUntil = credential.limitedUntil === null ? Number.NaN : Date.parse(credential.limitedUntil);
44501
+ return {
44502
+ credential_id: credential.id,
44503
+ kind,
44504
+ secret,
44505
+ hint: credential.hint,
44506
+ ...credential.label !== null ? { label: credential.label } : {},
44507
+ ...Number.isFinite(limitedUntil) ? { limited_until: limitedUntil } : {},
44508
+ changed_at: credential.rotatedAt ?? credential.createdAt
44509
+ };
44510
+ }
44511
+ function slotTakesPool(store, provider, harness) {
44512
+ const own = store.pool(provider, harness).find((member4) => member4.source !== VAULT_POOL_SOURCE);
44513
+ return own !== void 0 && own.source !== "sandbox:launch";
44514
+ }
44515
+ async function syncCredentialPools(deps) {
44516
+ const reports = [];
44517
+ const harnesses = [...new Set(deps.harnesses)].filter(isBrokerableHarness);
44518
+ for (const harness of harnesses) {
44519
+ const provider = BROKERABLE_HARNESS_PROVIDER[harness];
44520
+ let takes;
44521
+ try {
44522
+ takes = slotTakesPool(deps.store, provider, harness);
44523
+ } catch (error2) {
44524
+ const detail = error2 instanceof Error ? error2.message : String(error2);
44525
+ deps.log(
44526
+ `credential pool sync: custody for ${harness} is unreadable, so it was not synced: ${detail}`
44527
+ );
44528
+ reports.push({ harness, synced: false, reason: "fetch_failed", detail });
44529
+ continue;
44530
+ }
44531
+ if (!takes) {
44532
+ reports.push({ harness, synced: false, reason: "not_brokered" });
44533
+ continue;
44534
+ }
44535
+ let credentials2;
44536
+ try {
44537
+ credentials2 = (await deps.client.modelCredentials(harness)).credentials;
44538
+ } catch (error2) {
44539
+ const detail = error2 instanceof ControlError ? controlErrorMessage(error2) : error2 instanceof Error ? error2.message : String(error2);
44540
+ deps.log(
44541
+ `credential pool sync: could not read the credentials saved for ${harness}, so custody keeps what it holds: ${detail}`
44542
+ );
44543
+ reports.push({ harness, synced: false, reason: "fetch_failed", detail });
44544
+ continue;
44545
+ }
44546
+ const members2 = [];
44547
+ for (const credential of credentials2) {
44548
+ const member4 = poolMemberOf(credential, provider, harness);
44549
+ if ("skipped" in member4) {
44550
+ deps.log(
44551
+ `credential pool sync: ${credential.id} does not join ${harness}'s pool: ${member4.skipped}`
44552
+ );
44553
+ continue;
44554
+ }
44555
+ members2.push(member4);
44556
+ }
44557
+ try {
44558
+ const outcome = deps.store.syncPool(
44559
+ provider,
44560
+ harness,
44561
+ members2,
44562
+ deps.now()
44563
+ );
44564
+ if (outcome.synced)
44565
+ deps.log(
44566
+ `credential pool sync: ${harness} holds ${outcome.added + outcome.kept} saved credentials after its own (${outcome.added} added, ${outcome.removed} removed)`
44567
+ );
44568
+ reports.push({ harness, ...outcome });
44569
+ } catch (error2) {
44570
+ const detail = error2 instanceof Error ? error2.message : String(error2);
44571
+ deps.log(
44572
+ `credential pool sync: custody for ${harness} could not be written, so it keeps what it held: ${detail}`
44573
+ );
44574
+ reports.push({ harness, synced: false, reason: "fetch_failed", detail });
44575
+ }
44576
+ }
44577
+ return reports;
44578
+ }
44579
+ function createCredentialStateReporter(deps) {
44580
+ const sent = /* @__PURE__ */ new Map();
44581
+ return (credentialId, report) => {
44582
+ const key = report.state === "invalid" ? `invalid:${report.reason}` : report.state;
44583
+ const at2 = deps.now();
44584
+ const last = sent.get(credentialId);
44585
+ if (last !== void 0 && last.key === key && at2 - last.at < CREDENTIAL_REPORT_REPEAT_MS)
44586
+ return;
44587
+ sent.set(credentialId, { key, at: at2 });
44588
+ void deps.client.reportModelCredential(credentialId, report).catch((error2) => {
44589
+ sent.delete(credentialId);
44590
+ deps.log(
44591
+ `credential pool: could not tell Oxagen that ${credentialId} is ${report.state}: ${error2 instanceof ControlError ? controlErrorMessage(error2) : error2 instanceof Error ? error2.message : String(error2)}`
44592
+ );
44593
+ });
44594
+ };
44595
+ }
44596
+ var CREDENTIAL_POOL_SYNC_MS, CREDENTIAL_REPORT_REPEAT_MS;
44597
+ var init_credential_pool = __esm({
44598
+ "../../packages/tacho/src/host/credential-pool.ts"() {
44599
+ "use strict";
44600
+ init_credential_store();
44601
+ init_control_client();
44602
+ init_wire();
44603
+ CREDENTIAL_POOL_SYNC_MS = 15 * 6e4;
44604
+ CREDENTIAL_REPORT_REPEAT_MS = 6e4;
43634
44605
  }
43635
44606
  });
43636
44607
 
@@ -50763,8 +51734,8 @@ function createGithubProxy(deps) {
50763
51734
  const path2 = requestPath(url2.pathname, lease);
50764
51735
  const service = url2.searchParams.get("service");
50765
51736
  const discovery = path2?.service === "info/refs" && req.method === "GET" && url2.searchParams.size === 1 && ["git-receive-pack", "git-upload-pack"].includes(service ?? "");
50766
- const exchange = path2 !== void 0 && path2.service !== "info/refs" && req.method === "POST" && url2.search === "" && req.headers["content-type"] === `application/x-${path2.service}-request`;
50767
- if (!path2 || !discovery && !exchange) {
51737
+ const exchange2 = path2 !== void 0 && path2.service !== "info/refs" && req.method === "POST" && url2.search === "" && req.headers["content-type"] === `application/x-${path2.service}-request`;
51738
+ if (!path2 || !discovery && !exchange2) {
50768
51739
  reply(
50769
51740
  res,
50770
51741
  403,
@@ -50891,7 +51862,7 @@ function createGithubProxy(deps) {
50891
51862
  headers,
50892
51863
  redirect: "manual",
50893
51864
  signal: controller.signal,
50894
- ...exchange ? {
51865
+ ...exchange2 ? {
50895
51866
  body: Readable.toWeb(
50896
51867
  Readable.from(body2())
50897
51868
  ),
@@ -51304,9 +52275,9 @@ var init_memory_send = __esm({
51304
52275
  "../../packages/tacho/src/collector/memory-capture/memory-send.ts"() {
51305
52276
  "use strict";
51306
52277
  MemoryRateLimited = class extends Error {
51307
- constructor(retryAfterMs2) {
52278
+ constructor(retryAfterMs3) {
51308
52279
  super("memory upload: the control plane answered 429");
51309
- this.retryAfterMs = retryAfterMs2;
52280
+ this.retryAfterMs = retryAfterMs3;
51310
52281
  this.name = "MemoryRateLimited";
51311
52282
  }
51312
52283
  retryAfterMs;
@@ -52059,7 +53030,7 @@ async function postToControlPlane(fetch2, host, path2, body2, signal) {
52059
53030
  body: payload,
52060
53031
  signal
52061
53032
  });
52062
- const retryAfterMs2 = parseRetryAfter(
53033
+ const retryAfterMs3 = parseRetryAfter(
52063
53034
  response.headers?.get("retry-after") ?? null,
52064
53035
  Date.now()
52065
53036
  );
@@ -52067,7 +53038,7 @@ async function postToControlPlane(fetch2, host, path2, body2, signal) {
52067
53038
  ok: response.ok,
52068
53039
  status: response.status,
52069
53040
  text: await response.text(),
52070
- ...retryAfterMs2 !== void 0 ? { retryAfterMs: retryAfterMs2 } : {}
53041
+ ...retryAfterMs3 !== void 0 ? { retryAfterMs: retryAfterMs3 } : {}
52071
53042
  };
52072
53043
  }
52073
53044
  function changedFailureLog(write) {
@@ -58096,13 +59067,13 @@ function providerError(provider, status2, code, message2) {
58096
59067
  const body2 = provider === "anthropic" ? {
58097
59068
  type: "error",
58098
59069
  error: {
58099
- type: status2 === 401 ? "authentication_error" : status2 === 403 ? "permission_error" : "api_error",
59070
+ type: status2 === 401 ? "authentication_error" : status2 === 403 ? "permission_error" : status2 === 429 ? "rate_limit_error" : "api_error",
58100
59071
  message: `${message2} (${code})`
58101
59072
  }
58102
59073
  } : {
58103
59074
  error: {
58104
59075
  message: message2,
58105
- type: status2 === 401 || status2 === 403 ? "invalid_request_error" : "server_error",
59076
+ type: status2 === 401 || status2 === 403 ? "invalid_request_error" : status2 === 429 ? "rate_limit_exceeded" : "server_error",
58106
59077
  param: null,
58107
59078
  code: status2 === 401 ? "invalid_api_key" : code
58108
59079
  }
@@ -58466,6 +59437,7 @@ import {
58466
59437
  Agent as HttpAgent
58467
59438
  } from "node:http";
58468
59439
  import { Agent as HttpsAgent, request as httpsRequest } from "node:https";
59440
+ import { PassThrough } from "node:stream";
58469
59441
  async function landedWithin(landing, ms) {
58470
59442
  let timer;
58471
59443
  try {
@@ -58647,6 +59619,95 @@ function presentedCredential(req) {
58647
59619
  function credentialRefusalStatus(code) {
58648
59620
  return code === "run_token_expired" || code === "run_token_invalid" || code === "run_token_malformed" ? 401 : 403;
58649
59621
  }
59622
+ function memberName(member4) {
59623
+ const tail = member4.hint !== void 0 && member4.hint.length > 0 ? `\u2026${member4.hint}` : "a credential";
59624
+ return `${tail} (${isLoginKind(member4.kind) ? "login" : "key"})`;
59625
+ }
59626
+ function holdOf(failure4, now) {
59627
+ return {
59628
+ kind: failure4.kind,
59629
+ until: isUsageLimit(failure4) ? failure4.until.getTime() : now + DEAD_CREDENTIAL_HOLD_MS
59630
+ };
59631
+ }
59632
+ function exhaustedRefusal(provider, members2, now) {
59633
+ const vendor = provider === "anthropic" ? "Anthropic" : "OpenAI";
59634
+ const lines = members2.map(({ member: member4, kind, until }) => {
59635
+ const words3 = FAILURE_WORDS[kind];
59636
+ return kind === "invalid_token" || kind === "account_deactivated" ? `${memberName(member4)} ${words3}` : `${memberName(member4)} ${words3} until ${new Date(until).toISOString()}`;
59637
+ });
59638
+ const resets = members2.filter(
59639
+ ({ kind }) => kind === "rate_limit" || kind === "usage_limit" || kind === "credit_exhausted"
59640
+ ).map(({ until }) => until);
59641
+ const soonest = resets.length === 0 ? void 0 : Math.min(...resets);
59642
+ const message2 = `Every ${vendor} credential this machine holds failed: ${lines.join("; ")}. ${soonest === void 0 ? "Save another credential in Oxagen." : "Save another credential in Oxagen, or wait for a limit to reset."}`;
59643
+ if (soonest !== void 0 && soonest - now <= EXHAUSTED_RETRY_MAX_MS)
59644
+ return {
59645
+ status: 429,
59646
+ message: message2,
59647
+ retryAfterSeconds: Math.max(1, Math.ceil((soonest - now) / 1e3))
59648
+ };
59649
+ return { status: 403, message: message2 };
59650
+ }
59651
+ function attachOf(held) {
59652
+ if (held.kind !== "chatgpt") return { kind: held.kind, secret: held.secret };
59653
+ const login = decodeChatGptLogin(held.secret);
59654
+ if (login === void 0) return void 0;
59655
+ return {
59656
+ kind: "chatgpt",
59657
+ secret: login.access_token,
59658
+ ...login.account_id !== void 0 ? { accountId: login.account_id } : {}
59659
+ };
59660
+ }
59661
+ function headerLookup(response) {
59662
+ return {
59663
+ get: (name2) => {
59664
+ const value = response.headers[name2.toLowerCase()];
59665
+ return typeof value === "string" ? value : Array.isArray(value) ? value.join(", ") : null;
59666
+ }
59667
+ };
59668
+ }
59669
+ function peekResponse(response, max2) {
59670
+ return new Promise((resolve29) => {
59671
+ const chunks = [];
59672
+ let size = 0;
59673
+ const done = (result2) => {
59674
+ response.off("data", onData);
59675
+ response.off("end", onEnd);
59676
+ response.off("error", onFail);
59677
+ response.off("aborted", onAborted);
59678
+ resolve29(result2);
59679
+ };
59680
+ const onData = (chunk) => {
59681
+ chunks.push(chunk);
59682
+ size += chunk.length;
59683
+ if (size > max2) {
59684
+ response.pause();
59685
+ done({ chunks, ended: false });
59686
+ }
59687
+ };
59688
+ const onEnd = () => done({ chunks, ended: true });
59689
+ const onFail = (error2) => done({ chunks, ended: false, failed: error2 });
59690
+ const onAborted = () => done({ chunks, ended: false, failed: new Error("aborted") });
59691
+ response.on("data", onData);
59692
+ response.once("end", onEnd);
59693
+ response.once("error", onFail);
59694
+ response.once("aborted", onAborted);
59695
+ });
59696
+ }
59697
+ function replayOf(response, peeked2) {
59698
+ const replay = new PassThrough();
59699
+ for (const chunk of peeked2.chunks) replay.write(chunk);
59700
+ if (peeked2.failed !== void 0) {
59701
+ replay.destroy(peeked2.failed);
59702
+ } else if (peeked2.ended) {
59703
+ replay.end();
59704
+ } else {
59705
+ response.on("error", (error2) => replay.destroy(error2));
59706
+ response.on("aborted", () => replay.destroy(new Error("aborted")));
59707
+ response.pipe(replay);
59708
+ }
59709
+ return replay;
59710
+ }
58650
59711
  function createModelProxy(deps) {
58651
59712
  const maxRequestBytes = deps.maxRequestBytes ?? DEFAULT_MAX_REQUEST_BYTES;
58652
59713
  const upstreamIdleMs = deps.upstreamIdleMs ?? DEFAULT_UPSTREAM_IDLE_MS;
@@ -58926,44 +59987,54 @@ function createModelProxy(deps) {
58926
59987
  }
58927
59988
  };
58928
59989
  }
58929
- const held2 = broker.custody(route.provider, owner);
58930
- if (held2 === void 0) {
58931
- return {
58932
- basis: TACHO_CREDENTIAL_GATEWAY_BROKERED,
58933
- claims: verdict.claims,
58934
- refusal: {
58935
- code: "credential_unavailable",
58936
- message: CREDENTIAL_MESSAGES.credential_unavailable
58937
- }
58938
- };
58939
- }
58940
- if (held2.kind === "chatgpt") {
58941
- const login = decodeChatGptLogin(held2.secret);
58942
- if (login === void 0)
58943
- return {
58944
- basis: TACHO_CREDENTIAL_GATEWAY_BROKERED,
58945
- claims: verdict.claims,
58946
- refusal: {
58947
- code: "credential_unavailable",
58948
- message: CREDENTIAL_MESSAGES.credential_unavailable
58949
- }
58950
- };
58951
- return {
58952
- basis: TACHO_CREDENTIAL_GATEWAY_BROKERED,
58953
- claims: verdict.claims,
58954
- attach: {
58955
- kind: "chatgpt",
58956
- secret: login.access_token,
58957
- ...login.account_id !== void 0 ? { accountId: login.account_id } : {}
58958
- }
58959
- };
59990
+ const unavailable = {
59991
+ basis: TACHO_CREDENTIAL_GATEWAY_BROKERED,
59992
+ claims: verdict.claims,
59993
+ refusal: {
59994
+ code: "credential_unavailable",
59995
+ message: CREDENTIAL_MESSAGES.credential_unavailable
59996
+ }
59997
+ };
59998
+ const pool = broker.pool;
59999
+ if (pool !== void 0) {
60000
+ const fits = memberFits(route);
60001
+ const now = deps.now();
60002
+ const passed = /* @__PURE__ */ new Set();
60003
+ for (; ; ) {
60004
+ const member4 = pool.next(route.provider, owner, {
60005
+ now,
60006
+ fits,
60007
+ tried: passed,
60008
+ allowHeldBack: true
60009
+ });
60010
+ if (member4 === void 0) return unavailable;
60011
+ const held3 = pool.open(route.provider, owner, member4.id);
60012
+ const attach2 = held3 === void 0 ? void 0 : attachOf(held3);
60013
+ if (attach2 !== void 0)
60014
+ return {
60015
+ basis: TACHO_CREDENTIAL_GATEWAY_BROKERED,
60016
+ claims: verdict.claims,
60017
+ attach: attach2,
60018
+ member: member4,
60019
+ poolSize: pool.members(route.provider, owner).filter(fits).length
60020
+ };
60021
+ passed.add(member4.id);
60022
+ }
58960
60023
  }
60024
+ const held2 = broker.custody(route.provider, owner);
60025
+ const attach = held2 === void 0 ? void 0 : attachOf(held2);
60026
+ if (attach === void 0) return unavailable;
58961
60027
  return {
58962
60028
  basis: TACHO_CREDENTIAL_GATEWAY_BROKERED,
58963
60029
  claims: verdict.claims,
58964
- attach: { kind: held2.kind, secret: held2.secret }
60030
+ attach
58965
60031
  };
58966
60032
  }
60033
+ function memberFits(route) {
60034
+ const chatgpt = route.upstream === "chatgpt";
60035
+ const copiesServe = deps.credentials?.pool?.copiesServe?.(route.upstream) ?? true;
60036
+ return (member4) => member4.kind === "chatgpt" === chatgpt && (copiesServe || member4.source !== VAULT_POOL_SOURCE);
60037
+ }
58967
60038
  function attrsFor(route, how, credential) {
58968
60039
  return {
58969
60040
  [TACHO_ENFORCEMENT_TIER_ATTR]: TACHO_GATEWAY_TIER,
@@ -59057,7 +60128,7 @@ function createModelProxy(deps) {
59057
60128
  lost(error2);
59058
60129
  }
59059
60130
  }
59060
- function sendProviderError(res, route, status2, code, message2, retryable = false) {
60131
+ function sendProviderError(res, route, status2, code, message2, retryable = false, retryAfterSeconds) {
59061
60132
  if (heldStreams.has(res)) {
59062
60133
  if (!res.writableEnded)
59063
60134
  res.end(heldStreamErrorEvent(status2, void 0, message2));
@@ -59077,7 +60148,7 @@ function createModelProxy(deps) {
59077
60148
  // should a failure on the way to the vendor, a second later: without
59078
60149
  // it a reset connection reached the person as a failed turn.
59079
60150
  "x-should-retry": retryable ? "true" : "false",
59080
- ...retryable ? { "retry-after": "1" } : {}
60151
+ ...retryable ? { "retry-after": String(retryAfterSeconds ?? 1) } : {}
59081
60152
  });
59082
60153
  res.end(error2.body);
59083
60154
  }
@@ -59856,15 +60927,24 @@ function createModelProxy(deps) {
59856
60927
  const responseBody = new BodyCapture();
59857
60928
  let meter;
59858
60929
  let settledUsage;
59859
- const headers = upstreamRequestHeaders(
59860
- req.rawHeaders,
59861
- target.host,
59862
- body2.length,
59863
- dropContentEncoding,
59864
- credential.attach
59865
- );
59866
- if (deps.cloudGateway && record2 !== void 0)
59867
- headers.push(MODEL_STEERING_RUN_HEADER, record2.recorder.sessionUuid);
60930
+ let currentAttach = credential.attach;
60931
+ let currentMember = credential.member;
60932
+ const headersFor = (attach) => {
60933
+ const built = upstreamRequestHeaders(
60934
+ req.rawHeaders,
60935
+ target.host,
60936
+ body2.length,
60937
+ dropContentEncoding,
60938
+ attach
60939
+ );
60940
+ if (deps.cloudGateway && record2 !== void 0)
60941
+ built.push(MODEL_STEERING_RUN_HEADER, record2.recorder.sessionUuid);
60942
+ return built;
60943
+ };
60944
+ let headers = headersFor(currentAttach);
60945
+ let loginRefreshed = false;
60946
+ const tried = /* @__PURE__ */ new Set();
60947
+ const rotation = [];
59868
60948
  const settle4 = (errorClass2) => {
59869
60949
  if (settled2) return;
59870
60950
  settled2 = true;
@@ -59923,7 +61003,7 @@ function createModelProxy(deps) {
59923
61003
  target.host,
59924
61004
  keepAliveCandidate.body.length,
59925
61005
  true,
59926
- credential.attach
61006
+ currentAttach
59927
61007
  ),
59928
61008
  ...deps.cloudGateway ? [MODEL_STEERING_RUN_HEADER, record2.recorder.sessionUuid] : []
59929
61009
  ],
@@ -59996,7 +61076,7 @@ function createModelProxy(deps) {
59996
61076
  priced,
59997
61077
  familyPriced,
59998
61078
  settledAt,
59999
- durationMs,
61079
+ durationMs: durationMs2,
60000
61080
  failed: failed5
60001
61081
  }) => {
60002
61082
  const responseText = responseBody.text();
@@ -60023,7 +61103,7 @@ function createModelProxy(deps) {
60023
61103
  estimated: cut || unreported || familyPriced,
60024
61104
  requestEffort,
60025
61105
  ttftMs: firstByteAt !== void 0 ? Math.max(0, firstByteAt - startedAt) : void 0,
60026
- durationMs,
61106
+ durationMs: durationMs2,
60027
61107
  status: status2,
60028
61108
  failed: failed5,
60029
61109
  requestId
@@ -60103,9 +61183,17 @@ function createModelProxy(deps) {
60103
61183
  upstreamReq?.destroy(new Error("client closed the connection"));
60104
61184
  settle4(abortReason !== void 0 ? "interrupted" : "client_aborted");
60105
61185
  });
60106
- const onResponse = (upstream) => {
61186
+ const deliver = (upstream, stream) => {
60107
61187
  status2 = upstream.statusCode ?? 502;
60108
61188
  firstByteAt = deps.now();
61189
+ if (rotation.length > 0)
61190
+ attrs2[CREDENTIAL_ROTATION_ATTR] = rotationAttr(currentMember);
61191
+ if (metered && status2 < 400 && currentMember?.failure !== void 0 && deps.credentials?.pool !== void 0)
61192
+ deps.credentials.pool.served(
61193
+ route.provider,
61194
+ custodyHarnessFor(route),
61195
+ currentMember
61196
+ );
60109
61197
  const idHeader = upstream.headers["request-id"] ?? upstream.headers["x-request-id"];
60110
61198
  requestId = typeof idHeader === "string" ? idHeader.slice(0, 512) : void 0;
60111
61199
  const contentType2 = upstream.headers["content-type"];
@@ -60141,7 +61229,7 @@ function createModelProxy(deps) {
60141
61229
  res.flushHeaders();
60142
61230
  res.socket?.setNoDelay(true);
60143
61231
  }
60144
- upstream.on("data", (chunk) => {
61232
+ stream.on("data", (chunk) => {
60145
61233
  if (settled2) return;
60146
61234
  if (heldError !== void 0 && heldErrorBytes < HELD_STREAM_ERROR_BYTES) {
60147
61235
  heldError.push(chunk);
@@ -60156,7 +61244,7 @@ function createModelProxy(deps) {
60156
61244
  }
60157
61245
  });
60158
61246
  const settleDeferred = (errorClass2) => process.nextTick(() => settle4(errorClass2));
60159
- upstream.on("end", () => {
61247
+ stream.on("end", () => {
60160
61248
  if (heldError !== void 0 && !res.writableEnded)
60161
61249
  res.end(
60162
61250
  heldStreamErrorEvent(
@@ -60187,11 +61275,174 @@ function createModelProxy(deps) {
60187
61275
  settle4(abortReason !== void 0 ? "interrupted" : "upstream_reset");
60188
61276
  res.destroy();
60189
61277
  };
60190
- upstream.on("error", failResponse);
60191
- upstream.on("aborted", () => {
61278
+ stream.on("error", failResponse);
61279
+ stream.on("aborted", () => {
60192
61280
  failResponse();
60193
61281
  });
60194
- if (heldError === void 0) upstream.pipe(res);
61282
+ if (heldError === void 0) stream.pipe(res);
61283
+ };
61284
+ const rotationAttr = (last) => [
61285
+ ...rotation.map(({ member: member4, kind }) => `${member4.id}:${kind}`),
61286
+ ...last !== void 0 && !rotation.some((r) => r.member === last) ? [`${last.id}:answered`] : []
61287
+ ].join(",");
61288
+ const refreshesLogin = (answered) => answered === 401 && !loginRefreshed && currentMember?.kind === "chatgpt" && currentMember.refresh_refused === void 0 && deps.credentials?.pool?.refreshLogin !== void 0;
61289
+ const checksCredential = (answered) => deps.credentials?.pool !== void 0 && currentMember !== void 0 && ((credential.poolSize ?? 0) >= 2 && mayBeModelFailure(route.provider, answered) || refreshesLogin(answered));
61290
+ const onResponse = (upstream) => {
61291
+ const answered = upstream.statusCode ?? 502;
61292
+ if (!checksCredential(answered)) {
61293
+ deliver(upstream, upstream);
61294
+ return;
61295
+ }
61296
+ void checkCredential(upstream, answered).catch((error2) => {
61297
+ deps.log(
61298
+ `model proxy: the credential check of ${target.host}'s answer failed: ${error2 instanceof Error ? error2.message : String(error2)} session=${sessionKey}`
61299
+ );
61300
+ if (settled2) return;
61301
+ upstream.destroy();
61302
+ settle4("gateway_error");
61303
+ sendProviderError(
61304
+ res,
61305
+ route,
61306
+ 502,
61307
+ "gateway_error",
61308
+ `The Oxagen gateway could not read the answer from ${target.host}. Retry the call.`,
61309
+ true
61310
+ );
61311
+ });
61312
+ };
61313
+ const checkCredential = async (upstream, answered) => {
61314
+ const peeked2 = await peekResponse(upstream, MODEL_FAILURE_BODY_MAX_BYTES);
61315
+ if (settled2 || abortReason !== void 0) {
61316
+ upstream.destroy();
61317
+ if (!settled2) settle4("interrupted");
61318
+ return;
61319
+ }
61320
+ if (peeked2.failed !== void 0 || !peeked2.ended) {
61321
+ deliver(upstream, replayOf(upstream, peeked2));
61322
+ return;
61323
+ }
61324
+ const encoding = upstream.headers["content-encoding"];
61325
+ const text6 = (await readableModelBody(
61326
+ Buffer.concat(peeked2.chunks),
61327
+ typeof encoding === "string" ? encoding : void 0,
61328
+ MODEL_FAILURE_BODY_MAX_BYTES
61329
+ ))?.toString("utf8");
61330
+ if (settled2 || abortReason !== void 0) {
61331
+ if (!settled2) settle4("interrupted");
61332
+ return;
61333
+ }
61334
+ const now = deps.now();
61335
+ const failure4 = classifyModelFailure(
61336
+ route.provider,
61337
+ answered,
61338
+ headerLookup(upstream),
61339
+ text6 ?? null,
61340
+ new Date(now)
61341
+ );
61342
+ const pool = deps.credentials?.pool;
61343
+ const failed5 = currentMember;
61344
+ const owner = custodyHarnessFor(route);
61345
+ let refreshFailed;
61346
+ if (failure4?.kind === "invalid_token" && refreshesLogin(answered) && pool?.refreshLogin !== void 0 && failed5 !== void 0) {
61347
+ loginRefreshed = true;
61348
+ const refreshed = await pool.refreshLogin(
61349
+ route.provider,
61350
+ owner,
61351
+ failed5
61352
+ );
61353
+ if (settled2 || abortReason !== void 0) {
61354
+ if (!settled2) settle4("interrupted");
61355
+ return;
61356
+ }
61357
+ const held2 = refreshed.outcome === "refreshed" ? pool.open(route.provider, owner, failed5.id) : void 0;
61358
+ const attach = held2 === void 0 ? void 0 : attachOf(held2);
61359
+ if (attach !== void 0) {
61360
+ deps.log(
61361
+ `model proxy: refreshed the ChatGPT login ${memberName(failed5)} after a 401; sending the call again on it session=${sessionKey}`
61362
+ );
61363
+ currentAttach = attach;
61364
+ headers = headersFor(attach);
61365
+ upstreamReq = openUpstream(false);
61366
+ return;
61367
+ }
61368
+ refreshFailed = refreshed.outcome === "refreshed" ? "failed" : refreshed.outcome;
61369
+ deps.log(
61370
+ `model proxy: could not refresh the ChatGPT login ${memberName(failed5)} after a 401: ${refreshed.outcome === "refreshed" ? "custody did not open the new tokens" : refreshed.detail} session=${sessionKey}`
61371
+ );
61372
+ }
61373
+ if (failure4 === null || pool === void 0 || failed5 === void 0 || (credential.poolSize ?? 0) < 2) {
61374
+ deliver(upstream, replayOf(upstream, peeked2));
61375
+ return;
61376
+ }
61377
+ const hold = {
61378
+ ...holdOf(failure4, now),
61379
+ ...refreshFailed !== void 0 ? { refresh: refreshFailed } : {}
61380
+ };
61381
+ tried.add(failed5.id);
61382
+ rotation.push({ member: failed5, kind: failure4.kind, until: hold.until });
61383
+ pool.markFailed(route.provider, owner, failed5, hold, now);
61384
+ const loginsOnly = failure4.kind === "rate_limit" && isLoginKind(failed5.kind);
61385
+ const fits = memberFits(route);
61386
+ for (; ; ) {
61387
+ const next = pool.next(route.provider, owner, {
61388
+ now,
61389
+ fits,
61390
+ tried,
61391
+ loginsOnly,
61392
+ allowHeldBack: false
61393
+ });
61394
+ if (next === void 0) break;
61395
+ const held2 = pool.open(route.provider, owner, next.id);
61396
+ const attach = held2 === void 0 ? void 0 : attachOf(held2);
61397
+ if (attach === void 0) {
61398
+ tried.add(next.id);
61399
+ continue;
61400
+ }
61401
+ deps.log(
61402
+ `model proxy: ${route.provider} credential ${memberName(failed5)} ${FAILURE_WORDS[failure4.kind]}; sending the call again on ${memberName(next)} session=${sessionKey}`
61403
+ );
61404
+ currentMember = next;
61405
+ currentAttach = attach;
61406
+ headers = headersFor(attach);
61407
+ upstreamReq = openUpstream(false);
61408
+ return;
61409
+ }
61410
+ const members2 = pool.members(route.provider, owner).filter(fits);
61411
+ if (loginsOnly && members2.some(
61412
+ (member4) => !tried.has(member4.id) && !isLoginKind(member4.kind)
61413
+ )) {
61414
+ deliver(upstream, replayOf(upstream, peeked2));
61415
+ return;
61416
+ }
61417
+ const failures = members2.flatMap((member4) => {
61418
+ const here = rotation.find((r) => r.member.id === member4.id);
61419
+ if (here !== void 0)
61420
+ return [{ member: member4, kind: here.kind, until: here.until }];
61421
+ if (tried.has(member4.id) || member4.failure === void 0) return [];
61422
+ return [
61423
+ {
61424
+ member: member4,
61425
+ kind: member4.failure.kind,
61426
+ until: Date.parse(member4.failure.until)
61427
+ }
61428
+ ];
61429
+ });
61430
+ const refusal = exhaustedRefusal(route.provider, failures, now);
61431
+ status2 = refusal.status;
61432
+ attrs2[CREDENTIAL_ROTATION_ATTR] = rotationAttr(void 0);
61433
+ deps.log(
61434
+ `model proxy: every ${route.provider} credential failed (${rotationAttr(void 0)}) session=${sessionKey}`
61435
+ );
61436
+ settle4(CREDENTIALS_EXHAUSTED);
61437
+ sendProviderError(
61438
+ res,
61439
+ route,
61440
+ refusal.status,
61441
+ CREDENTIALS_EXHAUSTED,
61442
+ refusal.message,
61443
+ refusal.retryAfterSeconds !== void 0,
61444
+ refusal.retryAfterSeconds
61445
+ );
60195
61446
  };
60196
61447
  const onError = (failed5, error2) => {
60197
61448
  if (settled2 || failed5 !== upstreamReq) return;
@@ -60394,7 +61645,7 @@ function createModelProxy(deps) {
60394
61645
  }
60395
61646
  };
60396
61647
  }
60397
- var DEFAULT_MAX_REQUEST_BYTES, NOT_FORWARDED_ATTR, DEFAULT_UPSTREAM_IDLE_MS, DEFAULT_BEFORE_FORWARD_TIMEOUT_MS, DEFAULT_UPSTREAM_CONNECT_MS, DEFAULT_REFUSAL_FRAME_WAIT_MS, DEFAULT_PAUSE_HOLD_MS, DEFAULT_PAUSE_STREAM_HOLD_MS, DEFAULT_PAUSE_HOLD_PING_MS, DEFAULT_PAUSE_HOLD_CHECK_MS, MAX_HELD_CALLS_PER_SESSION, PAUSE_HOLD_CODES, ANTHROPIC_PING_EVENT, HELD_STREAM_ERROR_BYTES, FREE_SOCKET_TIMEOUT_MS, KEEP_ALIVE_TIMEOUT_MS, KEEP_ALIVE_MAX_RESPONSE_BYTES, BodyCapture, EXCHANGE_OPEN_BYTES, EXCHANGE_JOIN_BYTES, REQUEST_EFFORT_MAX, CREDENTIAL_MESSAGES;
61648
+ var DEFAULT_MAX_REQUEST_BYTES, NOT_FORWARDED_ATTR, DEFAULT_UPSTREAM_IDLE_MS, DEFAULT_BEFORE_FORWARD_TIMEOUT_MS, DEFAULT_UPSTREAM_CONNECT_MS, DEFAULT_REFUSAL_FRAME_WAIT_MS, DEFAULT_PAUSE_HOLD_MS, DEFAULT_PAUSE_STREAM_HOLD_MS, DEFAULT_PAUSE_HOLD_PING_MS, DEFAULT_PAUSE_HOLD_CHECK_MS, MAX_HELD_CALLS_PER_SESSION, PAUSE_HOLD_CODES, ANTHROPIC_PING_EVENT, HELD_STREAM_ERROR_BYTES, FREE_SOCKET_TIMEOUT_MS, KEEP_ALIVE_TIMEOUT_MS, KEEP_ALIVE_MAX_RESPONSE_BYTES, BodyCapture, EXCHANGE_OPEN_BYTES, EXCHANGE_JOIN_BYTES, REQUEST_EFFORT_MAX, CREDENTIALS_EXHAUSTED, CREDENTIAL_ROTATION_ATTR, EXHAUSTED_RETRY_MAX_MS, FAILURE_WORDS, CREDENTIAL_MESSAGES;
60398
61649
  var init_model_proxy = __esm({
60399
61650
  "../../packages/tacho/src/collector/model-proxy.ts"() {
60400
61651
  "use strict";
@@ -60409,7 +61660,9 @@ var init_model_proxy = __esm({
60409
61660
  init_replay_grade();
60410
61661
  init_bundle();
60411
61662
  init_redaction();
61663
+ init_credential_store();
60412
61664
  init_model_credential();
61665
+ init_model_failure();
60413
61666
  init_run_token();
60414
61667
  init_wire();
60415
61668
  init_cache_keep_alive();
@@ -60469,6 +61722,16 @@ var init_model_proxy = __esm({
60469
61722
  EXCHANGE_OPEN_BYTES = Buffer.byteLength('{"request":');
60470
61723
  EXCHANGE_JOIN_BYTES = Buffer.byteLength(',"response":');
60471
61724
  REQUEST_EFFORT_MAX = 32;
61725
+ CREDENTIALS_EXHAUSTED = "credentials_exhausted";
61726
+ CREDENTIAL_ROTATION_ATTR = "oxagen.credential_rotation";
61727
+ EXHAUSTED_RETRY_MAX_MS = 5 * 6e4;
61728
+ FAILURE_WORDS = {
61729
+ rate_limit: "hit a rate limit",
61730
+ usage_limit: "reached its usage limit",
61731
+ credit_exhausted: "has no credit left",
61732
+ invalid_token: "was refused as an invalid token",
61733
+ account_deactivated: "belongs to a deactivated account"
61734
+ };
60472
61735
  CREDENTIAL_MESSAGES = {
60473
61736
  run_token_malformed: "The credential this call carried is not a run token this Oxagen gateway can read. Run `oxagen agent enroll` again to point the harness at the gateway's run tokens.",
60474
61737
  run_token_invalid: "The run token this call carried was not issued by this Oxagen gateway. Run `oxagen credential status` on this machine.",
@@ -61105,6 +62368,15 @@ function createRequestHandler(api, log, options = {}) {
61105
62368
  );
61106
62369
  return;
61107
62370
  }
62371
+ if (path2 === "/credential/sync") {
62372
+ if (api.syncCredentialPools === void 0) {
62373
+ send2(res, 404, { error: "this daemon keeps no credential pool" });
62374
+ return;
62375
+ }
62376
+ const answer = await api.syncCredentialPools();
62377
+ send2(res, answer.status, answer.body);
62378
+ return;
62379
+ }
61108
62380
  if (path2 === "/credential/issue") {
61109
62381
  if (api.issueRunToken === void 0) {
61110
62382
  send2(res, 404, { error: "this daemon issues no run tokens" });
@@ -62627,7 +63899,16 @@ function cloudGatewayCredentialStore(disk, runToken) {
62627
63899
  );
62628
63900
  },
62629
63901
  release: () => void 0,
62630
- status: () => []
63902
+ status: () => [],
63903
+ // The cloud gateway holds the operator's pool and moves a call through
63904
+ // it itself (`gateway.model.ts`), so a sandbox's gateway holds none.
63905
+ pool: () => [],
63906
+ open: () => void 0,
63907
+ nextUntried: () => void 0,
63908
+ markFailed: () => false,
63909
+ clearFailure: () => false,
63910
+ replaceSecret: () => false,
63911
+ syncPool: () => ({ synced: false, reason: "sandbox" })
62631
63912
  };
62632
63913
  }
62633
63914
  function readTextOrUndefined(path2) {
@@ -63226,7 +64507,7 @@ async function initializeDaemon(options, server, port, ready, clock2) {
63226
64507
  return { written: 0, dropped: bodies.length };
63227
64508
  }
63228
64509
  const placed = placeBodies(bodies, origin);
63229
- wal.append(events, placed.write, holdOf(placed.hold));
64510
+ wal.append(events, placed.write, holdOf2(placed.hold));
63230
64511
  const evicted = afterPlaced(placed);
63231
64512
  stateDirty = true;
63232
64513
  for (const event of events)
@@ -63306,7 +64587,7 @@ async function initializeDaemon(options, server, port, ready, clock2) {
63306
64587
  }
63307
64588
  return evicted;
63308
64589
  }
63309
- function holdOf(bodies) {
64590
+ function holdOf2(bodies) {
63310
64591
  return bodies.length > 0 ? { bodies, at: now() } : void 0;
63311
64592
  }
63312
64593
  function heldBoundText() {
@@ -64807,7 +66088,7 @@ async function initializeDaemon(options, server, port, ready, clock2) {
64807
66088
  }))
64808
66089
  )
64809
66090
  );
64810
- wal.appendRecovered(terminal.events, placed.write, holdOf(placed.hold));
66091
+ wal.appendRecovered(terminal.events, placed.write, holdOf2(placed.hold));
64811
66092
  afterPlaced(placed);
64812
66093
  const saved = terminal.state.sessions[0];
64813
66094
  const current = saved === void 0 ? void 0 : registry3.list().find(
@@ -65296,6 +66577,88 @@ async function initializeDaemon(options, server, port, ready, clock2) {
65296
66577
  }
65297
66578
  let startupDaySpend;
65298
66579
  let daySpendSeed = Promise.resolve();
66580
+ function custodyRead(read2, fallback) {
66581
+ try {
66582
+ return read2();
66583
+ } catch (error2) {
66584
+ log(
66585
+ `credential store unreadable: ${error2 instanceof Error ? error2.message : String(error2)}; check ${paths.credentials} and ${paths.credentialsKey}, then run \`oxagen credential status\``
66586
+ );
66587
+ return fallback;
66588
+ }
66589
+ }
66590
+ let lastPoolSyncAt = Number.NEGATIVE_INFINITY;
66591
+ const reportCredentialState = createCredentialStateReporter({
66592
+ client,
66593
+ now,
66594
+ log
66595
+ });
66596
+ const chatGptRefresher = createChatGptRefresher({
66597
+ store: credentialStore,
66598
+ fetch: options.fetch ?? fetch,
66599
+ now,
66600
+ refreshed: (member4) => {
66601
+ if (member4.credential_id === void 0) return;
66602
+ if (member4.failure !== void 0 && Date.parse(member4.failure.until) > now())
66603
+ return;
66604
+ reportCredentialState(member4.credential_id, { state: "recovered" });
66605
+ }
66606
+ });
66607
+ const custodyPool = options.cloudGateway !== void 0 ? void 0 : {
66608
+ members: (provider, harness) => custodyRead(() => credentialStore.pool(provider, harness), []),
66609
+ next: (provider, harness, pick4) => custodyRead(
66610
+ () => credentialStore.nextUntried(provider, harness, pick4),
66611
+ void 0
66612
+ ),
66613
+ open: (provider, harness, id2) => custodyRead(
66614
+ () => credentialStore.open(provider, harness, id2),
66615
+ void 0
66616
+ ),
66617
+ markFailed: (provider, harness, member4, failure4, at2) => {
66618
+ custodyRead(
66619
+ () => credentialStore.markFailed(
66620
+ provider,
66621
+ harness,
66622
+ member4.id,
66623
+ {
66624
+ kind: failure4.kind,
66625
+ until: failure4.until,
66626
+ ...failure4.refresh === "rotated" || failure4.refresh === "refused" ? { refreshRefused: failure4.refresh } : {}
66627
+ },
66628
+ at2
66629
+ ),
66630
+ false
66631
+ );
66632
+ if (member4.credential_id === void 0) return;
66633
+ if (failure4.refresh === "rotated" || failure4.refresh === "failed")
66634
+ return;
66635
+ reportCredentialState(
66636
+ member4.credential_id,
66637
+ failure4.kind === "invalid_token" || failure4.kind === "account_deactivated" ? { state: "invalid", reason: failure4.kind } : {
66638
+ state: "limited",
66639
+ until: new Date(failure4.until).toISOString()
66640
+ }
66641
+ );
66642
+ },
66643
+ served: (provider, harness, member4) => {
66644
+ custodyRead(
66645
+ () => credentialStore.clearFailure(provider, harness, member4.id),
66646
+ false
66647
+ );
66648
+ if (member4.credential_id !== void 0)
66649
+ reportCredentialState(member4.credential_id, {
66650
+ state: "recovered"
66651
+ });
66652
+ },
66653
+ // Only Codex's slot holds ChatGPT logins.
66654
+ refreshLogin: (provider, harness, member4) => provider === "openai" && harness === "codex" ? chatGptRefresher.refresh(member4.id) : Promise.resolve({
66655
+ outcome: "failed",
66656
+ detail: `${harness} holds no ChatGPT login to refresh`
66657
+ }),
66658
+ // Never to a base URL the harness named itself, such as a
66659
+ // company's own gateway: it would read the person's own keys.
66660
+ copiesServe: (upstream) => displacedUpstreams[upstream] === void 0
66661
+ };
65299
66662
  const modelProxy = createModelProxy({
65300
66663
  registry: registry3,
65301
66664
  hostRecorder: () => hostRecorder,
@@ -65381,7 +66744,8 @@ async function initializeDaemon(options, server, port, ready, clock2) {
65381
66744
  host: host.host_enrollment_id,
65382
66745
  provider,
65383
66746
  now: now()
65384
- })
66747
+ }),
66748
+ ...custodyPool !== void 0 ? { pool: custodyPool } : {}
65385
66749
  },
65386
66750
  port: () => modelProxyListener.port(),
65387
66751
  log,
@@ -65555,6 +66919,13 @@ async function initializeDaemon(options, server, port, ready, clock2) {
65555
66919
  ...codegraph === void 0 ? {} : {
65556
66920
  codegraph: (route, body2) => answerCodeGraphRoute(codegraph, route, body2)
65557
66921
  },
66922
+ // A sandbox's daemon keeps no pool, so its route answers 404.
66923
+ ...options.cloudGateway === void 0 ? {
66924
+ syncCredentialPools: async () => ({
66925
+ status: 200,
66926
+ body: { pools: await syncPools() }
66927
+ })
66928
+ } : {},
65558
66929
  issueRunToken: (input) => issueRunToken(input, {
65559
66930
  key: runTokenKey,
65560
66931
  store: credentialStore,
@@ -66159,11 +67530,7 @@ async function initializeDaemon(options, server, port, ready, clock2) {
66159
67530
  if (harnesses.includes("codex") && now() - lastLoginRefreshAt >= CHATGPT_LOGIN_CHECK_MS) {
66160
67531
  lastLoginRefreshAt = now();
66161
67532
  try {
66162
- const refreshed = await refreshChatGptCustody(
66163
- credentialStore,
66164
- options.fetch ?? fetch,
66165
- now()
66166
- );
67533
+ const refreshed = await chatGptRefresher.refreshDue();
66167
67534
  if (refreshed === "refreshed")
66168
67535
  log("refreshed the ChatGPT login in custody");
66169
67536
  else if (typeof refreshed === "object")
@@ -66195,10 +67562,38 @@ async function initializeDaemon(options, server, port, ready, clock2) {
66195
67562
  log
66196
67563
  });
66197
67564
  }
67565
+ async function syncPools() {
67566
+ if (options.cloudGateway !== void 0) return [];
67567
+ lastPoolSyncAt = now();
67568
+ const served2 = [];
67569
+ for (const harness of host.harnesses) {
67570
+ const route = POOL_ROUTES[harness];
67571
+ if (route === void 0 || route.upstreams.every((up) => displacedUpstreams[up] === void 0)) {
67572
+ served2.push(harness);
67573
+ continue;
67574
+ }
67575
+ custodyRead(
67576
+ () => credentialStore.syncPool(route.provider, route.harness, [], now()),
67577
+ void 0
67578
+ );
67579
+ }
67580
+ return syncCredentialPools({
67581
+ store: credentialStore,
67582
+ client,
67583
+ harnesses: served2,
67584
+ now,
67585
+ log
67586
+ });
67587
+ }
67588
+ async function syncPoolsWhenDue() {
67589
+ if (now() - lastPoolSyncAt < CREDENTIAL_POOL_SYNC_MS) return;
67590
+ await syncPools();
67591
+ }
66198
67592
  async function tick() {
66199
67593
  await controlTick();
66200
67594
  await renewCertificate();
66201
67595
  await renewStaticTokens();
67596
+ await syncPoolsWhenDue();
66202
67597
  await gitLane;
66203
67598
  }
66204
67599
  let timer;
@@ -66209,7 +67604,7 @@ async function initializeDaemon(options, server, port, ready, clock2) {
66209
67604
  if (pendingSessionEnds.size > 0) void startGitReads();
66210
67605
  if (ticking) return;
66211
67606
  ticking = true;
66212
- controlTick().then(() => renewCertificate()).then(() => renewStaticTokens()).catch((error2) => {
67607
+ controlTick().then(() => renewCertificate()).then(() => renewStaticTokens()).then(() => syncPoolsWhenDue()).catch((error2) => {
66213
67608
  const code = error2 instanceof Error && "code" in error2 ? ` [${String(error2.code)}]` : "";
66214
67609
  const site = error2 instanceof Error && typeof error2.stack === "string" ? error2.stack.split("\n")[1]?.trim() ?? "" : "";
66215
67610
  log(
@@ -66464,7 +67859,7 @@ async function initializeDaemon(options, server, port, ready, clock2) {
66464
67859
  }
66465
67860
  };
66466
67861
  }
66467
- var IDLE_COMMAND_POLL_FACTOR, DEFAULT_TIMERS, STATIC_TOKEN_RENEWAL_CHECK_MS, CERTIFICATE_RENEWAL_RETRY_MS, CHATGPT_LOGIN_CHECK_MS, MEMORY_SCAN_MS, CLOUD_GATEWAY_ORIGIN, CLOUD_GATEWAY_BASE_PATH, QUEUED_PROMPT_CLASS, TRACE_DRAIN_TIMEOUT_MS, RECORDER_EVENTS_KEPT, owedBodyPurgeSchema, objectSchema, spoolFileSchema, otlpResourceListSchema, otlpPayloadSchema, defaultExecAsync, STOPPING, STOPPED_EXEC, STATE_WRITE_DEFER_MS;
67862
+ var IDLE_COMMAND_POLL_FACTOR, DEFAULT_TIMERS, STATIC_TOKEN_RENEWAL_CHECK_MS, CERTIFICATE_RENEWAL_RETRY_MS, CHATGPT_LOGIN_CHECK_MS, MEMORY_SCAN_MS, CLOUD_GATEWAY_ORIGIN, CLOUD_GATEWAY_BASE_PATH, POOL_ROUTES, QUEUED_PROMPT_CLASS, TRACE_DRAIN_TIMEOUT_MS, RECORDER_EVENTS_KEPT, owedBodyPurgeSchema, objectSchema, spoolFileSchema, otlpResourceListSchema, otlpPayloadSchema, defaultExecAsync, STOPPING, STOPPED_EXEC, STATE_WRITE_DEFER_MS;
66468
67863
  var init_daemon = __esm({
66469
67864
  "../../packages/tacho/src/collector/daemon.ts"() {
66470
67865
  "use strict";
@@ -66490,6 +67885,7 @@ var init_daemon = __esm({
66490
67885
  init_model_credential();
66491
67886
  init_static_token_renewal();
66492
67887
  init_chatgpt_refresh();
67888
+ init_credential_pool();
66493
67889
  init_run_token();
66494
67890
  init_process_scan();
66495
67891
  init_retention();
@@ -66582,6 +67978,23 @@ var init_daemon = __esm({
66582
67978
  MEMORY_SCAN_MS = 5 * 6e4;
66583
67979
  CLOUD_GATEWAY_ORIGIN = "https://api.oxagen.sh";
66584
67980
  CLOUD_GATEWAY_BASE_PATH = "/v1/gateway";
67981
+ POOL_ROUTES = {
67982
+ "claude-code": {
67983
+ provider: "anthropic",
67984
+ harness: "claude-code",
67985
+ upstreams: ["anthropic"]
67986
+ },
67987
+ stella: {
67988
+ provider: "anthropic",
67989
+ harness: "stella",
67990
+ upstreams: ["anthropic"]
67991
+ },
67992
+ codex: {
67993
+ provider: "openai",
67994
+ harness: "codex",
67995
+ upstreams: ["openai", "chatgpt"]
67996
+ }
67997
+ };
66585
67998
  QUEUED_PROMPT_CLASS = RETENTION_CLASS_BY_KIND["oxagen:message"] ?? "model_call";
66586
67999
  TRACE_DRAIN_TIMEOUT_MS = 1e4;
66587
68000
  RECORDER_EVENTS_KEPT = 64;
@@ -67621,7 +69034,7 @@ async function daemonRoute(deps, route, body2) {
67621
69034
  }
67622
69035
  return { status: answer.status, body: parsed2 };
67623
69036
  }
67624
- function errorOf(body2, status2) {
69037
+ function errorOf2(body2, status2) {
67625
69038
  const error2 = body2?.error;
67626
69039
  return typeof error2 === "string" ? error2 : `the daemon answered HTTP ${status2}`;
67627
69040
  }
@@ -67631,7 +69044,7 @@ function daemonLink(deps) {
67631
69044
  if (answer === void 0)
67632
69045
  throw new CodegraphCommandError("the daemon stopped answering");
67633
69046
  if (answer.status < 200 || answer.status >= 300)
67634
- throw new CodegraphCommandError(errorOf(answer.body, answer.status));
69047
+ throw new CodegraphCommandError(errorOf2(answer.body, answer.status));
67635
69048
  return answer.body;
67636
69049
  };
67637
69050
  return {
@@ -67817,7 +69230,7 @@ async function codegraphStop(options, deps) {
67817
69230
  const answer = await daemonRoute(deps, "stop", {}).catch(() => void 0);
67818
69231
  if (answer !== void 0 && (answer.status < 200 || answer.status >= 300)) {
67819
69232
  deps.err(
67820
- `oxagen graph: the daemon did not stop the code graph server: ${errorOf(answer.body, answer.status)}`
69233
+ `oxagen graph: the daemon did not stop the code graph server: ${errorOf2(answer.body, answer.status)}`
67821
69234
  );
67822
69235
  return false;
67823
69236
  }
@@ -67873,11 +69286,13 @@ __export(cli_exports, {
67873
69286
  credentialIssue: () => credentialIssue,
67874
69287
  credentialLogin: () => credentialLogin,
67875
69288
  credentialStatus: () => credentialStatus,
69289
+ credentialSync: () => credentialSync,
67876
69290
  cursorAppFacts: () => cursorAppFacts,
67877
69291
  cursorFacts: () => cursorFacts,
67878
69292
  dataLocalDir: () => dataLocalDir,
67879
69293
  defaultCliDeps: () => defaultCliDeps,
67880
69294
  describeHarness: () => describeHarness,
69295
+ describePoolSync: () => describePoolSync,
67881
69296
  describeRepo: () => describeRepo,
67882
69297
  detect: () => detect,
67883
69298
  disarmGateway: () => disarmGateway,
@@ -67936,6 +69351,7 @@ __export(cli_exports, {
67936
69351
  stopGateway: () => stopGateway,
67937
69352
  streamDaemon: () => streamDaemon,
67938
69353
  stripEnrollmentHooks: () => stripEnrollmentHooks,
69354
+ syncCredentialPoolsNow: () => syncCredentialPoolsNow,
67939
69355
  transientBinDir: () => transientBinDir,
67940
69356
  unenroll: () => unenroll,
67941
69357
  unenrollTarget: () => unenrollTarget,
@@ -73149,6 +74565,15 @@ function buildTachoProgram(options = {}) {
73149
74565
  if (!outcome.ok) process.exitCode = 1;
73150
74566
  }
73151
74567
  );
74568
+ credential.command("sync").description(
74569
+ "Read the model credentials you saved in Oxagen into the gateway's custody now, so a call moves to the next one when a provider refuses the one in use"
74570
+ ).option("--json", "Machine-readable output").action(async (opts) => {
74571
+ const outcome = await credentialSync(
74572
+ { ...opts.json !== void 0 ? { json: opts.json } : {} },
74573
+ deps
74574
+ );
74575
+ if (!outcome.ok) process.exitCode = 1;
74576
+ });
73152
74577
  credential.command("status").description(
73153
74578
  "Which providers the gateway holds, and how each harness gets its credential"
73154
74579
  ).option("--json", "Machine-readable output").action(async (opts) => {
@@ -73448,7 +74873,7 @@ var init_package = __esm({
73448
74873
  "package.json"() {
73449
74874
  package_default = {
73450
74875
  name: "@oxagen/cli",
73451
- version: "3.0.1-817",
74876
+ version: "3.0.1-818",
73452
74877
  description: "Oxagen governance CLI: spend, source tracking, grounding, credentials, and audit (agentic coding lives in the stella CLI)",
73453
74878
  type: "module",
73454
74879
  main: "./dist/index.js",
@@ -76472,7 +77897,7 @@ var init_common = __esm({
76472
77897
  function call(name2, request3, result2) {
76473
77898
  return { call: name2, request: request3, result: result2, response: responseSchema(result2) };
76474
77899
  }
76475
- var unit3, count8, names, excluded, withinSchema, testRefSchema, SEARCH_GROUPS, searchHitSchema, SEARCH_MEANING_STATES, searchMeaningStateSchema, searchCodeGraphRequest, searchCodeGraphResult, blastTargetSchema, decisionItemSchema, blastGroupsSchema, getBlastRadiusRequest, getBlastRadiusResult, listUnitTestsRequest, listUnitTestsResult, flowDataSchema, flowNodeSchema, jobStepSchema, getExecutionFlowRequest, getExecutionFlowResult, traceSpecRequest, traceSpecResult, listGoverningDecisionsBase, listGoverningDecisionsRequest, listGoverningDecisionsResult, getEnvVarsRequest, getEnvVarsResult, connectionSchema, getInfraRequest, getInfraResult, listCiJobsRequest, listCiJobsResult, scriptEffectSchema, listScriptsRequest, listScriptsResult, getApiDocsRequest, getApiDocsResult, exportOpenapiDraftRequest, exportOpenapiDraftResult, listCoChangesRequest, listCoChangesResult, rankSymbolsRequest, rankSymbolsResult, getRepoMapRequest, getRepoMapResult, getDomainBriefRequest, getDomainBriefResult, checkChangeRequest, checkChangeResult, findDefinitionRequest, findDefinitionResult, findReferencesRequest, findReferencesResult, findImplementationsRequest, findImplementationsResult, listNeighborsRequest, listNeighborsResult, failureRefSchema, FAILURE_KINDS, failureSchema, DATAFLOW_EDGE_KINDS, SLICE_DIRECTIONS, SLICE_ROLES, SLICE_MAX_DEPTH, sliceStepSchema, dataflowSliceBase, getDataflowSliceRequest, getDataflowSliceResult, FAULT_SIGNALS, LOCALIZE_MAX_SUSPECTS, signalEvidenceSchema, suspectSchema, localizeFaultBase, localizeFaultRequest, localizeFaultResult, INTENT_EVIDENCE_KINDS, intentEvidenceSchema, getIntendedBehaviorRequest, getIntendedBehaviorResult, REPAIR_CONTEXT_SECTIONS, REPAIR_CONTEXT_DEFAULT_BUDGET, REPAIR_CONTEXT_MAX_BUDGET, repairContextSectionSchema, repairContextBase, getRepairContextRequest, getRepairContextResult, CODEGRAPH_CALLS;
77900
+ var unit3, count8, names, excluded, withinSchema, testRefSchema, SEARCH_GROUPS, searchHitSchema, SEARCH_MEANING_STATES, searchMeaningStateSchema, searchCodeGraphRequest, searchCodeGraphResult, blastTargetSchema, decisionItemSchema, blastGroupsSchema, getBlastRadiusRequest, getBlastRadiusResult, listUnitTestsRequest, listUnitTestsResult, flowDataSchema, flowNodeSchema, jobStepSchema, getExecutionFlowRequest, getExecutionFlowResult, traceSpecRequest, traceSpecResult, listGoverningDecisionsBase, listGoverningDecisionsRequest, listGoverningDecisionsResult, getEnvVarsRequest, getEnvVarsResult, connectionSchema, getInfraRequest, getInfraResult, listCiJobsRequest, listCiJobsResult, scriptEffectSchema, listScriptsRequest, listScriptsResult, getApiDocsRequest, getApiDocsResult, exportOpenapiDraftRequest, exportOpenapiDraftResult, listCoChangesRequest, listCoChangesResult, rankSymbolsRequest, rankSymbolsResult, getRepoMapRequest, getRepoMapResult, getDomainBriefRequest, getDomainBriefResult, checkChangeRequest, checkChangeResult, findDefinitionRequest, findDefinitionResult, findReferencesRequest, findReferencesResult, findImplementationsRequest, findImplementationsResult, listNeighborsRequest, listNeighborsResult, failureRefSchema, FAILURE_KINDS, failureSchema2, DATAFLOW_EDGE_KINDS, SLICE_DIRECTIONS, SLICE_ROLES, SLICE_MAX_DEPTH, sliceStepSchema, dataflowSliceBase, getDataflowSliceRequest, getDataflowSliceResult, FAULT_SIGNALS, LOCALIZE_MAX_SUSPECTS, signalEvidenceSchema, suspectSchema, localizeFaultBase, localizeFaultRequest, localizeFaultResult, INTENT_EVIDENCE_KINDS, intentEvidenceSchema, getIntendedBehaviorRequest, getIntendedBehaviorResult, REPAIR_CONTEXT_SECTIONS, REPAIR_CONTEXT_DEFAULT_BUDGET, REPAIR_CONTEXT_MAX_BUDGET, repairContextSectionSchema, repairContextBase, getRepairContextRequest, getRepairContextResult, CODEGRAPH_CALLS;
76476
77901
  var init_calls = __esm({
76477
77902
  "../../packages/codegraph/src/query/calls.ts"() {
76478
77903
  "use strict";
@@ -77000,7 +78425,7 @@ var init_calls = __esm({
77000
78425
  "broken_decision",
77001
78426
  "drifted_spec"
77002
78427
  ];
77003
- failureSchema = external_exports.object({
78428
+ failureSchema2 = external_exports.object({
77004
78429
  id: external_exports.string().min(1).optional(),
77005
78430
  kind: external_exports.enum(FAILURE_KINDS).optional(),
77006
78431
  /** The exception type, the top frames inside the repo, and the test id. */
@@ -77111,7 +78536,7 @@ var init_calls = __esm({
77111
78536
  { message: "pass a failure, an issue's text, or a stack trace" }
77112
78537
  );
77113
78538
  localizeFaultResult = external_exports.object({
77114
- failure: failureSchema.optional(),
78539
+ failure: failureSchema2.optional(),
77115
78540
  suspects: external_exports.array(suspectSchema),
77116
78541
  /** Each signal, whether it ran, and why not when it did not. */
77117
78542
  signals: external_exports.array(
@@ -77195,7 +78620,7 @@ var init_calls = __esm({
77195
78620
  { message: "pass suspects or a failure" }
77196
78621
  );
77197
78622
  getRepairContextResult = external_exports.object({
77198
- failure: failureSchema.optional(),
78623
+ failure: failureSchema2.optional(),
77199
78624
  sections: external_exports.array(repairContextSectionSchema),
77200
78625
  /** On a replay: the share of the fix's lines inside the bundle. */
77201
78626
  coverageAtBudget: unit3.optional(),
@@ -92455,9 +93880,11 @@ __export(host_exports, {
92455
93880
  DEVICE_KEY_PROOF_DOMAIN: () => DEVICE_KEY_PROOF_DOMAIN,
92456
93881
  ENROLLMENT_CERTIFICATE_TTL_S: () => ENROLLMENT_CERTIFICATE_TTL_S,
92457
93882
  HARNESS_PROVIDER: () => HARNESS_PROVIDER,
93883
+ HELD_MEMBER_ID: () => HELD_MEMBER_ID,
92458
93884
  HOST_FILE_SCHEMA: () => HOST_FILE_SCHEMA,
92459
93885
  HTTP_HOOK_EVENTS: () => HTTP_HOOK_EVENTS,
92460
93886
  LEGACY_CREATED_WANTS_MARK: () => LEGACY_CREATED_WANTS_MARK,
93887
+ LOGIN_REFRESH_REFUSALS: () => LOGIN_REFRESH_REFUSALS,
92461
93888
  REQUEST_SIGNATURE_DOMAIN: () => REQUEST_SIGNATURE_DOMAIN,
92462
93889
  REQUEST_SIGNATURE_HEADER: () => REQUEST_SIGNATURE_HEADER,
92463
93890
  REQUEST_SIGNATURE_MAX_SKEW_S: () => REQUEST_SIGNATURE_MAX_SKEW_S,
@@ -92485,6 +93912,7 @@ __export(host_exports, {
92485
93912
  TACHO_ENV_KEYS: () => TACHO_ENV_KEYS,
92486
93913
  TACHO_INGEST_TIMEOUT_MS: () => TACHO_INGEST_TIMEOUT_MS,
92487
93914
  TACHO_LOCAL_TOKEN_ENV: () => TACHO_LOCAL_TOKEN_ENV,
93915
+ VAULT_POOL_SOURCE: () => VAULT_POOL_SOURCE,
92488
93916
  Wal: () => Wal,
92489
93917
  WalRecoveryConflict: () => WalRecoveryConflict,
92490
93918
  absoluteHookCommandProblem: () => absoluteHookCommandProblem,
@@ -92562,6 +93990,7 @@ __export(host_exports, {
92562
93990
  hostFileSchema: () => hostFileSchema,
92563
93991
  hostStatusInForce: () => hostStatusInForce,
92564
93992
  isDaemonImage: () => isDaemonImage,
93993
+ isLoginKind: () => isLoginKind,
92565
93994
  isModelProxyBaseUrl: () => isModelProxyBaseUrl,
92566
93995
  isProcessAlive: () => isProcessAlive,
92567
93996
  isSubscriptionToken: () => isSubscriptionToken,
@@ -92750,12 +94179,12 @@ async function detectHarnesses(deps = {}) {
92750
94179
  const names2 = commandNames(HARNESS_BINARY[harness], platform2);
92751
94180
  const path2 = dirs.flatMap((dir) => names2.map((name2) => join65(dir, name2))).find(isExecutable2);
92752
94181
  if (path2 !== void 0) {
92753
- found.push({ harness, label: harnessLabel(harness), path: path2 });
94182
+ found.push({ harness, label: harnessLabel2(harness), path: path2 });
92754
94183
  }
92755
94184
  }
92756
94185
  return found;
92757
94186
  }
92758
- function harnessLabel(harness) {
94187
+ function harnessLabel2(harness) {
92759
94188
  return TACHO_HARNESS_LABELS[harness];
92760
94189
  }
92761
94190
  function isWrapped(name2) {
@@ -93108,7 +94537,7 @@ async function agentConnect(opts, writer = stdoutWriter, deps = {}) {
93108
94537
  );
93109
94538
  }
93110
94539
  const ref = `${preview.org.slug}/${preview.workspace.slug}`;
93111
- const label = isDeviceHarness(preview.agent.harness) ? harnessLabel(preview.agent.harness) : preview.agent.harness;
94540
+ const label = isDeviceHarness(preview.agent.harness) ? harnessLabel2(preview.agent.harness) : preview.agent.harness;
93112
94541
  if (preview.state === "connected") {
93113
94542
  if (!preview.connectedHere)
93114
94543
  return out.error(
@@ -93897,7 +95326,7 @@ async function harnessesToConnect(opts, ref, interactive, deps, out) {
93897
95326
  }
93898
95327
  return parsed2.harnesses.map((harness) => ({
93899
95328
  harness,
93900
- label: harnessLabel(harness)
95329
+ label: harnessLabel2(harness)
93901
95330
  }));
93902
95331
  }
93903
95332
  let installed;
@@ -151071,7 +152500,7 @@ function deadlineExceeded(deadline_ms) {
151071
152500
  status: void 0
151072
152501
  };
151073
152502
  }
151074
- function retryAfterMs(value, now) {
152503
+ function retryAfterMs2(value, now) {
151075
152504
  if (value === void 0) return void 0;
151076
152505
  const text6 = value.trim();
151077
152506
  if (/^\d+$/.test(text6)) return Number(text6) * 1e3;
@@ -151595,38 +153024,38 @@ async function attemptOnce(spec, deadline) {
151595
153024
  const response = sent.value;
151596
153025
  const read2 = await readBody3(response, { clock: clock2, deadline_ms });
151597
153026
  if (!read2.ok) return { attempt: read2, exchange: void 0 };
151598
- const exchange = {
153027
+ const exchange2 = {
151599
153028
  request: spec.recorded,
151600
153029
  response: recordHttpResponse(response, read2.bytes)
151601
153030
  };
151602
153031
  const attempt = spec.interpret(response, read2.bytes);
151603
153032
  if (!attempt.ok && spec.retryable && RETRY_STATUSES.has(response.status)) {
151604
- const after_ms = retryAfterMs(
153033
+ const after_ms = retryAfterMs2(
151605
153034
  headerValue(response.headers, "retry-after"),
151606
153035
  Date.now()
151607
153036
  );
151608
153037
  return {
151609
153038
  attempt: { ok: false, error: attempt.error, retry: { after_ms } },
151610
- exchange
153039
+ exchange: exchange2
151611
153040
  };
151612
153041
  }
151613
- return { attempt, exchange };
153042
+ return { attempt, exchange: exchange2 };
151614
153043
  } finally {
151615
153044
  clock2.dispose();
151616
153045
  }
151617
153046
  }
151618
153047
  async function runHttp(spec) {
151619
153048
  const deadline = Date.now() + spec.context.shaping.deadline_ms;
151620
- let exchange;
153049
+ let exchange2;
151621
153050
  const result2 = await withRetries(
151622
153051
  async () => {
151623
153052
  const outcome = await attemptOnce(spec, deadline);
151624
- exchange = outcome.exchange;
153053
+ exchange2 = outcome.exchange;
151625
153054
  return outcome.attempt;
151626
153055
  },
151627
153056
  { deadline, signal: spec.context.signal, backoff_ms: spec.backoff_ms }
151628
153057
  );
151629
- const exchanges = exchange === void 0 ? [] : [exchange];
153058
+ const exchanges = exchange2 === void 0 ? [] : [exchange2];
151630
153059
  return result2.ok ? { ok: true, value: result2.value, attempts: result2.attempts, exchanges } : { ok: false, error: result2.error, attempts: result2.attempts, exchanges };
151631
153060
  }
151632
153061
  var KEPT_RESERVED, RETRY_STATUSES, MAX_DETAIL;
@@ -151813,7 +153242,7 @@ async function rejected(session, response, setup) {
151813
153242
  }
151814
153243
  function rejectedAttempt(response, failure4) {
151815
153244
  if (!failure4.retry) return { ok: false, error: failure4.error };
151816
- const after_ms = retryAfterMs(
153245
+ const after_ms = retryAfterMs2(
151817
153246
  headerValue(response.headers, "retry-after"),
151818
153247
  Date.now()
151819
153248
  );
@@ -152043,16 +153472,16 @@ async function attemptOnce2(call2, deadline) {
152043
153472
  }
152044
153473
  async function runAttempts(context, backoff_ms, attempt) {
152045
153474
  const deadline = Date.now() + context.shaping.deadline_ms;
152046
- let exchange;
153475
+ let exchange2;
152047
153476
  const result2 = await withRetries(
152048
153477
  async () => {
152049
153478
  const outcome = await attempt(deadline);
152050
- exchange = outcome.exchange;
153479
+ exchange2 = outcome.exchange;
152051
153480
  return outcome.attempt;
152052
153481
  },
152053
153482
  { deadline, signal: context.signal, backoff_ms }
152054
153483
  );
152055
- const exchanges = exchange === void 0 ? [] : [exchange];
153484
+ const exchanges = exchange2 === void 0 ? [] : [exchange2];
152056
153485
  return result2.ok ? { ok: true, value: result2.value, attempts: result2.attempts, exchanges } : { ok: false, error: result2.error, attempts: result2.attempts, exchanges };
152057
153486
  }
152058
153487
  function createMcpSender(options = {}) {
@@ -154226,10 +155655,10 @@ function scrubJson(value, secrets) {
154226
155655
  function scrubSent(sent, secrets) {
154227
155656
  if (secrets.length === 0) return sent;
154228
155657
  const exchanges = sent.exchanges?.map(
154229
- (exchange) => ({
154230
- ...exchange,
155658
+ (exchange2) => ({
155659
+ ...exchange2,
154231
155660
  response: scrubJson(
154232
- exchange.response,
155661
+ exchange2.response,
154233
155662
  secrets
154234
155663
  )
154235
155664
  })
@@ -172525,21 +173954,21 @@ function replayTransport(exchanges, route) {
172525
173954
  problem ??= found;
172526
173955
  throw new TransportError("unsupported", found.message, false);
172527
173956
  };
172528
- const wrongKind = (exchange, response, needed, reason3) => {
173957
+ const wrongKind = (exchange2, response, needed, reason3) => {
172529
173958
  const recorded = responseKind(response);
172530
173959
  return refuse3({
172531
173960
  part: "response",
172532
- exchange,
173961
+ exchange: exchange2,
172533
173962
  expected: recorded,
172534
173963
  actual: needed,
172535
- message: `Exchange ${exchange} records ${recorded}, but ${reason3}.`
173964
+ message: `Exchange ${exchange2} records ${recorded}, but ${reason3}.`
172536
173965
  });
172537
173966
  };
172538
173967
  const take = () => {
172539
173968
  const again = retryable ? exchanges[next - 1] : void 0;
172540
173969
  if (again !== void 0) return again.response;
172541
- const exchange = exchanges[next];
172542
- if (exchange === void 0) {
173970
+ const exchange2 = exchanges[next];
173971
+ if (exchange2 === void 0) {
172543
173972
  return refuse3({
172544
173973
  part: "exchanges",
172545
173974
  exchange: next + 1,
@@ -172550,7 +173979,7 @@ function replayTransport(exchanges, route) {
172550
173979
  }
172551
173980
  next += 1;
172552
173981
  retryable = false;
172553
- return exchange.response;
173982
+ return exchange2.response;
172554
173983
  };
172555
173984
  const takeHttp = () => {
172556
173985
  const response = take();
@@ -172719,8 +174148,8 @@ async function replayCall(server, call2) {
172719
174148
  }
172720
174149
  const problem = replay.problem();
172721
174150
  if (problem !== void 0) {
172722
- const { part, exchange, expected, actual, message: message2 } = problem;
172723
- return differs({ part, exchange, path: "", expected, actual, message: message2 });
174151
+ const { part, exchange: exchange2, expected, actual, message: message2 } = problem;
174152
+ return differs({ part, exchange: exchange2, path: "", expected, actual, message: message2 });
172724
174153
  }
172725
174154
  const used = replay.used();
172726
174155
  if (used !== call2.exchanges.length) {
@@ -173603,9 +175032,9 @@ async function replayFolder(name2, text6, tools, manifest) {
173603
175032
  const result2 = await replayCall(manifest, call2);
173604
175033
  if (result2.status === "skipped") tally2.skipped.push(result2.reason);
173605
175034
  if (result2.status !== "differs") continue;
173606
- const { part, exchange, message: message2 } = result2.difference;
175035
+ const { part, exchange: exchange2, message: message2 } = result2.difference;
173607
175036
  const detail = { tool: call2.tool, part };
173608
- if (exchange !== void 0) detail.exchange = exchange;
175037
+ if (exchange2 !== void 0) detail.exchange = exchange2;
173609
175038
  findings.push(replayFinding(path2, index, call2, message2, detail));
173610
175039
  }
173611
175040
  return { findings, notes: replayNotes(path2, tally2) };