claude-use 11.10.0 → 11.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -33419,7 +33419,7 @@ function isRateLimitHeader(name) {
33419
33419
  const lower = name.toLowerCase();
33420
33420
  return lower === "retry-after" || lower.startsWith("anthropic-ratelimit-") || lower.startsWith("x-ratelimit-") || lower.startsWith("ratelimit") || lower.startsWith("x-codex-");
33421
33421
  }
33422
- var USAGE_SCHEMA_VERSION, VersionSchema, InstantSchema, TokenCountSchema, TokenUsageSchema, LIMIT_KINDS, LimitClassificationSchema, UsageRecordSchema, QuotaWindowSchema, ExtraUsageSpendSchema, UnifiedRateLimitSchema, RateLimitStateSchema, LimitEventSchema, ProviderQuotaWindowSchema, ProviderQuotaSchema, ProviderUsageStateSchema, AccountMetadataSchema, UsageSnapshotSchema;
33422
+ var USAGE_SCHEMA_VERSION, VersionSchema, InstantSchema, TokenCountSchema, TokenUsageSchema, LIMIT_KINDS, LimitClassificationSchema, UsageRecordSchema, QuotaWindowSchema, ExtraUsageSpendSchema, UnifiedRateLimitSchema, RateLimitStateSchema, LimitEventSchema, ProviderQuotaWindowSchema, ProviderAccountSchema, ProviderQuotaSchema, ProviderUsageStateSchema, AccountMetadataSchema, UsageSnapshotSchema;
33423
33423
  var init_schema2 = __esm({
33424
33424
  "src/usage/schema.ts"() {
33425
33425
  "use strict";
@@ -33551,12 +33551,18 @@ var init_schema2 = __esm({
33551
33551
  used: external_exports.number().nonnegative().optional(),
33552
33552
  remaining: external_exports.number().nonnegative().optional()
33553
33553
  });
33554
+ ProviderAccountSchema = external_exports.strictObject({
33555
+ email: external_exports.string().optional(),
33556
+ accountId: external_exports.string().optional()
33557
+ });
33554
33558
  ProviderQuotaSchema = external_exports.strictObject({
33555
33559
  observedAt: InstantSchema,
33556
33560
  /** Which usage endpoint produced it (`z.ai`). */
33557
33561
  source: external_exports.string(),
33558
33562
  /** The subscription level the endpoint reports, when it does. */
33559
33563
  level: external_exports.string().optional(),
33564
+ /** The account the provider's credential belongs to, when its endpoint reports it. */
33565
+ account: ProviderAccountSchema.optional(),
33560
33566
  windows: external_exports.array(ProviderQuotaWindowSchema)
33561
33567
  });
33562
33568
  ProviderUsageStateSchema = external_exports.strictObject({
@@ -34087,7 +34093,7 @@ var init_package = __esm({
34087
34093
  "package.json"() {
34088
34094
  package_default = {
34089
34095
  name: "claude-use",
34090
- version: "11.10.0",
34096
+ version: "11.12.0",
34091
34097
  description: "A profile manager and launcher for Claude Code that lets one person run multiple logins from one machine while controlling what gets shared between them.",
34092
34098
  license: "MIT",
34093
34099
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -34689,13 +34695,16 @@ function decoderFor(encoding) {
34689
34695
  return void 0;
34690
34696
  }
34691
34697
  }
34692
- function destinationOf(path59) {
34698
+ function destinationOf(path59, sessionProvider) {
34693
34699
  const scoped = parseProviderPath(path59);
34694
- return scoped === void 0 ? { provider: ANTHROPIC_PROVIDER, endpoint: path59 } : { provider: scoped.provider, endpoint: scoped.rest };
34700
+ if (scoped !== void 0) {
34701
+ return { provider: scoped.provider, endpoint: scoped.rest };
34702
+ }
34703
+ return { provider: sessionProvider ?? ANTHROPIC_PROVIDER, endpoint: path59 };
34695
34704
  }
34696
34705
  function buildRecord(event, context) {
34697
34706
  const { scan } = context;
34698
- const { provider, endpoint } = destinationOf(event.path);
34707
+ const { provider, endpoint } = destinationOf(event.path, event.session.provider);
34699
34708
  const rateLimitHeaders = rateLimitHeadersOf(event.headers);
34700
34709
  const limit = classifyLimit({ status: event.status, headers: rateLimitHeaders ?? {}, error: scan?.error, nowMs: context.endedAt });
34701
34710
  const requestId = headerValue(event.headers, "request-id");
@@ -63765,10 +63774,10 @@ function resolveLaunch(params) {
63765
63774
  environment
63766
63775
  };
63767
63776
  }
63768
- function runLaunchPlan(plan, spawn6) {
63777
+ function runLaunchPlan(plan, spawn7) {
63769
63778
  try {
63770
63779
  plan.markChildStarted();
63771
- const result = spawn6.spawnSync(plan.bin, plan.args, { stdio: "inherit", env: plan.env });
63780
+ const result = spawn7.spawnSync(plan.bin, plan.args, { stdio: "inherit", env: plan.env });
63772
63781
  if (result.error !== void 0) {
63773
63782
  throw result.error;
63774
63783
  }
@@ -63981,6 +63990,125 @@ var init_identityClaude = __esm({
63981
63990
  }
63982
63991
  });
63983
63992
 
63993
+ // src/antigravity/cloudUpstream.ts
63994
+ function isCcpaEndpoint(endpoint) {
63995
+ return endpoint.includes("cloudcode-pa.googleapis.com");
63996
+ }
63997
+ function buildCloudUrl(config2, model) {
63998
+ const { cloud } = config2;
63999
+ if (cloud.projectId !== void 0 && cloud.location !== void 0) {
64000
+ const base2 = cloud.endpoint ?? `https://${cloud.location}-aiplatform.googleapis.com`;
64001
+ return `${base2}/v1/projects/${cloud.projectId}/locations/${cloud.location}/publishers/google/models/${encodeURIComponent(model)}:streamGenerateContent?alt=sse`;
64002
+ }
64003
+ const base = cloud.endpoint ?? CCPA_ENDPOINT;
64004
+ if (isCcpaEndpoint(base)) {
64005
+ return `${base}/v1internal:streamGenerateContent?alt=sse`;
64006
+ }
64007
+ return `${base}/v1beta/models/${encodeURIComponent(model)}:streamGenerateContent?alt=sse`;
64008
+ }
64009
+ function buildCloudHeaders(token, credentialTarget, endpoint) {
64010
+ const headers = {
64011
+ "Content-Type": "application/json",
64012
+ Accept: "text/event-stream"
64013
+ };
64014
+ const target = credentialTarget ?? "bearer";
64015
+ if (target === "apiKey") {
64016
+ headers["x-goog-api-key"] = token;
64017
+ } else {
64018
+ headers.Authorization = `Bearer ${token}`;
64019
+ }
64020
+ const base = endpoint ?? CCPA_ENDPOINT;
64021
+ if (isCcpaEndpoint(base)) {
64022
+ headers["User-Agent"] = CCPA_USER_AGENT;
64023
+ }
64024
+ return headers;
64025
+ }
64026
+ function buildCloudRequestBody(params) {
64027
+ const base = params.config.cloud.endpoint ?? CCPA_ENDPOINT;
64028
+ if (isCcpaEndpoint(base)) {
64029
+ return JSON.stringify({
64030
+ project: params.config.cloud.projectId ?? CCPA_DEFAULT_PROJECT_ID,
64031
+ requestId: `agent/${(0, import_node_crypto16.randomUUID)()}/${String(Date.now())}/1`,
64032
+ request: params.request,
64033
+ model: params.model,
64034
+ userAgent: "antigravity"
64035
+ });
64036
+ }
64037
+ return JSON.stringify(params.request);
64038
+ }
64039
+ function isRecord4(value2) {
64040
+ return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
64041
+ }
64042
+ function isGeminiChunk(value2) {
64043
+ return isRecord4(value2);
64044
+ }
64045
+ async function* callCloudAntigravity(params, fetchFn = fetch) {
64046
+ const url2 = buildCloudUrl(params.config, params.model);
64047
+ const headers = buildCloudHeaders(params.token, params.credentialTarget, params.config.cloud.endpoint);
64048
+ const body = buildCloudRequestBody(params);
64049
+ const response = await fetchFn(url2, {
64050
+ method: "POST",
64051
+ headers,
64052
+ body,
64053
+ signal: params.signal
64054
+ });
64055
+ if (!response.ok) {
64056
+ const errorText = await response.text();
64057
+ const retryAfter = response.headers.get("retry-after");
64058
+ throw new AntigravityUpstreamError(response.status, errorText, retryAfter);
64059
+ }
64060
+ if (response.body === null) {
64061
+ return;
64062
+ }
64063
+ const decoder = new TextDecoder("utf-8");
64064
+ let buffer2 = "";
64065
+ const sseDataPrefix = "data:";
64066
+ for await (const rawChunk of response.body) {
64067
+ const chunk = rawChunk instanceof Uint8Array ? rawChunk : Buffer.from(String(rawChunk));
64068
+ buffer2 += decoder.decode(chunk, { stream: true });
64069
+ const lines = buffer2.split("\n");
64070
+ buffer2 = lines.pop() ?? "";
64071
+ for (const line of lines) {
64072
+ const trimmed = line.trim();
64073
+ if (trimmed.startsWith(sseDataPrefix)) {
64074
+ const jsonStr = trimmed.slice(sseDataPrefix.length).trim();
64075
+ if (jsonStr.length > 0) {
64076
+ try {
64077
+ const parsed = JSON.parse(jsonStr);
64078
+ if (isRecord4(parsed)) {
64079
+ const unwrapped = isRecord4(parsed.response) ? parsed.response : parsed;
64080
+ if (isGeminiChunk(unwrapped)) {
64081
+ yield unwrapped;
64082
+ }
64083
+ }
64084
+ } catch {
64085
+ }
64086
+ }
64087
+ }
64088
+ }
64089
+ }
64090
+ }
64091
+ var import_node_crypto16, CCPA_ENDPOINT, CCPA_DEFAULT_PROJECT_ID, CCPA_USER_AGENT, AntigravityUpstreamError;
64092
+ var init_cloudUpstream = __esm({
64093
+ "src/antigravity/cloudUpstream.ts"() {
64094
+ "use strict";
64095
+ import_node_crypto16 = require("node:crypto");
64096
+ CCPA_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
64097
+ CCPA_DEFAULT_PROJECT_ID = "aicode-consumers";
64098
+ CCPA_USER_AGENT = "antigravity/cli/1.3.5 (aidev_client; os_type=darwin; arch=arm64; cl=998863838; auth_method=consumer)";
64099
+ AntigravityUpstreamError = class extends Error {
64100
+ status;
64101
+ retryAfter;
64102
+ constructor(status, message, retryAfter) {
64103
+ super(`Google Antigravity API error (${String(status)}): ${message}`);
64104
+ this.name = "AntigravityUpstreamError";
64105
+ this.status = status;
64106
+ this.retryAfter = retryAfter;
64107
+ }
64108
+ };
64109
+ }
64110
+ });
64111
+
63984
64112
  // src/usage/providerQuota.ts
63985
64113
  function zaiWindow(limit) {
63986
64114
  const unitMs = ZAI_UNIT_MS.get(limit.unit);
@@ -64024,11 +64152,12 @@ function quotaFreshnessMs(quota) {
64024
64152
  const lengths = quota.windows.flatMap((window) => window.periodMs === void 0 ? [] : [window.periodMs]);
64025
64153
  return lengths.length === 0 ? Number.POSITIVE_INFINITY : Math.min(...lengths) / PERCENT3;
64026
64154
  }
64027
- var ProviderQuotaError, MS_PER_SECOND6, SECONDS_PER_HOUR, HOURS_PER_DAY3, DAYS_PER_MONTH, PERCENT3, HTTP_OK, ZAI_SOURCE, ZAI_HOST, ZAI_QUOTA_URL, ZAI_UNIT_HOURS, ZAI_UNIT_MONTHS, ZAI_UNIT_MS, ZAI_MEASURES, ZaiLimitSchema, ZaiResponseSchema, zaiQuotaAdapter, OPENROUTER_SOURCE, OPENROUTER_HOST, OPENROUTER_KEY_URL, OPENROUTER_CREDITS_URL, HTTP_FORBIDDEN, MS_PER_DAY2, OpenRouterKeySchema, OpenRouterCreditsSchema, openRouterQuotaAdapter, PROVIDER_QUOTA_ADAPTERS;
64155
+ var ProviderQuotaError, MS_PER_SECOND6, SECONDS_PER_HOUR, HOURS_PER_DAY3, DAYS_PER_MONTH, PERCENT3, HTTP_OK, ZAI_SOURCE, ZAI_HOST, ZAI_QUOTA_URL, ZAI_UNIT_HOURS, ZAI_UNIT_MONTHS, ZAI_UNIT_MS, ZAI_MEASURES, ZaiLimitSchema, ZaiResponseSchema, zaiQuotaAdapter, OPENROUTER_SOURCE, OPENROUTER_HOST, OPENROUTER_KEY_URL, OPENROUTER_CREDITS_URL, HTTP_FORBIDDEN, MS_PER_DAY2, OpenRouterKeySchema, OpenRouterCreditsSchema, openRouterQuotaAdapter, ANTIGRAVITY_SOURCE, ANTIGRAVITY_HOST, ANTIGRAVITY_QUOTA_URL, GOOGLE_TOKENINFO_URL, FIVE_HOURS2, DAYS_PER_WEEK, FIVE_HOURS_MS, WEEK_MS, AntigravityBucketSchema, AntigravitySummarySchema, GoogleTokenInfoSchema, ANTIGRAVITY_WINDOW_MS, antigravityQuotaAdapter, PROVIDER_QUOTA_ADAPTERS;
64028
64156
  var init_providerQuota = __esm({
64029
64157
  "src/usage/providerQuota.ts"() {
64030
64158
  "use strict";
64031
64159
  init_zod();
64160
+ init_cloudUpstream();
64032
64161
  init_schema2();
64033
64162
  ProviderQuotaError = class extends Error {
64034
64163
  constructor(source, detail) {
@@ -64142,7 +64271,71 @@ var init_providerQuota = __esm({
64142
64271
  });
64143
64272
  }
64144
64273
  };
64145
- PROVIDER_QUOTA_ADAPTERS = [zaiQuotaAdapter, openRouterQuotaAdapter];
64274
+ ANTIGRAVITY_SOURCE = "Cloud Code";
64275
+ ANTIGRAVITY_HOST = "daily-cloudcode-pa.googleapis.com";
64276
+ ANTIGRAVITY_QUOTA_URL = `https://${ANTIGRAVITY_HOST}/v1internal:retrieveUserQuotaSummary`;
64277
+ GOOGLE_TOKENINFO_URL = "https://oauth2.googleapis.com/tokeninfo";
64278
+ FIVE_HOURS2 = 5;
64279
+ DAYS_PER_WEEK = 7;
64280
+ FIVE_HOURS_MS = FIVE_HOURS2 * SECONDS_PER_HOUR * MS_PER_SECOND6;
64281
+ WEEK_MS = DAYS_PER_WEEK * HOURS_PER_DAY3 * SECONDS_PER_HOUR * MS_PER_SECOND6;
64282
+ AntigravityBucketSchema = external_exports.object({
64283
+ bucketId: external_exports.string(),
64284
+ remainingFraction: external_exports.number().optional(),
64285
+ resetTime: external_exports.string().optional()
64286
+ });
64287
+ AntigravitySummarySchema = external_exports.object({ groups: external_exports.array(external_exports.object({ buckets: external_exports.array(AntigravityBucketSchema) })) });
64288
+ GoogleTokenInfoSchema = external_exports.object({
64289
+ email: external_exports.string().optional(),
64290
+ sub: external_exports.string().optional()
64291
+ });
64292
+ ANTIGRAVITY_WINDOW_MS = { "gemini-5h": FIVE_HOURS_MS, "3p-5h": FIVE_HOURS_MS, "gemini-weekly": WEEK_MS, "3p-weekly": WEEK_MS };
64293
+ antigravityQuotaAdapter = {
64294
+ source: ANTIGRAVITY_SOURCE,
64295
+ matches: (baseUrl) => URL.canParse(baseUrl) && new URL(baseUrl).hostname === ANTIGRAVITY_HOST,
64296
+ fetch: async (apiKey, http8, signal, nowMs) => {
64297
+ const headers = { authorization: `Bearer ${apiKey}`, "content-type": "application/json", "user-agent": CCPA_USER_AGENT };
64298
+ const summaryResponse = await http8(ANTIGRAVITY_QUOTA_URL, headers, signal, { method: "POST", body: JSON.stringify({ project: "aicode-consumers" }) });
64299
+ if (summaryResponse.status !== HTTP_OK) {
64300
+ throw new ProviderQuotaError(ANTIGRAVITY_SOURCE, `answered HTTP ${String(summaryResponse.status)}`);
64301
+ }
64302
+ let summaryBody;
64303
+ try {
64304
+ summaryBody = JSON.parse(summaryResponse.text);
64305
+ } catch {
64306
+ throw new ProviderQuotaError(ANTIGRAVITY_SOURCE, "answered something that is not JSON");
64307
+ }
64308
+ const parsed = AntigravitySummarySchema.safeParse(summaryBody);
64309
+ if (!parsed.success) {
64310
+ throw new ProviderQuotaError(ANTIGRAVITY_SOURCE, `answered an unexpected shape: ${parsed.error.issues.map((issue2) => `${issue2.path.join(".")}: ${issue2.message}`).join("; ")}`);
64311
+ }
64312
+ const tokenResponse = await http8(`${GOOGLE_TOKENINFO_URL}?access_token=${encodeURIComponent(apiKey)}`, { accept: "application/json" }, signal);
64313
+ let account;
64314
+ if (tokenResponse.status === HTTP_OK) {
64315
+ try {
64316
+ const tokenInfo = GoogleTokenInfoSchema.parse(JSON.parse(tokenResponse.text));
64317
+ if (tokenInfo.email !== void 0 || tokenInfo.sub !== void 0) {
64318
+ account = { ...tokenInfo.email === void 0 ? {} : { email: tokenInfo.email }, ...tokenInfo.sub === void 0 ? {} : { accountId: tokenInfo.sub } };
64319
+ }
64320
+ } catch {
64321
+ }
64322
+ }
64323
+ return ProviderQuotaSchema.parse({
64324
+ observedAt: new Date(nowMs).toISOString(),
64325
+ source: ANTIGRAVITY_SOURCE,
64326
+ ...account === void 0 ? {} : { account },
64327
+ windows: parsed.data.groups.flatMap(
64328
+ (group) => group.buckets.map((bucket) => ({
64329
+ measures: bucket.bucketId,
64330
+ ...ANTIGRAVITY_WINDOW_MS[bucket.bucketId] === void 0 ? {} : { periodMs: ANTIGRAVITY_WINDOW_MS[bucket.bucketId] },
64331
+ utilization: bucket.remainingFraction === void 0 ? 0 : 1 - bucket.remainingFraction,
64332
+ ...bucket.resetTime === void 0 ? {} : { resetsAt: bucket.resetTime }
64333
+ }))
64334
+ )
64335
+ });
64336
+ }
64337
+ };
64338
+ PROVIDER_QUOTA_ADAPTERS = [zaiQuotaAdapter, openRouterQuotaAdapter, antigravityQuotaAdapter];
64146
64339
  }
64147
64340
  });
64148
64341
 
@@ -64217,11 +64410,15 @@ function createQuotaRefresher(deps) {
64217
64410
  function createProviderLookup(ports) {
64218
64411
  return (name) => {
64219
64412
  const definition = loadProvider(ports.providersDir, name, ports.fs);
64220
- if (definition === void 0 || !isHttpProvider(definition)) {
64413
+ if (definition === void 0) {
64414
+ return void 0;
64415
+ }
64416
+ const baseUrl = isAntigravityProvider(definition) ? "https://daily-cloudcode-pa.googleapis.com" : isHttpProvider(definition) ? definition.baseUrl : void 0;
64417
+ if (baseUrl === void 0) {
64221
64418
  return void 0;
64222
64419
  }
64223
64420
  return {
64224
- baseUrl: definition.baseUrl,
64421
+ baseUrl,
64225
64422
  apiKey: () => {
64226
64423
  const resolution = resolveCredential({ credential: definition.credential, env: ports.env, port: ports.credentials, subject: `provider ${name}` });
64227
64424
  if (!resolution.ok) {
@@ -113952,11 +114149,11 @@ init_capability();
113952
114149
  init_capture();
113953
114150
 
113954
114151
  // src/frontdoor/connect.ts
113955
- var import_node_crypto17 = require("node:crypto");
114152
+ var import_node_crypto18 = require("node:crypto");
113956
114153
  var fs17 = __toESM(require("node:fs"), 1);
113957
114154
 
113958
114155
  // src/frontdoor/x509.ts
113959
- var import_node_crypto16 = require("node:crypto");
114156
+ var import_node_crypto17 = require("node:crypto");
113960
114157
  var import_node_net = __toESM(require("node:net"), 1);
113961
114158
  var TAG_BOOLEAN = 1;
113962
114159
  var TAG_INTEGER = 2;
@@ -114108,7 +114305,7 @@ function ipBytes(address) {
114108
114305
  return bytes;
114109
114306
  }
114110
114307
  function keyIdentifier(publicKey) {
114111
- return (0, import_node_crypto16.createHash)("sha1").update(publicKey.export({ type: "pkcs1", format: "der" })).digest();
114308
+ return (0, import_node_crypto17.createHash)("sha1").update(publicKey.export({ type: "pkcs1", format: "der" })).digest();
114112
114309
  }
114113
114310
  function readElement(buffer2, offset) {
114114
114311
  const tag = buffer2[offset];
@@ -114154,7 +114351,7 @@ ${body.join("\n")}
114154
114351
  `;
114155
114352
  }
114156
114353
  function randomSerial() {
114157
- const bytes = (0, import_node_crypto16.randomBytes)(SERIAL_NUMBER_BYTES);
114354
+ const bytes = (0, import_node_crypto17.randomBytes)(SERIAL_NUMBER_BYTES);
114158
114355
  bytes[0] = (bytes[0] ?? 0) & BASE_128_PAYLOAD_MASK | HIGH_BIT >> 1;
114159
114356
  return bytes;
114160
114357
  }
@@ -114169,7 +114366,7 @@ function assemble(spec) {
114169
114366
  spec.subjectPublicKey.export({ type: "spki", format: "der" }),
114170
114367
  tlv(TAG_EXTENSIONS, sequence(...spec.extensions))
114171
114368
  );
114172
- const signature = (0, import_node_crypto16.sign)("sha256", tbs, spec.signingKey);
114369
+ const signature = (0, import_node_crypto17.sign)("sha256", tbs, spec.signingKey);
114173
114370
  return sequence(tbs, SIGNATURE_ALGORITHM, wholeBitString(signature));
114174
114371
  }
114175
114372
  function subjectKeyIdentifierExtension(publicKey) {
@@ -114179,7 +114376,7 @@ function basicConstraintsExtension(isCa) {
114179
114376
  return extension(OID_BASIC_CONSTRAINTS, true, sequence(...isCa ? [boolean4(true)] : []));
114180
114377
  }
114181
114378
  function rsaKeyPair() {
114182
- return (0, import_node_crypto16.generateKeyPairSync)("rsa", { modulusLength: RSA_MODULUS_BITS });
114379
+ return (0, import_node_crypto17.generateKeyPairSync)("rsa", { modulusLength: RSA_MODULUS_BITS });
114183
114380
  }
114184
114381
  function keyPem(privateKey) {
114185
114382
  return privateKey.export({ type: "pkcs8", format: "pem" });
@@ -114203,8 +114400,8 @@ function issueLeafCertificate(ca2, names, notBefore, notAfter) {
114203
114400
  if (commonName === void 0) {
114204
114401
  throw new Error("a leaf certificate needs at least one name");
114205
114402
  }
114206
- const caCertificate = new import_node_crypto16.X509Certificate(ca2.certPem);
114207
- const caPrivateKey = (0, import_node_crypto16.createPrivateKey)(ca2.keyPem);
114403
+ const caCertificate = new import_node_crypto17.X509Certificate(ca2.certPem);
114404
+ const caPrivateKey = (0, import_node_crypto17.createPrivateKey)(ca2.keyPem);
114208
114405
  const { publicKey, privateKey } = rsaKeyPair();
114209
114406
  const generalNames = names.map((name) => import_node_net.default.isIP(name) === 0 ? tlv(TAG_GENERAL_NAME_DNS, Buffer.from(name, "ascii")) : tlv(TAG_GENERAL_NAME_IP, ipBytes(name)));
114210
114407
  const der = assemble({
@@ -114559,8 +114756,8 @@ function ensureCa(store, generate) {
114559
114756
  }
114560
114757
  function caParses(ca2) {
114561
114758
  try {
114562
- new import_node_crypto17.X509Certificate(ca2.certPem);
114563
- (0, import_node_crypto17.createPrivateKey)(ca2.keyPem);
114759
+ new import_node_crypto18.X509Certificate(ca2.certPem);
114760
+ (0, import_node_crypto18.createPrivateKey)(ca2.keyPem);
114564
114761
  return true;
114565
114762
  } catch {
114566
114763
  return false;
@@ -114887,7 +115084,7 @@ var LiveTaskSchema = external_exports.strictObject({
114887
115084
  observedAt: external_exports.number()
114888
115085
  });
114889
115086
  var SYSTEM_SUBTYPES = ["task_started", "task_progress", "task_updated", "task_notification", "background_tasks_changed"];
114890
- function isRecord4(value2) {
115087
+ function isRecord5(value2) {
114891
115088
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
114892
115089
  }
114893
115090
  function stringField(record2, field) {
@@ -114904,7 +115101,7 @@ function booleanField(record2, field) {
114904
115101
  }
114905
115102
  function usageOf(record2) {
114906
115103
  const raw = record2.usage;
114907
- if (!isRecord4(raw)) {
115104
+ if (!isRecord5(raw)) {
114908
115105
  return void 0;
114909
115106
  }
114910
115107
  const totalTokens = numberField(raw, "total_tokens");
@@ -114936,7 +115133,7 @@ function bounded(book) {
114936
115133
  return book;
114937
115134
  }
114938
115135
  function applyAgentTaskEvent(book, sessionId, payload, observedAt2) {
114939
- if (!isRecord4(payload) || payload.type !== "system") {
115136
+ if (!isRecord5(payload) || payload.type !== "system") {
114940
115137
  return book;
114941
115138
  }
114942
115139
  const subtype = payload.subtype;
@@ -114952,8 +115149,8 @@ function applyAgentTaskEvent(book, sessionId, payload, observedAt2) {
114952
115149
  if (subtype === "background_tasks_changed") {
114953
115150
  const tasks = Array.isArray(payload.tasks) ? payload.tasks : [];
114954
115151
  for (const raw of tasks) {
114955
- const taskId2 = isRecord4(raw) ? stringField(raw, "task_id") : void 0;
114956
- if (isRecord4(raw) && taskId2 !== void 0) {
115152
+ const taskId2 = isRecord5(raw) ? stringField(raw, "task_id") : void 0;
115153
+ if (isRecord5(raw) && taskId2 !== void 0) {
114957
115154
  upsert(taskId2, { runId: stringField(raw, "run_id"), taskType: stringField(raw, "task_type"), description: stringField(raw, "description") });
114958
115155
  }
114959
115156
  }
@@ -114976,7 +115173,7 @@ function applyAgentTaskEvent(book, sessionId, payload, observedAt2) {
114976
115173
  } else if (subtype === "task_progress") {
114977
115174
  upsert(taskId, { ...common, subagentType: stringField(payload, "subagent_type"), lastToolName: stringField(payload, "last_tool_name"), usage: usageOf(payload) });
114978
115175
  } else if (subtype === "task_updated") {
114979
- const patch = isRecord4(payload.patch) ? payload.patch : {};
115176
+ const patch = isRecord5(payload.patch) ? payload.patch : {};
114980
115177
  upsert(taskId, { runId: stringField(payload, "run_id"), status: stringField(patch, "status") });
114981
115178
  } else {
114982
115179
  upsert(taskId, { ...common, status: stringField(payload, "status"), outputFile: stringField(payload, "output_file"), summary: stringField(payload, "summary"), usage: usageOf(payload) });
@@ -115058,7 +115255,7 @@ function sessionCreateId(body) {
115058
115255
  const id2 = session.id;
115059
115256
  return typeof id2 === "string" && id2.startsWith(RC_SESSION_ID_PREFIX) ? id2 : void 0;
115060
115257
  }
115061
- function isRecord5(value2) {
115258
+ function isRecord6(value2) {
115062
115259
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
115063
115260
  }
115064
115261
  function parseJsonObject(body) {
@@ -115068,7 +115265,7 @@ function parseJsonObject(body) {
115068
115265
  } catch {
115069
115266
  return void 0;
115070
115267
  }
115071
- return isRecord5(parsed) ? parsed : void 0;
115268
+ return isRecord6(parsed) ? parsed : void 0;
115072
115269
  }
115073
115270
  function nonEmptyString(record2, field) {
115074
115271
  const value2 = record2 === void 0 ? void 0 : record2[field];
@@ -115089,11 +115286,11 @@ function payloadEventsOf(body) {
115089
115286
  }
115090
115287
  const payloads = [];
115091
115288
  for (const event of events) {
115092
- if (!isRecord5(event)) {
115289
+ if (!isRecord6(event)) {
115093
115290
  continue;
115094
115291
  }
115095
115292
  const payload = event.payload;
115096
- if (!isRecord5(payload)) {
115293
+ if (!isRecord6(payload)) {
115097
115294
  continue;
115098
115295
  }
115099
115296
  payloads.push(payload);
@@ -115108,7 +115305,7 @@ function pendingOfControlRequestPayload(payload) {
115108
115305
  if (requestId === void 0) {
115109
115306
  return void 0;
115110
115307
  }
115111
- const request7 = isRecord5(payload.request) ? payload.request : void 0;
115308
+ const request7 = isRecord6(payload.request) ? payload.request : void 0;
115112
115309
  const subtype = nonEmptyString(request7, "subtype");
115113
115310
  const type2 = subtype ?? "control_request";
115114
115311
  let summary = "";
@@ -115125,7 +115322,7 @@ function answeredRequestIdsOfControlResponsePayload(payload) {
115125
115322
  if (payload.type !== "control_response") {
115126
115323
  return [];
115127
115324
  }
115128
- const response = isRecord5(payload.response) ? payload.response : void 0;
115325
+ const response = isRecord6(payload.response) ? payload.response : void 0;
115129
115326
  const id2 = nonEmptyString(response, "request_id") ?? nonEmptyString(payload, "request_id") ?? nonEmptyString(payload, "uuid");
115130
115327
  return id2 === void 0 ? [] : [id2];
115131
115328
  }
@@ -115354,7 +115551,7 @@ function createRcSessionTracker(deps) {
115354
115551
  return;
115355
115552
  }
115356
115553
  entry.sequenceNum = entry.sequenceNum === void 0 || event.sequence_num > entry.sequenceNum ? event.sequence_num : entry.sequenceNum;
115357
- if (!isRecord5(event.payload)) {
115554
+ if (!isRecord6(event.payload)) {
115358
115555
  return;
115359
115556
  }
115360
115557
  entry.liveTasks = applyAgentTaskEvent(entry.liveTasks, sessionId, event.payload, deps.now());
@@ -120232,7 +120429,7 @@ var HTTP_METHODS_UP_TO_V31 = [
120232
120429
  function operationFields(convert) {
120233
120430
  return Object.fromEntries(HTTP_METHODS_UP_TO_V31.map((method) => [method, convert]));
120234
120431
  }
120235
- function isRecord6(value2) {
120432
+ function isRecord7(value2) {
120236
120433
  if (typeof value2 !== "object" || value2 === null) {
120237
120434
  return false;
120238
120435
  }
@@ -120252,7 +120449,7 @@ function setOwn2(object3, key, value2) {
120252
120449
  }
120253
120450
  }
120254
120451
  function cloneValue(value2, seen) {
120255
- if (!(Array.isArray(value2) || isRecord6(value2))) {
120452
+ if (!(Array.isArray(value2) || isRecord7(value2))) {
120256
120453
  return value2;
120257
120454
  }
120258
120455
  const existing = seen.get(value2);
@@ -120275,14 +120472,14 @@ function cloneValue(value2, seen) {
120275
120472
  return out;
120276
120473
  }
120277
120474
  function deepClone(value2) {
120278
- if (!(Array.isArray(value2) || isRecord6(value2))) {
120475
+ if (!(Array.isArray(value2) || isRecord7(value2))) {
120279
120476
  return value2;
120280
120477
  }
120281
120478
  return cloneValue(value2, /* @__PURE__ */ new WeakMap());
120282
120479
  }
120283
120480
  var converting = /* @__PURE__ */ new WeakMap();
120284
120481
  function convertRecord(value2, fields, finish) {
120285
- if (!isRecord6(value2)) {
120482
+ if (!isRecord7(value2)) {
120286
120483
  return deepClone(value2);
120287
120484
  }
120288
120485
  const inProgress = converting.get(value2);
@@ -120308,7 +120505,7 @@ function convertRecord(value2, fields, finish) {
120308
120505
  }
120309
120506
  }
120310
120507
  function mapRecord(value2, convert) {
120311
- if (!isRecord6(value2)) {
120508
+ if (!isRecord7(value2)) {
120312
120509
  return deepClone(value2);
120313
120510
  }
120314
120511
  const out = {};
@@ -120327,7 +120524,7 @@ function mapArray(value2, convert) {
120327
120524
  return value2.map((item) => convert(item)).filter((item) => item !== DROP);
120328
120525
  }
120329
120526
  function getRef(value2) {
120330
- if (isRecord6(value2) && typeof value2.$ref === "string") {
120527
+ if (isRecord7(value2) && typeof value2.$ref === "string") {
120331
120528
  return value2.$ref;
120332
120529
  }
120333
120530
  return void 0;
@@ -120533,7 +120730,7 @@ function convertSchema2(schema) {
120533
120730
  if (schema === false) {
120534
120731
  return { not: {} };
120535
120732
  }
120536
- if (isRecord6(schema) && typeof schema.$ref === "string" && Object.keys(schema).length === 1) {
120733
+ if (isRecord7(schema) && typeof schema.$ref === "string" && Object.keys(schema).length === 1) {
120537
120734
  return { $ref: schema.$ref };
120538
120735
  }
120539
120736
  return convertRecord(schema, SCHEMA_FIELDS, finishSchema);
@@ -120545,7 +120742,7 @@ function resolveSchemeType(name, schemes, seen) {
120545
120742
  return void 0;
120546
120743
  }
120547
120744
  const scheme = schemes[name];
120548
- if (!isRecord6(scheme)) {
120745
+ if (!isRecord7(scheme)) {
120549
120746
  return void 0;
120550
120747
  }
120551
120748
  if (typeof scheme.type === "string") {
@@ -120562,11 +120759,11 @@ function resolveSchemeType(name, schemes, seen) {
120562
120759
  return void 0;
120563
120760
  }
120564
120761
  function createContext(spec) {
120565
- const components = isRecord6(spec) ? spec.components : void 0;
120566
- const pathItems = isRecord6(components) ? components.pathItems : void 0;
120567
- const schemes = isRecord6(components) ? components.securitySchemes : void 0;
120762
+ const components = isRecord7(spec) ? spec.components : void 0;
120763
+ const pathItems = isRecord7(components) ? components.pathItems : void 0;
120764
+ const schemes = isRecord7(components) ? components.securitySchemes : void 0;
120568
120765
  const schemeTypes = /* @__PURE__ */ new Map();
120569
- if (isRecord6(schemes)) {
120766
+ if (isRecord7(schemes)) {
120570
120767
  for (const name of Object.keys(schemes)) {
120571
120768
  const type2 = resolveSchemeType(name, schemes, /* @__PURE__ */ new Set());
120572
120769
  if (type2 !== void 0) {
@@ -120576,7 +120773,7 @@ function createContext(spec) {
120576
120773
  }
120577
120774
  return {
120578
120775
  inlining: /* @__PURE__ */ new Set(),
120579
- pathItems: isRecord6(pathItems) ? pathItems : void 0,
120776
+ pathItems: isRecord7(pathItems) ? pathItems : void 0,
120580
120777
  schemeTypes
120581
120778
  };
120582
120779
  }
@@ -120584,7 +120781,7 @@ function isMutualTls(name, context) {
120584
120781
  return context.schemeTypes.get(name) === "mutualTLS";
120585
120782
  }
120586
120783
  function convertRequirement(value2, context) {
120587
- if (!isRecord6(value2)) {
120784
+ if (!isRecord7(value2)) {
120588
120785
  return deepClone(value2);
120589
120786
  }
120590
120787
  const entries = Object.entries(value2);
@@ -120684,10 +120881,10 @@ function resolvePathItemRef(value2, context) {
120684
120881
  return void 0;
120685
120882
  }
120686
120883
  const target = context.pathItems[name];
120687
- return isRecord6(target) ? [name, target] : void 0;
120884
+ return isRecord7(target) ? [name, target] : void 0;
120688
120885
  }
120689
120886
  function convertPathItem(value2, context) {
120690
- if (!isRecord6(value2)) {
120887
+ if (!isRecord7(value2)) {
120691
120888
  return deepClone(value2);
120692
120889
  }
120693
120890
  const resolved = resolvePathItemRef(value2, context);
@@ -120787,7 +120984,7 @@ function convertExample(value2) {
120787
120984
  });
120788
120985
  }
120789
120986
  function isQuerystringParameter(value2) {
120790
- return isRecord6(value2) && value2.in === "querystring";
120987
+ return isRecord7(value2) && value2.in === "querystring";
120791
120988
  }
120792
120989
  function isRemovedRef(value2, removed) {
120793
120990
  const ref = getRef(value2);
@@ -120803,7 +121000,7 @@ function convertParameterOrHeader2(value2, context) {
120803
121000
  style: (item) => item === "cookie" ? DROP : deepClone(item)
120804
121001
  },
120805
121002
  (out, parameter) => {
120806
- const lostContent = isRecord6(parameter.content) && Object.keys(parameter.content).length > 0 && isRecord6(out.content) && Object.keys(out.content).length === 0;
121003
+ const lostContent = isRecord7(parameter.content) && Object.keys(parameter.content).length > 0 && isRecord7(out.content) && Object.keys(out.content).length === 0;
120807
121004
  return lostContent ? DROP : out;
120808
121005
  }
120809
121006
  );
@@ -120924,7 +121121,7 @@ function convertComponents2(value2, context) {
120924
121121
  });
120925
121122
  }
120926
121123
  function losesEntireContent(value2, mediaTypes) {
120927
- if (!(isRecord6(value2) && isRecord6(value2.content))) {
121124
+ if (!(isRecord7(value2) && isRecord7(value2.content))) {
120928
121125
  return false;
120929
121126
  }
120930
121127
  const entries = Object.values(value2.content);
@@ -120932,7 +121129,7 @@ function losesEntireContent(value2, mediaTypes) {
120932
121129
  }
120933
121130
  function indexRemovedComponentRefs(map2, prefix, mediaTypes, isDirectlyRemoved) {
120934
121131
  const removed = /* @__PURE__ */ new Set();
120935
- if (!isRecord6(map2)) {
121132
+ if (!isRecord7(map2)) {
120936
121133
  return removed;
120937
121134
  }
120938
121135
  const entries = Object.entries(map2);
@@ -120954,12 +121151,12 @@ function indexRemovedComponentRefs(map2, prefix, mediaTypes, isDirectlyRemoved)
120954
121151
  return removed;
120955
121152
  }
120956
121153
  function createContext2(spec) {
120957
- const components = isRecord6(spec) ? spec.components : void 0;
120958
- const mediaTypes = isRecord6(components) && isRecord6(components.mediaTypes) ? components.mediaTypes : void 0;
121154
+ const components = isRecord7(spec) ? spec.components : void 0;
121155
+ const mediaTypes = isRecord7(components) && isRecord7(components.mediaTypes) ? components.mediaTypes : void 0;
120959
121156
  return {
120960
121157
  mediaTypes,
120961
- removedHeaderRefs: indexRemovedComponentRefs(isRecord6(components) ? components.headers : void 0, HEADERS_REF_PREFIX, mediaTypes, () => false),
120962
- removedParameterRefs: indexRemovedComponentRefs(isRecord6(components) ? components.parameters : void 0, PARAMETERS_REF_PREFIX, mediaTypes, isQuerystringParameter)
121158
+ removedHeaderRefs: indexRemovedComponentRefs(isRecord7(components) ? components.headers : void 0, HEADERS_REF_PREFIX, mediaTypes, () => false),
121159
+ removedParameterRefs: indexRemovedComponentRefs(isRecord7(components) ? components.parameters : void 0, PARAMETERS_REF_PREFIX, mediaTypes, isQuerystringParameter)
120963
121160
  };
120964
121161
  }
120965
121162
  function convertJsonSchemaDialect(value2) {
@@ -126647,7 +126844,7 @@ function createQuotaExpiringPublisher(hub, deps) {
126647
126844
  latest.set(snapshot.identity, snapshot);
126648
126845
  });
126649
126846
  const announced = /* @__PURE__ */ new Set();
126650
- const windowsOf = (snapshot) => {
126847
+ const windowsOf2 = (snapshot) => {
126651
126848
  const views = [];
126652
126849
  for (const provider of Object.keys(snapshot.providers).sort()) {
126653
126850
  const unified = snapshot.providers[provider]?.rateLimit?.unified;
@@ -126670,7 +126867,7 @@ function createQuotaExpiringPublisher(hub, deps) {
126670
126867
  if (snapshot === void 0) {
126671
126868
  continue;
126672
126869
  }
126673
- for (const { provider, view } of windowsOf(snapshot)) {
126870
+ for (const { provider, view } of windowsOf2(snapshot)) {
126674
126871
  if (view.utilization >= 1 || view.resetsAtMs <= now || view.resetsAtMs - now >= view.spanMs * QUOTA_EXPIRING_WINDOW_FRACTION) {
126675
126872
  continue;
126676
126873
  }
@@ -126728,7 +126925,7 @@ var import_consumers = require("node:stream/consumers");
126728
126925
  init_route();
126729
126926
 
126730
126927
  // src/frontdoor/lineage.ts
126731
- var import_node_crypto18 = require("node:crypto");
126928
+ var import_node_crypto19 = require("node:crypto");
126732
126929
  var CACHE_MARKER_KEY = '"cache_control"';
126733
126930
  var THREAD_MEMBER_KEYS = /* @__PURE__ */ new Set(['"model"', '"system"', '"tools"']);
126734
126931
  var MESSAGES_KEY = '"messages"';
@@ -126805,8 +127002,8 @@ function nextToken(body, from) {
126805
127002
  return SCALAR;
126806
127003
  }
126807
127004
  function walk(body, hashing, parentAfter) {
126808
- const thread = (0, import_node_crypto18.createHash)("sha256");
126809
- const messages = (0, import_node_crypto18.createHash)("sha256");
127005
+ const thread = (0, import_node_crypto19.createHash)("sha256");
127006
+ const messages = (0, import_node_crypto19.createHash)("sha256");
126810
127007
  let parentDigest;
126811
127008
  let elements = 0;
126812
127009
  let depth = 0;
@@ -126927,7 +127124,7 @@ function lineageOf(body) {
126927
127124
  }
126928
127125
  const parentAfter = counted.elements > MESSAGES_PER_TURN ? counted.elements - MESSAGES_PER_TURN : void 0;
126929
127126
  const hashed = walk(body, true, parentAfter);
126930
- const combine = (messagesDigest) => (0, import_node_crypto18.createHash)("sha256").update(hashed.threadDigest).update(messagesDigest).digest("hex");
127127
+ const combine = (messagesDigest) => (0, import_node_crypto19.createHash)("sha256").update(hashed.threadDigest).update(messagesDigest).digest("hex");
126931
127128
  return { ownKey: combine(hashed.messagesDigest), parentKey: hashed.parentDigest === void 0 ? void 0 : combine(hashed.parentDigest) };
126932
127129
  }
126933
127130
 
@@ -127312,7 +127509,7 @@ init_load();
127312
127509
  init_schema();
127313
127510
 
127314
127511
  // src/codex/translate.ts
127315
- var import_node_crypto19 = require("node:crypto");
127512
+ var import_node_crypto20 = require("node:crypto");
127316
127513
  init_schema();
127317
127514
 
127318
127515
  // src/codex/anthropic.ts
@@ -127427,7 +127624,7 @@ function shortToolName(name, names) {
127427
127624
  if (name.length <= CODEX_TOOL_NAME_LIMIT) {
127428
127625
  return name;
127429
127626
  }
127430
- const hash2 = (0, import_node_crypto19.createHash)("sha256").update(name).digest("hex").slice(0, TOOL_NAME_HASH_CHARS);
127627
+ const hash2 = (0, import_node_crypto20.createHash)("sha256").update(name).digest("hex").slice(0, TOOL_NAME_HASH_CHARS);
127431
127628
  const shortened = `${name.slice(0, CODEX_TOOL_NAME_LIMIT - TOOL_NAME_HASH_CHARS - 1)}_${hash2}`;
127432
127629
  names.set(shortened, name);
127433
127630
  return shortened;
@@ -127552,7 +127749,7 @@ function translateRequest(body, config2) {
127552
127749
  }
127553
127750
 
127554
127751
  // src/antigravity/translate.ts
127555
- var import_node_crypto20 = require("node:crypto");
127752
+ var import_node_crypto21 = require("node:crypto");
127556
127753
 
127557
127754
  // src/antigravity/signatures.ts
127558
127755
  var MAX_REMEMBERED = 1024;
@@ -127595,11 +127792,13 @@ function resolveAntigravityConfig(config2) {
127595
127792
  }
127596
127793
  };
127597
127794
  }
127795
+ var CONTEXT_MARKER_1M = "[1m]";
127598
127796
  function mapModel2(requested, config2) {
127599
- if (requested.startsWith("gemini-") || requested.startsWith("antigravity-")) {
127600
- return requested;
127797
+ const stripped = requested.toLowerCase().endsWith(CONTEXT_MARKER_1M) ? requested.slice(0, -CONTEXT_MARKER_1M.length) : requested;
127798
+ if (stripped.startsWith("gemini-") || stripped.startsWith("antigravity-")) {
127799
+ return stripped;
127601
127800
  }
127602
- const lower = requested.toLowerCase();
127801
+ const lower = stripped.toLowerCase();
127603
127802
  const tier = ANTIGRAVITY_TIERS.find((candidate) => lower.includes(candidate));
127604
127803
  return tier === void 0 ? config2.defaultModel : config2.models[tier];
127605
127804
  }
@@ -127637,7 +127836,7 @@ function shortToolName2(name, names) {
127637
127836
  if (sanitized.length <= ANTIGRAVITY_TOOL_NAME_LIMIT) {
127638
127837
  result = sanitized;
127639
127838
  } else {
127640
- const hash2 = (0, import_node_crypto20.createHash)("sha256").update(name).digest("hex").slice(0, TOOL_NAME_HASH_CHARS2);
127839
+ const hash2 = (0, import_node_crypto21.createHash)("sha256").update(name).digest("hex").slice(0, TOOL_NAME_HASH_CHARS2);
127641
127840
  const prefix = sanitized.slice(0, ANTIGRAVITY_TOOL_NAME_LIMIT - TOOL_NAME_HASH_CHARS2 - 1);
127642
127841
  result = `${prefix}_${hash2}`;
127643
127842
  }
@@ -127666,7 +127865,7 @@ function turnBlocks2(message) {
127666
127865
  }
127667
127866
  return blocks.map((block2) => isTextBlock(block2) ? { ...block2, text: systemReminder2(block2.text) } : block2);
127668
127867
  }
127669
- function isRecord7(value2) {
127868
+ function isRecord8(value2) {
127670
127869
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
127671
127870
  }
127672
127871
  function messagesToGeminiContents(messages, names, toolIdToName) {
@@ -127712,7 +127911,7 @@ function messagesToGeminiContents(messages, names, toolIdToName) {
127712
127911
  ensureRole("model").push({
127713
127912
  functionCall: {
127714
127913
  name: sanitizedName,
127715
- args: isRecord7(block2.input) ? block2.input : {}
127914
+ args: isRecord8(block2.input) ? block2.input : {}
127716
127915
  },
127717
127916
  // The relay remembered the signature the backend attached to this exact call; echoing it back is what the backend requires of a repeated function call.
127718
127917
  ...signature === void 0 ? {} : { thoughtSignature: signature }
@@ -127734,7 +127933,7 @@ function messagesToGeminiContents(messages, names, toolIdToName) {
127734
127933
  var EMPTY_SCHEMA = { type: "object", properties: {} };
127735
127934
  var GEMINI_SCHEMA_KEYS = /* @__PURE__ */ new Set(["type", "format", "description", "nullable", "enum", "anyOf", "items", "properties", "required", "minimum", "maximum", "minItems", "maxItems"]);
127736
127935
  function describeSchemaValue(node2) {
127737
- if (!isRecord7(node2)) {
127936
+ if (!isRecord8(node2)) {
127738
127937
  return "any value";
127739
127938
  }
127740
127939
  const type2 = node2.type;
@@ -127745,7 +127944,7 @@ function describeSchemaValue(node2) {
127745
127944
  return name === "object" ? "an object" : `a ${name}`;
127746
127945
  }
127747
127946
  function toGeminiSchema(node2) {
127748
- if (!isRecord7(node2)) {
127947
+ if (!isRecord8(node2)) {
127749
127948
  return node2;
127750
127949
  }
127751
127950
  const out = {};
@@ -127763,7 +127962,7 @@ function toGeminiSchema(node2) {
127763
127962
  if (!GEMINI_SCHEMA_KEYS.has(key)) {
127764
127963
  if (key === "additionalProperties" && value2 !== false) {
127765
127964
  notes.push(`Each value is ${describeSchemaValue(value2)}.`);
127766
- } else if (key === "propertyNames" && isRecord7(value2) && typeof value2.pattern === "string") {
127965
+ } else if (key === "propertyNames" && isRecord8(value2) && typeof value2.pattern === "string") {
127767
127966
  notes.push(`Keys match ${value2.pattern}.`);
127768
127967
  }
127769
127968
  continue;
@@ -127780,7 +127979,7 @@ function toGeminiSchema(node2) {
127780
127979
  const description = typeof out.description === "string" ? out.description : "";
127781
127980
  out.description = `${description}${description === "" ? "" : " "}${notes.join(" ")}`;
127782
127981
  }
127783
- if ("properties" in out && isRecord7(out.properties)) {
127982
+ if ("properties" in out && isRecord8(out.properties)) {
127784
127983
  out.properties = Object.fromEntries(Object.entries(out.properties).map(([name, child]) => [name, toGeminiSchema(child)]));
127785
127984
  }
127786
127985
  if ("items" in out) {
@@ -127802,7 +128001,7 @@ function mapTools2(tools, names) {
127802
128001
  return {
127803
128002
  name: shortToolName2(tool.name, names),
127804
128003
  description: tool.description,
127805
- parameters: isRecord7(converted) ? converted : EMPTY_SCHEMA
128004
+ parameters: isRecord8(converted) ? converted : EMPTY_SCHEMA
127806
128005
  };
127807
128006
  });
127808
128007
  return [{ functionDeclarations: declarations }];
@@ -127853,124 +128052,12 @@ function translateRequest2(request7, config2) {
127853
128052
  };
127854
128053
  }
127855
128054
 
127856
- // src/antigravity/cloudUpstream.ts
127857
- var import_node_crypto21 = require("node:crypto");
127858
- var CCPA_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
127859
- var CCPA_DEFAULT_PROJECT_ID = "aicode-consumers";
127860
- var CCPA_USER_AGENT = "antigravity/cli/1.3.5 (aidev_client; os_type=darwin; arch=arm64; cl=998863838; auth_method=consumer)";
127861
- function isCcpaEndpoint(endpoint) {
127862
- return endpoint.includes("cloudcode-pa.googleapis.com");
127863
- }
127864
- function buildCloudUrl(config2, model) {
127865
- const { cloud } = config2;
127866
- if (cloud.projectId !== void 0 && cloud.location !== void 0) {
127867
- const base2 = cloud.endpoint ?? `https://${cloud.location}-aiplatform.googleapis.com`;
127868
- return `${base2}/v1/projects/${cloud.projectId}/locations/${cloud.location}/publishers/google/models/${encodeURIComponent(model)}:streamGenerateContent?alt=sse`;
127869
- }
127870
- const base = cloud.endpoint ?? CCPA_ENDPOINT;
127871
- if (isCcpaEndpoint(base)) {
127872
- return `${base}/v1internal:streamGenerateContent?alt=sse`;
127873
- }
127874
- return `${base}/v1beta/models/${encodeURIComponent(model)}:streamGenerateContent?alt=sse`;
127875
- }
127876
- function buildCloudHeaders(token, credentialTarget, endpoint) {
127877
- const headers = {
127878
- "Content-Type": "application/json",
127879
- Accept: "text/event-stream"
127880
- };
127881
- const target = credentialTarget ?? "bearer";
127882
- if (target === "apiKey") {
127883
- headers["x-goog-api-key"] = token;
127884
- } else {
127885
- headers.Authorization = `Bearer ${token}`;
127886
- }
127887
- const base = endpoint ?? CCPA_ENDPOINT;
127888
- if (isCcpaEndpoint(base)) {
127889
- headers["User-Agent"] = CCPA_USER_AGENT;
127890
- }
127891
- return headers;
127892
- }
127893
- function buildCloudRequestBody(params) {
127894
- const base = params.config.cloud.endpoint ?? CCPA_ENDPOINT;
127895
- if (isCcpaEndpoint(base)) {
127896
- return JSON.stringify({
127897
- project: params.config.cloud.projectId ?? CCPA_DEFAULT_PROJECT_ID,
127898
- requestId: `agent/${(0, import_node_crypto21.randomUUID)()}/${String(Date.now())}/1`,
127899
- request: params.request,
127900
- model: params.model,
127901
- userAgent: "antigravity"
127902
- });
127903
- }
127904
- return JSON.stringify(params.request);
127905
- }
127906
- function isRecord8(value2) {
127907
- return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
127908
- }
127909
- function isGeminiChunk(value2) {
127910
- return isRecord8(value2);
127911
- }
127912
- var AntigravityUpstreamError = class extends Error {
127913
- status;
127914
- retryAfter;
127915
- constructor(status, message, retryAfter) {
127916
- super(`Google Antigravity API error (${String(status)}): ${message}`);
127917
- this.name = "AntigravityUpstreamError";
127918
- this.status = status;
127919
- this.retryAfter = retryAfter;
127920
- }
127921
- };
127922
- async function* callCloudAntigravity(params, fetchFn = fetch) {
127923
- const url2 = buildCloudUrl(params.config, params.model);
127924
- const headers = buildCloudHeaders(params.token, params.credentialTarget, params.config.cloud.endpoint);
127925
- const body = buildCloudRequestBody(params);
127926
- const response = await fetchFn(url2, {
127927
- method: "POST",
127928
- headers,
127929
- body,
127930
- signal: params.signal
127931
- });
127932
- if (!response.ok) {
127933
- const errorText = await response.text();
127934
- const retryAfter = response.headers.get("retry-after");
127935
- throw new AntigravityUpstreamError(response.status, errorText, retryAfter);
127936
- }
127937
- if (response.body === null) {
127938
- return;
127939
- }
127940
- const decoder = new TextDecoder("utf-8");
127941
- let buffer2 = "";
127942
- const sseDataPrefix = "data:";
127943
- for await (const rawChunk of response.body) {
127944
- const chunk = rawChunk instanceof Uint8Array ? rawChunk : Buffer.from(String(rawChunk));
127945
- buffer2 += decoder.decode(chunk, { stream: true });
127946
- const lines = buffer2.split("\n");
127947
- buffer2 = lines.pop() ?? "";
127948
- for (const line of lines) {
127949
- const trimmed = line.trim();
127950
- if (trimmed.startsWith(sseDataPrefix)) {
127951
- const jsonStr = trimmed.slice(sseDataPrefix.length).trim();
127952
- if (jsonStr.length > 0) {
127953
- try {
127954
- const parsed = JSON.parse(jsonStr);
127955
- if (isRecord8(parsed)) {
127956
- const unwrapped = isRecord8(parsed.response) ? parsed.response : parsed;
127957
- if (isGeminiChunk(unwrapped)) {
127958
- yield unwrapped;
127959
- }
127960
- }
127961
- } catch {
127962
- }
127963
- }
127964
- }
127965
- }
127966
- }
127967
- }
127968
-
127969
128055
  // src/antigravity/quota.ts
128056
+ init_cloudUpstream();
127970
128057
  var MS_PER_SECOND8 = 1e3;
127971
128058
  var DEFAULT_RETRY_AFTER_SECONDS = 60;
127972
- var PERCENT_MULTIPLIER = 100;
127973
- var EXHAUSTED_PERCENT = "100";
128059
+ var FRACTION_DIGITS = 3;
128060
+ var EXHAUSTED_FRACTION = "1.000";
127974
128061
  var GEMINI_5H_KEYS = ["gemini-5h", "gemini_5h", "gemini"];
127975
128062
  var GEMINI_WEEKLY_KEYS = ["gemini-weekly", "gemini_weekly"];
127976
128063
  var THIRD_PARTY_5H_KEYS = ["3p-5h", "claude-5h", "3p_5h", "claude_5h", "claude"];
@@ -127990,7 +128077,7 @@ function calculateUtilization(remainingFraction) {
127990
128077
  }
127991
128078
  const clampedRem = Math.max(0, Math.min(1, remainingFraction));
127992
128079
  const used = Math.max(0, 1 - clampedRem);
127993
- return String(Math.round(used * PERCENT_MULTIPLIER));
128080
+ return used.toFixed(FRACTION_DIGITS);
127994
128081
  }
127995
128082
  function calculateResetTimestamp(nowSec, resetInSeconds) {
127996
128083
  if (resetInSeconds === void 0 || !Number.isFinite(resetInSeconds) || resetInSeconds < 0) {
@@ -128016,9 +128103,6 @@ function parseRetryAfterSeconds(raw, defaultSeconds = DEFAULT_RETRY_AFTER_SECOND
128016
128103
  function unifiedAntigravityQuotaHeaders(params) {
128017
128104
  const rejected = params.rejected === true;
128018
128105
  const nowSec = Math.floor(params.nowMs / MS_PER_SECOND8);
128019
- const headers = {
128020
- "anthropic-ratelimit-unified-status": rejected ? "rejected" : "allowed"
128021
- };
128022
128106
  const modelLower = (params.model ?? "").toLowerCase();
128023
128107
  const isGemini = modelLower.includes("gemini");
128024
128108
  const fiveHourKeys = isGemini ? GEMINI_5H_KEYS : THIRD_PARTY_5H_KEYS;
@@ -128030,6 +128114,12 @@ function unifiedAntigravityQuotaHeaders(params) {
128030
128114
  const reset5h = calculateResetTimestamp(nowSec, b5h?.reset_in_seconds);
128031
128115
  const used7d = calculateUtilization(bWk?.remaining_fraction);
128032
128116
  const reset7d = calculateResetTimestamp(nowSec, bWk?.reset_in_seconds);
128117
+ if (!rejected && used5h === void 0 && reset5h === void 0 && used7d === void 0 && reset7d === void 0) {
128118
+ return {};
128119
+ }
128120
+ const headers = {
128121
+ "anthropic-ratelimit-unified-status": rejected ? "rejected" : "allowed"
128122
+ };
128033
128123
  let earliestResetSec;
128034
128124
  if (used5h !== void 0 && reset5h !== void 0) {
128035
128125
  headers["anthropic-ratelimit-unified-5h-utilization"] = used5h;
@@ -128046,11 +128136,11 @@ function unifiedAntigravityQuotaHeaders(params) {
128046
128136
  const retrySec = params.retryAfterSeconds ?? DEFAULT_RETRY_AFTER_SECONDS;
128047
128137
  const fallbackReset = String(nowSec + retrySec);
128048
128138
  if (headers["anthropic-ratelimit-unified-5h-utilization"] === void 0) {
128049
- headers["anthropic-ratelimit-unified-5h-utilization"] = EXHAUSTED_PERCENT;
128139
+ headers["anthropic-ratelimit-unified-5h-utilization"] = EXHAUSTED_FRACTION;
128050
128140
  headers["anthropic-ratelimit-unified-5h-reset"] = fallbackReset;
128051
128141
  }
128052
128142
  if (headers["anthropic-ratelimit-unified-7d-utilization"] === void 0) {
128053
- headers["anthropic-ratelimit-unified-7d-utilization"] = EXHAUSTED_PERCENT;
128143
+ headers["anthropic-ratelimit-unified-7d-utilization"] = EXHAUSTED_FRACTION;
128054
128144
  headers["anthropic-ratelimit-unified-7d-reset"] = fallbackReset;
128055
128145
  }
128056
128146
  earliestResetSec = earliestResetSec === void 0 ? nowSec + retrySec : Math.min(earliestResetSec, nowSec + retrySec);
@@ -128285,10 +128375,10 @@ function quotaHeaders(upstream) {
128285
128375
  }
128286
128376
  return headers;
128287
128377
  }
128288
- var EXHAUSTED_PERCENT2 = "100";
128378
+ var EXHAUSTED_PERCENT = "100";
128289
128379
  function unifiedQuotaHeaders(upstream, rejected, quotaError) {
128290
128380
  const headers = { "anthropic-ratelimit-unified-status": rejected ? "rejected" : "allowed" };
128291
- const used7d = upstream.get("x-codex-primary-used-percent") ?? (rejected ? EXHAUSTED_PERCENT2 : null);
128381
+ const used7d = upstream.get("x-codex-primary-used-percent") ?? (rejected ? EXHAUSTED_PERCENT : null);
128292
128382
  const reset7d = upstream.get("x-codex-primary-reset-at") ?? (quotaError?.resets_at === void 0 ? null : String(quotaError.resets_at));
128293
128383
  if (used7d !== null && reset7d !== null) {
128294
128384
  headers["anthropic-ratelimit-unified-7d-utilization"] = used7d;
@@ -128311,7 +128401,7 @@ function unifiedQuotaHeaders(upstream, rejected, quotaError) {
128311
128401
  }
128312
128402
  var MS_PER_SECOND9 = 1e3;
128313
128403
  function buildUsageSnapshot(upstream, quotaError, nowMs) {
128314
- const used7 = upstream.get("x-codex-primary-used-percent") ?? (quotaError === void 0 ? null : EXHAUSTED_PERCENT2);
128404
+ const used7 = upstream.get("x-codex-primary-used-percent") ?? (quotaError === void 0 ? null : EXHAUSTED_PERCENT);
128315
128405
  const reset7 = upstream.get("x-codex-primary-reset-at") ?? (quotaError?.resets_at === void 0 ? null : String(quotaError.resets_at));
128316
128406
  const sevenDay = used7 !== null && reset7 !== null ? { used_percentage: Number(used7), resets_at: new Date(Number(reset7) * MS_PER_SECOND9).toISOString() } : void 0;
128317
128407
  let fiveHour;
@@ -128803,10 +128893,12 @@ function createAntigravityRelay(params) {
128803
128893
  frames.length = 0;
128804
128894
  ensureStarted();
128805
128895
  if (chunk.usageMetadata !== void 0) {
128896
+ const cached2 = chunk.usageMetadata.cachedContentTokenCount ?? 0;
128897
+ const promptTotal = chunk.usageMetadata.promptTokenCount ?? usage.input_tokens + cached2;
128806
128898
  usage = {
128807
- input_tokens: chunk.usageMetadata.promptTokenCount ?? usage.input_tokens,
128899
+ input_tokens: Math.max(0, promptTotal - cached2),
128808
128900
  cache_creation_input_tokens: 0,
128809
- cache_read_input_tokens: 0,
128901
+ cache_read_input_tokens: cached2,
128810
128902
  output_tokens: chunk.usageMetadata.candidatesTokenCount ?? usage.output_tokens
128811
128903
  };
128812
128904
  }
@@ -128919,6 +129011,9 @@ function createAntigravityRelay(params) {
128919
129011
  return { pushChunk, finish };
128920
129012
  }
128921
129013
 
129014
+ // src/antigravity/route.ts
129015
+ init_cloudUpstream();
129016
+
128922
129017
  // src/antigravity/localUpstream.ts
128923
129018
  var import_node_child_process6 = require("node:child_process");
128924
129019
  var import_node_net2 = __toESM(require("node:net"), 1);
@@ -132649,8 +132744,8 @@ init_realPorts();
132649
132744
  init_quotaRefresh();
132650
132745
 
132651
132746
  // src/usage/quotaHttp.ts
132652
- var realQuotaHttpGet = async (url2, headers, signal) => {
132653
- const response = await fetch(url2, { method: "GET", headers: { ...headers }, signal });
132747
+ var realQuotaHttpGet = async (url2, headers, signal, options) => {
132748
+ const response = await fetch(url2, { method: options?.method ?? "GET", headers: { ...headers }, ...options?.body === void 0 ? {} : { body: options.body }, signal });
132654
132749
  return { status: response.status, text: await response.text() };
132655
132750
  };
132656
132751
 
@@ -133154,6 +133249,382 @@ function registerFrontDoorCommand(program2, deps) {
133154
133249
  });
133155
133250
  }
133156
133251
 
133252
+ // src/statusline/commands.ts
133253
+ var import_node_child_process7 = require("node:child_process");
133254
+ init_commandDeps();
133255
+ init_realPorts();
133256
+ init_read();
133257
+
133258
+ // src/statusline/enrich.ts
133259
+ var FULL_PERCENT = 100;
133260
+ function identityOf(env) {
133261
+ const headers = env.ANTHROPIC_CUSTOM_HEADERS;
133262
+ if (headers !== void 0) {
133263
+ const match = /x-agent-shim-identity:\s*([A-Za-z0-9@._-]+)/i.exec(headers);
133264
+ if (match !== null) {
133265
+ return match[1];
133266
+ }
133267
+ }
133268
+ const configDir = env.CLAUDE_CONFIG_DIR;
133269
+ if (configDir !== void 0) {
133270
+ const slash = configDir.lastIndexOf("/");
133271
+ const name = slash === -1 ? "" : configDir.slice(slash + 1);
133272
+ const parent = slash === -1 ? "" : configDir.slice(0, slash);
133273
+ const parentSlash = parent.lastIndexOf("/");
133274
+ if (parentSlash !== -1 && parent.slice(parentSlash + 1) === "identities" && name !== "") {
133275
+ return name;
133276
+ }
133277
+ }
133278
+ return void 0;
133279
+ }
133280
+ function windowsOf(states) {
133281
+ let fiveHourUsed;
133282
+ let fiveHourResetAt;
133283
+ let sevenDayUsed;
133284
+ let sevenDayResetAt;
133285
+ for (const state of states) {
133286
+ const unified = state.rateLimit?.unified;
133287
+ if (unified === void 0) {
133288
+ continue;
133289
+ }
133290
+ const fiveWindow = unified.fiveHour === void 0 ? void 0 : unified.fiveHour.utilization;
133291
+ const five = typeof fiveWindow === "number" && Number.isFinite(fiveWindow) ? Math.round(Math.min(1, Math.max(0, fiveWindow)) * FULL_PERCENT) : void 0;
133292
+ if (five !== void 0 && (fiveHourUsed === void 0 || five > fiveHourUsed)) {
133293
+ fiveHourUsed = five;
133294
+ fiveHourResetAt = unified.fiveHour?.resetsAt;
133295
+ }
133296
+ const sevenWindow = unified.sevenDay === void 0 ? void 0 : unified.sevenDay.utilization;
133297
+ const seven = typeof sevenWindow === "number" && Number.isFinite(sevenWindow) ? Math.round(Math.min(1, Math.max(0, sevenWindow)) * FULL_PERCENT) : void 0;
133298
+ if (seven !== void 0 && (sevenDayUsed === void 0 || seven > sevenDayUsed)) {
133299
+ sevenDayUsed = seven;
133300
+ sevenDayResetAt = unified.sevenDay?.resetsAt;
133301
+ }
133302
+ }
133303
+ return { fiveHourUsed, fiveHourResetAt, sevenDayUsed, sevenDayResetAt };
133304
+ }
133305
+ function enrichStatuslinePayload(params) {
133306
+ const identity = identityOf(params.env);
133307
+ let summary = {
133308
+ identity,
133309
+ provider: params.env.AGENT_SHIM_PROVIDER === void 0 || params.env.AGENT_SHIM_PROVIDER === "" ? void 0 : params.env.AGENT_SHIM_PROVIDER,
133310
+ providerAccountEmail: void 0,
133311
+ fiveHourUsed: void 0,
133312
+ fiveHourResetAt: void 0,
133313
+ sevenDayUsed: void 0,
133314
+ sevenDayResetAt: void 0
133315
+ };
133316
+ if (params.snapshot !== void 0) {
133317
+ const scopedName = providerScopedState(params.snapshot, params.env.AGENT_SHIM_PROVIDER);
133318
+ const scopedState = scopedName === void 0 ? void 0 : params.snapshot.providers[scopedName];
133319
+ const states = scopedState === void 0 ? Object.values(params.snapshot.providers) : [scopedState];
133320
+ let email3;
133321
+ for (const state of states) {
133322
+ const candidate = state.quota?.account?.email;
133323
+ if (email3 === void 0 && typeof candidate === "string" && candidate !== "") {
133324
+ email3 = candidate;
133325
+ }
133326
+ }
133327
+ summary = { ...summary, ...windowsOf(states), providerAccountEmail: email3 };
133328
+ }
133329
+ if (typeof params.payload !== "object" || params.payload === null || Array.isArray(params.payload)) {
133330
+ return { payload: params.payload, summary };
133331
+ }
133332
+ const enriched = { agent_shim: summary };
133333
+ for (const [key, value2] of Object.entries(params.payload)) {
133334
+ enriched[key] = value2;
133335
+ }
133336
+ return { payload: enriched, summary };
133337
+ }
133338
+ function providerScopedState(snapshot, providerDisplayName) {
133339
+ if (providerDisplayName === void 0 || providerDisplayName === "") {
133340
+ return void 0;
133341
+ }
133342
+ const wanted = providerDisplayName.toLowerCase();
133343
+ for (const name of Object.keys(snapshot.providers)) {
133344
+ if (name.toLowerCase() === wanted) {
133345
+ return name;
133346
+ }
133347
+ }
133348
+ return void 0;
133349
+ }
133350
+
133351
+ // src/statusline/render.ts
133352
+ var BAR_WIDTH = 10;
133353
+ var SECONDS_PER_MINUTE2 = 60;
133354
+ var MINUTES_PER_HOUR3 = 60;
133355
+ var SECONDS_PER_DAY = 86400;
133356
+ var THOUSAND = 1e3;
133357
+ var MILLION = 1e6;
133358
+ var TEN = 10;
133359
+ var TWENTY = 20;
133360
+ var RESERVED_COLUMNS = 4;
133361
+ var SEPARATOR2 = " | ";
133362
+ var FULL_PERCENT2 = 100;
133363
+ var USED_RED_AT = 0.9;
133364
+ var USED_YELLOW_AT = 0.7;
133365
+ var ESCAPE_CHAR_CODE = 27;
133366
+ var ESCAPE = String.fromCharCode(ESCAPE_CHAR_CODE);
133367
+ var RESET = `${ESCAPE}[0m`;
133368
+ var DIM = `${ESCAPE}[90m`;
133369
+ var GREEN = `${ESCAPE}[32m`;
133370
+ var YELLOW = `${ESCAPE}[33m`;
133371
+ var RED = `${ESCAPE}[31m`;
133372
+ var ANSI_REGEX = new RegExp(`${ESCAPE}\\[[0-9;]*[a-zA-Z]`, "g");
133373
+ function visibleLength(text2) {
133374
+ return text2.replace(ANSI_REGEX, "").length;
133375
+ }
133376
+ function colorize() {
133377
+ return process.env.NO_COLOR === void 0;
133378
+ }
133379
+ function statusColor(fraction, isUsedMetric) {
133380
+ if (!colorize()) {
133381
+ return "";
133382
+ }
133383
+ if (isUsedMetric) {
133384
+ if (fraction >= USED_RED_AT) {
133385
+ return RED;
133386
+ }
133387
+ return fraction >= USED_YELLOW_AT ? YELLOW : GREEN;
133388
+ }
133389
+ if (fraction <= 1 - USED_RED_AT) {
133390
+ return RED;
133391
+ }
133392
+ return fraction <= 1 - USED_YELLOW_AT ? YELLOW : GREEN;
133393
+ }
133394
+ function formatTokens(num) {
133395
+ if (num >= MILLION) {
133396
+ const val = num / MILLION;
133397
+ return val % 1 === 0 ? `${String(Math.round(val))}M` : `${val.toFixed(1)}M`;
133398
+ }
133399
+ if (num >= THOUSAND) {
133400
+ const val = num / THOUSAND;
133401
+ return val >= TEN ? `${String(Math.round(val))}k` : `${val.toFixed(1)}k`;
133402
+ }
133403
+ return String(Math.round(num));
133404
+ }
133405
+ function formatDuration(seconds) {
133406
+ if (seconds === void 0 || seconds <= 0) {
133407
+ return "available";
133408
+ }
133409
+ const days = Math.floor(seconds / SECONDS_PER_DAY);
133410
+ const hours = Math.floor(seconds % SECONDS_PER_DAY / (MINUTES_PER_HOUR3 * SECONDS_PER_MINUTE2));
133411
+ const minutes = Math.floor(seconds % (MINUTES_PER_HOUR3 * SECONDS_PER_MINUTE2) / SECONDS_PER_MINUTE2);
133412
+ if (days > 0) {
133413
+ return `${String(days)}d ${String(hours)}h`;
133414
+ }
133415
+ if (hours > 0) {
133416
+ return `${String(hours)}h ${String(minutes).padStart(2, "0")}m`;
133417
+ }
133418
+ return `${String(minutes)}m`;
133419
+ }
133420
+ function cacheShareText(view) {
133421
+ const hitRatio = view.cacheHitRatio;
133422
+ if (hitRatio !== void 0 && Number.isFinite(hitRatio)) {
133423
+ return ` (Cache: ${(Math.max(0, Math.min(1, hitRatio)) * FULL_PERCENT2).toFixed(0)}%)`;
133424
+ }
133425
+ const promptTotal = (view.cacheReadTokens ?? 0) + (view.freshInputTokens ?? 0);
133426
+ if (promptTotal > 0 && (view.cacheReadTokens ?? 0) > 0) {
133427
+ return ` (Cache: ${((view.cacheReadTokens ?? 0) / promptTotal * FULL_PERCENT2).toFixed(0)}%)`;
133428
+ }
133429
+ return "";
133430
+ }
133431
+ function secondsUntil(resetAt, nowMs) {
133432
+ if (resetAt === void 0) {
133433
+ return void 0;
133434
+ }
133435
+ const resetMs = Date.parse(resetAt);
133436
+ return Number.isNaN(resetMs) ? void 0 : Math.max(0, Math.round((resetMs - nowMs) / THOUSAND));
133437
+ }
133438
+ var Segment = class {
133439
+ constructor(kind, text2 = "", prefix = "", suffix = "", fraction = 0, isUsed = true) {
133440
+ this.kind = kind;
133441
+ this.text = text2;
133442
+ this.prefix = prefix;
133443
+ this.suffix = suffix;
133444
+ this.fraction = fraction;
133445
+ this.isUsed = isUsed;
133446
+ }
133447
+ kind;
133448
+ text;
133449
+ prefix;
133450
+ suffix;
133451
+ fraction;
133452
+ isUsed;
133453
+ baseLength(baseBarWidth) {
133454
+ if (this.kind === "static") {
133455
+ return visibleLength(this.text);
133456
+ }
133457
+ return visibleLength(this.prefix) + baseBarWidth + 2 + visibleLength(this.suffix);
133458
+ }
133459
+ render(barWidth) {
133460
+ if (this.kind === "static") {
133461
+ return this.text;
133462
+ }
133463
+ const clamped = Math.max(0, Math.min(1, this.fraction));
133464
+ const filled = Math.round(clamped * barWidth);
133465
+ const color = statusColor(clamped, this.isUsed);
133466
+ const bar = color === "" ? `[${"\u2588".repeat(filled)}${"\u2591".repeat(barWidth - filled)}]` : `[${color}${"\u2588".repeat(filled)}${DIM}${"\u2591".repeat(barWidth - filled)}${RESET}]`;
133467
+ return `${this.prefix}${bar}${this.suffix}`;
133468
+ }
133469
+ };
133470
+ function renderLineWithExtra(segments, maxWidth, separator, baseBarWidth) {
133471
+ const separatorLength = visibleLength(separator);
133472
+ const bars = segments.filter((segment) => segment.kind === "bar");
133473
+ const lineBase = segments.reduce((total, segment) => total + segment.baseLength(baseBarWidth), 0) + separatorLength * (segments.length - 1);
133474
+ const extra = Math.max(0, maxWidth - lineBase);
133475
+ const extraById = /* @__PURE__ */ new Map();
133476
+ if (bars.length > 0 && extra > 0) {
133477
+ const perBar = Math.floor(extra / bars.length);
133478
+ const remainder = extra % bars.length;
133479
+ bars.forEach((bar, index) => {
133480
+ extraById.set(bar, perBar + (index < remainder ? 1 : 0));
133481
+ });
133482
+ }
133483
+ return segments.map((segment) => segment.render(baseBarWidth + (extraById.get(segment) ?? 0))).join(separator);
133484
+ }
133485
+ function layoutGrouped(group1, group2, maxWidth, fillMode, separator, baseBarWidth) {
133486
+ const separatorLength = visibleLength(separator);
133487
+ const allSegments = [...group1, ...group2];
133488
+ if (allSegments.length === 0) {
133489
+ return "";
133490
+ }
133491
+ const fillUnwrapped = fillMode === "always";
133492
+ const fillWrapped = fillMode === "always" || fillMode === "wrapped";
133493
+ const totalBase = allSegments.reduce((total, segment) => total + segment.baseLength(baseBarWidth), 0) + separatorLength * (allSegments.length - 1);
133494
+ if (totalBase <= maxWidth) {
133495
+ if (fillUnwrapped) {
133496
+ return renderLineWithExtra(allSegments, maxWidth, separator, baseBarWidth);
133497
+ }
133498
+ return allSegments.map((segment) => segment.render(baseBarWidth)).join(separator);
133499
+ }
133500
+ const lines = [group1, group2].map((group) => {
133501
+ if (group.length === 0) {
133502
+ return "";
133503
+ }
133504
+ const groupBase = group.reduce((total, segment) => total + segment.baseLength(baseBarWidth), 0) + separatorLength * (group.length - 1);
133505
+ if (groupBase <= maxWidth) {
133506
+ return fillWrapped ? renderLineWithExtra(group, maxWidth, separator, baseBarWidth) : group.map((segment) => segment.render(baseBarWidth)).join(separator);
133507
+ }
133508
+ return group.map((segment) => fillWrapped ? renderLineWithExtra([segment], maxWidth, separator, baseBarWidth) : segment.render(baseBarWidth)).join("\n");
133509
+ });
133510
+ return lines.filter((line) => line !== "").join("\n");
133511
+ }
133512
+ function renderStatuslineBlock(summary, view, terminalWidth, nowMs) {
133513
+ const header = [];
133514
+ if (view.modelDisplayName !== void 0 && view.modelDisplayName !== "") {
133515
+ header.push(new Segment("static", view.modelDisplayName));
133516
+ }
133517
+ const contextGroup = [];
133518
+ if (view.contextUsedPercentage !== void 0) {
133519
+ const fraction = Math.max(0, Math.min(1, view.contextUsedPercentage / FULL_PERCENT2));
133520
+ const color = statusColor(fraction, true);
133521
+ const percent2 = `${color}${view.contextUsedPercentage.toFixed(1)}%${RESET}`;
133522
+ const tokens = view.contextTotalTokens !== void 0 && view.contextWindowTokens !== void 0 ? `${formatTokens(view.contextTotalTokens)}/${formatTokens(view.contextWindowTokens)} ` : "";
133523
+ const cache = cacheShareText(view);
133524
+ contextGroup.push(new Segment("bar", "", `Ctx ${tokens}`, ` ${percent2}${cache}`, fraction, true));
133525
+ }
133526
+ const quotaGroup = [];
133527
+ if (summary.fiveHourUsed !== void 0) {
133528
+ const fraction = Math.max(0, Math.min(1, summary.fiveHourUsed / FULL_PERCENT2));
133529
+ const color = statusColor(fraction, true);
133530
+ quotaGroup.push(new Segment("bar", "", "5h ", ` ${color}${summary.fiveHourUsed.toFixed(1)}%${RESET} (${formatDuration(secondsUntil(summary.fiveHourResetAt, nowMs))})`, fraction, true));
133531
+ }
133532
+ if (summary.sevenDayUsed !== void 0) {
133533
+ const fraction = Math.max(0, Math.min(1, summary.sevenDayUsed / FULL_PERCENT2));
133534
+ const color = statusColor(fraction, true);
133535
+ quotaGroup.push(new Segment("bar", "", "Wk ", ` ${color}${summary.sevenDayUsed.toFixed(1)}%${RESET} (${formatDuration(secondsUntil(summary.sevenDayResetAt, nowMs))})`, fraction, true));
133536
+ }
133537
+ if (summary.provider !== void 0) {
133538
+ quotaGroup.push(new Segment("static", summary.providerAccountEmail === void 0 ? summary.provider : `${summary.provider} \xB7 ${summary.providerAccountEmail}`));
133539
+ }
133540
+ const width = Math.max(TWENTY, terminalWidth - RESERVED_COLUMNS);
133541
+ const lines = [];
133542
+ if (header.length > 0) {
133543
+ lines.push(header.map((segment) => segment.render(BAR_WIDTH)).join(SEPARATOR2));
133544
+ }
133545
+ const body = layoutGrouped(contextGroup, quotaGroup, width, "always", SEPARATOR2, BAR_WIDTH);
133546
+ if (body !== "") {
133547
+ lines.push(body);
133548
+ }
133549
+ return lines.join("\n");
133550
+ }
133551
+
133552
+ // src/statusline/commands.ts
133553
+ function payloadViewOf(payload) {
133554
+ const empty = { modelDisplayName: void 0, contextUsedPercentage: void 0, contextTotalTokens: void 0, contextWindowTokens: void 0, cacheHitRatio: void 0, cacheReadTokens: void 0, freshInputTokens: void 0 };
133555
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
133556
+ return empty;
133557
+ }
133558
+ const record2 = {};
133559
+ for (const [key, value2] of Object.entries(payload)) {
133560
+ record2[key] = value2;
133561
+ }
133562
+ const model = record2.model;
133563
+ const displayName = typeof model === "object" && model !== null && !Array.isArray(model) && "display_name" in model && typeof model.display_name === "string" ? model.display_name : void 0;
133564
+ const context = record2.context_window;
133565
+ const ctx = typeof context === "object" && context !== null && !Array.isArray(context) ? context : void 0;
133566
+ const used = ctx !== void 0 && "used_percentage" in ctx && typeof ctx.used_percentage === "number" ? ctx.used_percentage : void 0;
133567
+ const totalIn = ctx !== void 0 && "total_input_tokens" in ctx && typeof ctx.total_input_tokens === "number" ? ctx.total_input_tokens : void 0;
133568
+ const size = ctx !== void 0 && "context_window_size" in ctx && typeof ctx.context_window_size === "number" ? ctx.context_window_size : void 0;
133569
+ const current = ctx !== void 0 && "current_usage" in ctx && typeof ctx.current_usage === "object" && ctx.current_usage !== null && !Array.isArray(ctx.current_usage) ? ctx.current_usage : void 0;
133570
+ const cacheRead = current !== void 0 && "cache_read_input_tokens" in current && typeof current.cache_read_input_tokens === "number" ? current.cache_read_input_tokens : void 0;
133571
+ const fresh = current !== void 0 && "input_tokens" in current && typeof current.input_tokens === "number" ? current.input_tokens : void 0;
133572
+ const promptCache = record2.prompt_cache;
133573
+ const cache = typeof promptCache === "object" && promptCache !== null && !Array.isArray(promptCache) ? promptCache : void 0;
133574
+ const hitRatio = cache !== void 0 && "hit_ratio" in cache && typeof cache.hit_ratio === "number" ? cache.hit_ratio : void 0;
133575
+ return { modelDisplayName: displayName, contextUsedPercentage: used, contextTotalTokens: totalIn, contextWindowTokens: size, cacheHitRatio: hitRatio, cacheReadTokens: cacheRead, freshInputTokens: fresh };
133576
+ }
133577
+ async function readAllStdin() {
133578
+ return await new Promise((resolve2) => {
133579
+ const chunks = [];
133580
+ process.stdin.on("data", (chunk) => {
133581
+ chunks.push(chunk);
133582
+ });
133583
+ process.stdin.on("end", () => {
133584
+ resolve2(Buffer.concat(chunks).toString("utf8"));
133585
+ });
133586
+ process.stdin.resume();
133587
+ });
133588
+ }
133589
+ var DEFAULT_COLUMNS = 80;
133590
+ function registerStatuslineCommand(program2, deps) {
133591
+ withExamples(
133592
+ program2.command("statusline").description("Serve as a statusline entrypoint: read the client's stdin payload, add the identity's live provider, account and usage windows under an agent_shim key, then run the renderer named in AGENT_SHIM_STATUSLINE_CMD or print the built-in line.").action(async () => {
133593
+ const stdin2 = await readAllStdin();
133594
+ let payload;
133595
+ try {
133596
+ payload = JSON.parse(stdin2);
133597
+ } catch {
133598
+ payload = void 0;
133599
+ }
133600
+ const identity = identityOf(process.env);
133601
+ let snapshot;
133602
+ if (identity !== void 0) {
133603
+ try {
133604
+ snapshot = readUsageSnapshot(realFarmFs, deps.paths.usageSnapshotsDir, identity);
133605
+ } catch {
133606
+ snapshot = void 0;
133607
+ }
133608
+ }
133609
+ const { payload: enriched, summary } = enrichStatuslinePayload({ payload, env: process.env, snapshot });
133610
+ const renderer = process.env.AGENT_SHIM_STATUSLINE_CMD;
133611
+ if (renderer !== void 0 && renderer !== "") {
133612
+ const child = (0, import_node_child_process7.spawn)("/bin/sh", ["-c", renderer], { stdio: ["pipe", "inherit", "inherit"] });
133613
+ child.stdin.end(`${JSON.stringify(enriched)}
133614
+ `);
133615
+ child.on("close", (code) => {
133616
+ process.exit(code ?? 0);
133617
+ });
133618
+ return;
133619
+ }
133620
+ const view = payloadViewOf(payload);
133621
+ const columns = Number.parseInt(process.env.COLUMNS ?? "", 10);
133622
+ console.log(renderStatuslineBlock(summary, view, Number.isNaN(columns) ? DEFAULT_COLUMNS : columns, Date.now()));
133623
+ }),
133624
+ ["$ agent-shim statusline # a client's statusline setting names this; it renders or delegates"]
133625
+ );
133626
+ }
133627
+
133157
133628
  // node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_supports-color@7.2.0_zod@4.6.5/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
133158
133629
  var import_node_process6 = __toESM(require("node:process"), 1);
133159
133630
 
@@ -143232,7 +143703,7 @@ function registerCompletionCommand(program2) {
143232
143703
  }
143233
143704
 
143234
143705
  // src/credentialCommand.ts
143235
- var import_node_child_process7 = require("node:child_process");
143706
+ var import_node_child_process8 = require("node:child_process");
143236
143707
  init_commandDeps();
143237
143708
  init_cliError();
143238
143709
  init_credential();
@@ -143292,7 +143763,7 @@ function realCommandPorts(deps) {
143292
143763
  cache: createRealCredentialCache(deps.paths.root),
143293
143764
  platform: process.platform,
143294
143765
  now: () => Date.now(),
143295
- ssh: (host, remoteCommand, input2) => (0, import_node_child_process7.spawnSync)("ssh", ["--", host, remoteCommand], { input: input2, stdio: ["pipe", "inherit", "inherit"] }).status
143766
+ ssh: (host, remoteCommand, input2) => (0, import_node_child_process8.spawnSync)("ssh", ["--", host, remoteCommand], { input: input2, stdio: ["pipe", "inherit", "inherit"] }).status
143296
143767
  };
143297
143768
  }
143298
143769
  var REMOTE_ROOT_SCRIPT = 'root="${AGENT_SHIM_HOME:-${CLAUDE_USE_HOME:-}}"; if [ -z "$root" ]; then if [ ! -d "$HOME/.agent-shim" ] && [ -d "$HOME/.claude-use" ]; then root="$HOME/.claude-use"; else root="$HOME/.agent-shim"; fi; fi';
@@ -143429,7 +143900,7 @@ function registerDoctorCommand(program2, deps) {
143429
143900
  var import_node_fs22 = __toESM(require("node:fs"), 1);
143430
143901
  var import_node_http4 = __toESM(require("node:http"), 1);
143431
143902
  var import_node_path54 = __toESM(require("node:path"), 1);
143432
- var import_node_child_process8 = require("node:child_process");
143903
+ var import_node_child_process9 = require("node:child_process");
143433
143904
  init_commandDeps();
143434
143905
  init_realFrontDoorPort();
143435
143906
  init_trust();
@@ -143613,7 +144084,7 @@ async function readyOverSocket(socketPath) {
143613
144084
  }
143614
144085
  var HEADROOM_TOOL_NAME = "headroom-ai";
143615
144086
  function readInstalledHeadroomCommit() {
143616
- const toolDir = (0, import_node_child_process8.spawnSync)("uv", ["tool", "dir"], { encoding: "utf8" });
144087
+ const toolDir = (0, import_node_child_process9.spawnSync)("uv", ["tool", "dir"], { encoding: "utf8" });
143617
144088
  if (toolDir.status !== 0) {
143618
144089
  return void 0;
143619
144090
  }
@@ -143657,7 +144128,7 @@ function realSupervisorPorts(paths) {
143657
144128
  }
143658
144129
  const logFd = import_node_fs22.default.openSync(paths.headroomLogPath, "a");
143659
144130
  try {
143660
- const child = (0, import_node_child_process8.spawn)("headroom", headroomProxyArgs(socketPath, allowlistFile, settings2), {
144131
+ const child = (0, import_node_child_process9.spawn)("headroom", headroomProxyArgs(socketPath, allowlistFile, settings2), {
143661
144132
  detached: true,
143662
144133
  stdio: ["ignore", logFd, logFd],
143663
144134
  env: headroomSpawnEnv(process.env, settings2, trust?.path)
@@ -143697,7 +144168,7 @@ function realSupervisorPorts(paths) {
143697
144168
  },
143698
144169
  ready: readyOverSocket,
143699
144170
  install: (spec) => {
143700
- const result = (0, import_node_child_process8.spawnSync)("uv", ["tool", "install", spec], { encoding: "utf8", timeout: HEADROOM_INSTALL_TIMEOUT_MS });
144171
+ const result = (0, import_node_child_process9.spawnSync)("uv", ["tool", "install", spec], { encoding: "utf8", timeout: HEADROOM_INSTALL_TIMEOUT_MS });
143701
144172
  if (result.error !== void 0) {
143702
144173
  const timedOut = "code" in result.error && result.error.code === "ETIMEDOUT";
143703
144174
  return {
@@ -143714,7 +144185,7 @@ function realSupervisorPorts(paths) {
143714
144185
  return result.status === 0 ? { ok: true } : { ok: false, error: `uv tool install exited ${String(result.status)}` };
143715
144186
  },
143716
144187
  headroomVersion: () => {
143717
- const result = (0, import_node_child_process8.spawnSync)("headroom", ["--version"], { encoding: "utf8" });
144188
+ const result = (0, import_node_child_process9.spawnSync)("headroom", ["--version"], { encoding: "utf8" });
143718
144189
  return result.status === 0 ? result.stdout.trim() : void 0;
143719
144190
  },
143720
144191
  installedCommit: readInstalledHeadroomCommit,
@@ -144803,6 +145274,7 @@ function buildProgram(deps) {
144803
145274
  registerConfigureCommand(program2, deps);
144804
145275
  registerDoctorCommand(program2, deps);
144805
145276
  registerShimCommand(program2, deps);
145277
+ registerStatuslineCommand(program2, deps);
144806
145278
  registerHeadroomCommand(program2, deps);
144807
145279
  registerCodexCommand(program2, deps);
144808
145280
  registerFrontDoorCommand(program2, deps);