@moxt-ai/mobius 0.0.455 → 0.0.456
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/{chunk-TPFOWHSZ.js → chunk-GUE7ZQI6.js} +2433 -201
- package/dist/{chunk-TPFOWHSZ.js.map → chunk-GUE7ZQI6.js.map} +4 -4
- package/dist/{chunk-ZNK44CJT.js → chunk-H3JQ3BX5.js} +2 -2
- package/dist/{chunk-ZNK44CJT.js.map → chunk-H3JQ3BX5.js.map} +1 -1
- package/dist/{cli-LYAYRPGJ.js → cli-E4GLG6NB.js} +3 -3
- package/dist/cli.js +2 -2
- package/dist/engine/acp/adapter/antigravity/adapter.d.ts +53 -0
- package/dist/engine/acp/adapter/antigravity/adapter.d.ts.map +1 -1
- package/dist/engine/acp/adapter/antigravity/adapter.js +7 -0
- package/dist/engine/acp/adapter/antigravity/adapter.js.map +1 -1
- package/dist/engine/acp/adapter/claude/adapter.d.ts +53 -0
- package/dist/engine/acp/adapter/claude/adapter.d.ts.map +1 -1
- package/dist/engine/acp/adapter/claude/adapter.js +8 -1
- package/dist/engine/acp/adapter/claude/adapter.js.map +1 -1
- package/dist/engine/acp/adapter/claude/agent-connection.d.ts.map +1 -1
- package/dist/engine/acp/adapter/claude/agent-connection.js +1 -0
- package/dist/engine/acp/adapter/claude/agent-connection.js.map +1 -1
- package/dist/engine/acp/adapter/codex/adapter.d.ts +53 -0
- package/dist/engine/acp/adapter/codex/adapter.d.ts.map +1 -1
- package/dist/engine/acp/adapter/codex/adapter.js +8 -1
- package/dist/engine/acp/adapter/codex/adapter.js.map +1 -1
- package/dist/engine/acp/adapter/codex/agent-connection.d.ts.map +1 -1
- package/dist/engine/acp/adapter/codex/agent-connection.js +1 -0
- package/dist/engine/acp/adapter/codex/agent-connection.js.map +1 -1
- package/dist/engine/acp/adapter/execution-connections.d.ts +2 -1
- package/dist/engine/acp/adapter/execution-connections.d.ts.map +1 -1
- package/dist/engine/acp/adapter/execution-connections.js +6 -1
- package/dist/engine/acp/adapter/execution-connections.js.map +1 -1
- package/dist/engine/acp/adapter/pi/adapter.d.ts +10 -0
- package/dist/engine/acp/adapter/pi/adapter.d.ts.map +1 -1
- package/dist/engine/acp/adapter/pi/adapter.js +9 -0
- package/dist/engine/acp/adapter/pi/adapter.js.map +1 -1
- package/dist/engine/acp/adapter/session-events.d.ts +2 -1
- package/dist/engine/acp/adapter/session-events.d.ts.map +1 -1
- package/dist/engine/acp/adapter/session-events.js +5 -0
- package/dist/engine/acp/adapter/session-events.js.map +1 -1
- package/dist/engine/acp/agent/in-process-endpoint.d.ts +12 -1
- package/dist/engine/acp/agent/in-process-endpoint.d.ts.map +1 -1
- package/dist/engine/acp/agent/in-process-endpoint.js.map +1 -1
- package/dist/engine/acp/connection/agent-connection.d.ts +2 -1
- package/dist/engine/acp/connection/agent-connection.d.ts.map +1 -1
- package/dist/engine/acp/harness/antigravity/usage-quota.d.ts +13 -0
- package/dist/engine/acp/harness/antigravity/usage-quota.d.ts.map +1 -0
- package/dist/engine/acp/harness/antigravity/usage-quota.js +457 -0
- package/dist/engine/acp/harness/antigravity/usage-quota.js.map +1 -0
- package/dist/engine/acp/harness/claude/endpoint.d.ts.map +1 -1
- package/dist/engine/acp/harness/claude/endpoint.js +9 -0
- package/dist/engine/acp/harness/claude/endpoint.js.map +1 -1
- package/dist/engine/acp/harness/claude/usage-quota.d.ts +30 -0
- package/dist/engine/acp/harness/claude/usage-quota.d.ts.map +1 -0
- package/dist/engine/acp/harness/claude/usage-quota.js +900 -0
- package/dist/engine/acp/harness/claude/usage-quota.js.map +1 -0
- package/dist/engine/acp/harness/codex/agent.d.ts.map +1 -1
- package/dist/engine/acp/harness/codex/agent.js +9 -0
- package/dist/engine/acp/harness/codex/agent.js.map +1 -1
- package/dist/engine/acp/harness/codex/usage-quota.d.ts +16 -0
- package/dist/engine/acp/harness/codex/usage-quota.d.ts.map +1 -0
- package/dist/engine/acp/harness/codex/usage-quota.js +360 -0
- package/dist/engine/acp/harness/codex/usage-quota.js.map +1 -0
- package/dist/engine/acp/native-history/preview-contract.d.ts +9 -1
- package/dist/engine/acp/native-history/preview-contract.d.ts.map +1 -1
- package/dist/engine/agent/runtime-agents.d.ts +1 -1
- package/dist/engine/agent/runtime-agents.d.ts.map +1 -1
- package/dist/engine/agent/runtime-agents.js +6 -2
- package/dist/engine/agent/runtime-agents.js.map +1 -1
- package/dist/engine/runtime/command/context.d.ts +2 -0
- package/dist/engine/runtime/command/context.d.ts.map +1 -1
- package/dist/engine/runtime/command/registry/index.d.ts.map +1 -1
- package/dist/engine/runtime/command/registry/index.js +2 -1
- package/dist/engine/runtime/command/registry/index.js.map +1 -1
- package/dist/engine/runtime/command/registry/runtime.d.ts +1 -0
- package/dist/engine/runtime/command/registry/runtime.d.ts.map +1 -1
- package/dist/engine/runtime/command/registry/runtime.js +52 -1
- package/dist/engine/runtime/command/registry/runtime.js.map +1 -1
- package/dist/engine/runtime/relay/run-relay-connection.d.ts +3 -1
- package/dist/engine/runtime/relay/run-relay-connection.d.ts.map +1 -1
- package/dist/engine/runtime/relay/run-relay-connection.js +2 -1
- package/dist/engine/runtime/relay/run-relay-connection.js.map +1 -1
- package/dist/engine/runtime/run.d.ts.map +1 -1
- package/dist/engine/runtime/run.js +9 -1
- package/dist/engine/runtime/run.js.map +1 -1
- package/dist/engine/session/usage/runtime-usage-service.d.ts +29 -0
- package/dist/engine/session/usage/runtime-usage-service.d.ts.map +1 -0
- package/dist/engine/session/usage/runtime-usage-service.js +248 -0
- package/dist/engine/session/usage/runtime-usage-service.js.map +1 -0
- package/dist/engine/storage/antigravity-usage-credentials.d.ts +26 -0
- package/dist/engine/storage/antigravity-usage-credentials.d.ts.map +1 -0
- package/dist/engine/storage/antigravity-usage-credentials.js +147 -0
- package/dist/engine/storage/antigravity-usage-credentials.js.map +1 -0
- package/dist/engine.js +2 -2
- package/package.json +2 -2
- /package/dist/{cli-LYAYRPGJ.js.map → cli-E4GLG6NB.js.map} +0 -0
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
__export,
|
|
4
4
|
__using,
|
|
5
5
|
package_default
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-H3JQ3BX5.js";
|
|
7
7
|
|
|
8
8
|
// src/engine/runtime/relay/runtime-revocation.ts
|
|
9
9
|
var runtimeRevocationCloseCode = 1008;
|
|
@@ -24,7 +24,7 @@ function isRuntimeRelayRevocation(closeCode, closeReason) {
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
// src/engine/runtime/engine.ts
|
|
27
|
-
import { resolve as
|
|
27
|
+
import { resolve as resolve20 } from "node:path";
|
|
28
28
|
|
|
29
29
|
// src/engine/session/manager/operation-drain.ts
|
|
30
30
|
var RuntimeOperations = class {
|
|
@@ -5175,7 +5175,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
|
|
|
5175
5175
|
var NONE = 0;
|
|
5176
5176
|
var ASSUMED = 1;
|
|
5177
5177
|
var PROVEN = 2;
|
|
5178
|
-
function isRecursive(inst, stack,
|
|
5178
|
+
function isRecursive(inst, stack, resolve21) {
|
|
5179
5179
|
const cached2 = recursive.get(inst);
|
|
5180
5180
|
if (cached2 !== void 0)
|
|
5181
5181
|
return cached2 ? PROVEN : NONE;
|
|
@@ -5185,7 +5185,7 @@ function isRecursive(inst, stack, resolve20) {
|
|
|
5185
5185
|
let result = NONE;
|
|
5186
5186
|
const check2 = (child) => {
|
|
5187
5187
|
if (result !== PROVEN && child?._zod) {
|
|
5188
|
-
const answer = isRecursive(child, stack,
|
|
5188
|
+
const answer = isRecursive(child, stack, resolve21);
|
|
5189
5189
|
if (answer > result)
|
|
5190
5190
|
result = answer;
|
|
5191
5191
|
}
|
|
@@ -5196,7 +5196,7 @@ function isRecursive(inst, stack, resolve20) {
|
|
|
5196
5196
|
const desc2 = Object.getOwnPropertyDescriptor(sh, key);
|
|
5197
5197
|
if (spread && !desc2.enumerable)
|
|
5198
5198
|
continue;
|
|
5199
|
-
const child = desc2.get ? ASSUMED : desc2.value?._zod ? isRecursive(desc2.value, stack,
|
|
5199
|
+
const child = desc2.get ? ASSUMED : desc2.value?._zod ? isRecursive(desc2.value, stack, resolve21) : NONE;
|
|
5200
5200
|
if (child > answer)
|
|
5201
5201
|
answer = child;
|
|
5202
5202
|
}
|
|
@@ -5260,7 +5260,7 @@ function isRecursive(inst, stack, resolve20) {
|
|
|
5260
5260
|
break;
|
|
5261
5261
|
// `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
|
|
5262
5262
|
case "lazy": {
|
|
5263
|
-
const inner = def._cachedInner ?? (
|
|
5263
|
+
const inner = def._cachedInner ?? (resolve21 ? inst._zod.innerType : void 0);
|
|
5264
5264
|
merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
|
|
5265
5265
|
break;
|
|
5266
5266
|
}
|
|
@@ -19996,12 +19996,14 @@ function decodeRuntimePongEvent(encoded) {
|
|
|
19996
19996
|
assertKind(value, RUNTIME_PONG_KIND);
|
|
19997
19997
|
const scopedFileRead = Reflect.get(value, "scopedFileRead");
|
|
19998
19998
|
const promptSuggestions = Reflect.get(value, "promptSuggestions");
|
|
19999
|
+
const usageQuota = Reflect.get(value, "usageQuota");
|
|
19999
20000
|
return {
|
|
20000
20001
|
kind: RUNTIME_PONG_KIND,
|
|
20001
20002
|
...Reflect.get(value, "sessionTitleGeneration") === true ? { sessionTitleGeneration: true } : {},
|
|
20002
20003
|
...typeof promptSuggestions === "boolean" ? { promptSuggestions } : {},
|
|
20003
20004
|
requestId: readIdentifier(value, "requestId"),
|
|
20004
|
-
...typeof scopedFileRead === "boolean" ? { scopedFileRead } : {}
|
|
20005
|
+
...typeof scopedFileRead === "boolean" ? { scopedFileRead } : {},
|
|
20006
|
+
...typeof usageQuota === "boolean" ? { usageQuota } : {}
|
|
20005
20007
|
};
|
|
20006
20008
|
}
|
|
20007
20009
|
function encodeRuntimeLivenessReadyEvent(message) {
|
|
@@ -20052,6 +20054,96 @@ var runtimeUpgradeResultSchema = external_exports.strictObject({
|
|
|
20052
20054
|
var decodeRuntimeUpgradeResult = (raw) => runtimeUpgradeResultSchema.parse(JSON.parse(raw));
|
|
20053
20055
|
var encodeRuntimeUpgradeResult = (value) => JSON.stringify(runtimeUpgradeResultSchema.parse(value));
|
|
20054
20056
|
|
|
20057
|
+
// ../mobius-sdk/src/protocol/runtime/usage.ts
|
|
20058
|
+
var RUNTIME_USAGE_READ_KIND = "runtime.usage.read";
|
|
20059
|
+
var RUNTIME_USAGE_RESULT_KIND = "runtime.usage.result";
|
|
20060
|
+
var isoDateTime = external_exports.string().datetime({ offset: true });
|
|
20061
|
+
var usageQuotaWindowKindSchema = external_exports.enum(["session", "weekly", "monthly", "other"]);
|
|
20062
|
+
var usageQuotaWindowSchema = external_exports.object({
|
|
20063
|
+
id: external_exports.string().min(1).max(128),
|
|
20064
|
+
kind: usageQuotaWindowKindSchema,
|
|
20065
|
+
label: external_exports.string().min(1).max(128),
|
|
20066
|
+
group: external_exports.string().min(1).max(64).optional(),
|
|
20067
|
+
usedPercent: external_exports.number().min(0).max(100),
|
|
20068
|
+
remainingPercent: external_exports.number().min(0).max(100),
|
|
20069
|
+
resetsAt: isoDateTime.optional(),
|
|
20070
|
+
windowDurationMins: external_exports.number().int().positive().optional(),
|
|
20071
|
+
isExtra: external_exports.boolean().optional()
|
|
20072
|
+
}).readonly();
|
|
20073
|
+
var usageQuotaCreditsSchema = external_exports.object({
|
|
20074
|
+
unlimited: external_exports.boolean(),
|
|
20075
|
+
balanceDisplay: external_exports.string().min(1).max(64).optional(),
|
|
20076
|
+
zeroSpendCap: external_exports.boolean().optional()
|
|
20077
|
+
}).readonly();
|
|
20078
|
+
var usageQuotaResetCreditsSchema = external_exports.object({
|
|
20079
|
+
availableCount: external_exports.number().int().nonnegative(),
|
|
20080
|
+
nextExpiresAt: isoDateTime.optional()
|
|
20081
|
+
}).readonly();
|
|
20082
|
+
var usageQuotaStaleInfoSchema = external_exports.object({
|
|
20083
|
+
errorCode: external_exports.string().min(1).max(64),
|
|
20084
|
+
errorMessage: external_exports.string().min(1).max(256),
|
|
20085
|
+
failedAt: isoDateTime
|
|
20086
|
+
}).readonly();
|
|
20087
|
+
var usageQuotaUnsupportedReasonSchema = external_exports.enum(["api_key", "no_subscription_quota", "agent_unsupported"]);
|
|
20088
|
+
var agentUsageQuotaSchema = external_exports.discriminatedUnion("status", [
|
|
20089
|
+
external_exports.object({
|
|
20090
|
+
agentId: identifierStringSchema,
|
|
20091
|
+
status: external_exports.literal("available"),
|
|
20092
|
+
checkedAt: isoDateTime,
|
|
20093
|
+
plan: external_exports.string().min(1).max(64).optional(),
|
|
20094
|
+
accountLabel: external_exports.string().min(1).max(128).optional(),
|
|
20095
|
+
windows: external_exports.array(usageQuotaWindowSchema).max(32).readonly(),
|
|
20096
|
+
credits: usageQuotaCreditsSchema.optional(),
|
|
20097
|
+
resetCredits: usageQuotaResetCreditsSchema.optional(),
|
|
20098
|
+
stale: usageQuotaStaleInfoSchema.optional()
|
|
20099
|
+
}).readonly(),
|
|
20100
|
+
external_exports.object({
|
|
20101
|
+
agentId: identifierStringSchema,
|
|
20102
|
+
status: external_exports.literal("unauthenticated"),
|
|
20103
|
+
checkedAt: isoDateTime,
|
|
20104
|
+
message: external_exports.string().min(1).max(256).optional()
|
|
20105
|
+
}).readonly(),
|
|
20106
|
+
external_exports.object({
|
|
20107
|
+
agentId: identifierStringSchema,
|
|
20108
|
+
status: external_exports.literal("unsupported"),
|
|
20109
|
+
checkedAt: isoDateTime,
|
|
20110
|
+
reason: usageQuotaUnsupportedReasonSchema,
|
|
20111
|
+
message: external_exports.string().min(1).max(256).optional()
|
|
20112
|
+
}).readonly(),
|
|
20113
|
+
external_exports.object({
|
|
20114
|
+
agentId: identifierStringSchema,
|
|
20115
|
+
status: external_exports.literal("unavailable"),
|
|
20116
|
+
checkedAt: isoDateTime,
|
|
20117
|
+
errorCode: external_exports.string().min(1).max(64),
|
|
20118
|
+
errorMessage: external_exports.string().min(1).max(256)
|
|
20119
|
+
}).readonly()
|
|
20120
|
+
]);
|
|
20121
|
+
var runtimeUsageReadRequestSchema = external_exports.object({
|
|
20122
|
+
kind: external_exports.literal(RUNTIME_USAGE_READ_KIND),
|
|
20123
|
+
requestId: identifierStringSchema,
|
|
20124
|
+
forceRefresh: external_exports.boolean().optional(),
|
|
20125
|
+
agentIds: external_exports.array(identifierStringSchema).max(16).readonly().optional()
|
|
20126
|
+
}).readonly();
|
|
20127
|
+
var runtimeUsageResultSchema = external_exports.discriminatedUnion("state", [
|
|
20128
|
+
external_exports.object({
|
|
20129
|
+
kind: external_exports.literal(RUNTIME_USAGE_RESULT_KIND),
|
|
20130
|
+
requestId: identifierStringSchema,
|
|
20131
|
+
state: external_exports.literal("supported"),
|
|
20132
|
+
collectedAt: isoDateTime,
|
|
20133
|
+
agents: external_exports.array(agentUsageQuotaSchema).max(32).readonly()
|
|
20134
|
+
}).readonly(),
|
|
20135
|
+
external_exports.object({
|
|
20136
|
+
kind: external_exports.literal(RUNTIME_USAGE_RESULT_KIND),
|
|
20137
|
+
requestId: identifierStringSchema,
|
|
20138
|
+
state: external_exports.literal("unsupported"),
|
|
20139
|
+
reason: external_exports.literal("runtime_upgrade_required")
|
|
20140
|
+
}).readonly()
|
|
20141
|
+
]).refine((value) => JSON.stringify(value).length <= 65536, "Usage report exceeds the payload limit");
|
|
20142
|
+
var decodeRuntimeUsageReadRequest = (raw) => runtimeUsageReadRequestSchema.parse(JSON.parse(raw));
|
|
20143
|
+
var decodeRuntimeUsageResult = (raw) => runtimeUsageResultSchema.parse(JSON.parse(raw));
|
|
20144
|
+
var encodeRuntimeUsageReadRequest = (value) => JSON.stringify(runtimeUsageReadRequestSchema.parse(value));
|
|
20145
|
+
var encodeRuntimeUsageResult = (value) => JSON.stringify(runtimeUsageResultSchema.parse(value));
|
|
20146
|
+
|
|
20055
20147
|
// ../mobius-sdk/src/protocol/session/agent/catalog.ts
|
|
20056
20148
|
var AGENT_CATALOG_DISCOVER_KIND = "agent.catalog.discover";
|
|
20057
20149
|
var AGENT_CATALOG_DISCOVERED_KIND = "agent.catalog.discovered";
|
|
@@ -21990,6 +22082,11 @@ var serviceToDaemonSignatures = {
|
|
|
21990
22082
|
encodeRuntimeDiagnosticsRequest,
|
|
21991
22083
|
decodeRuntimeDiagnosticsRequest
|
|
21992
22084
|
),
|
|
22085
|
+
[RUNTIME_USAGE_READ_KIND]: defineMessageSignature(
|
|
22086
|
+
RUNTIME_USAGE_READ_KIND,
|
|
22087
|
+
encodeRuntimeUsageReadRequest,
|
|
22088
|
+
decodeRuntimeUsageReadRequest
|
|
22089
|
+
),
|
|
21993
22090
|
[RUNTIME_PING_KIND]: defineMessageSignature(RUNTIME_PING_KIND, encodeRuntimePingCommand, decodeRuntimePingCommand),
|
|
21994
22091
|
[SESSION_CANCEL_BEFORE_START_KIND]: defineMessageSignature(
|
|
21995
22092
|
SESSION_CANCEL_BEFORE_START_KIND,
|
|
@@ -22180,6 +22277,11 @@ var daemonToServiceSignatures = {
|
|
|
22180
22277
|
encodeRuntimeDiagnosticsResult,
|
|
22181
22278
|
decodeRuntimeDiagnosticsResult
|
|
22182
22279
|
),
|
|
22280
|
+
[RUNTIME_USAGE_RESULT_KIND]: defineMessageSignature(
|
|
22281
|
+
RUNTIME_USAGE_RESULT_KIND,
|
|
22282
|
+
encodeRuntimeUsageResult,
|
|
22283
|
+
decodeRuntimeUsageResult
|
|
22284
|
+
),
|
|
22183
22285
|
[RUNTIME_PONG_KIND]: defineMessageSignature(RUNTIME_PONG_KIND, encodeRuntimePongEvent, decodeRuntimePongEvent),
|
|
22184
22286
|
[SESSION_EVENT_KIND]: defineMessageSignature(
|
|
22185
22287
|
SESSION_EVENT_KIND,
|
|
@@ -23208,8 +23310,8 @@ async function readOrCreateInstallationId(engineDataDir, signal) {
|
|
|
23208
23310
|
|
|
23209
23311
|
// src/engine/runtime/pairing.ts
|
|
23210
23312
|
import { hostname as hostname3 } from "node:os";
|
|
23211
|
-
import { basename as basename7, resolve as
|
|
23212
|
-
import { fetch as
|
|
23313
|
+
import { basename as basename7, resolve as resolve17 } from "node:path";
|
|
23314
|
+
import { fetch as fetch4 } from "undici";
|
|
23213
23315
|
|
|
23214
23316
|
// ../../node_modules/.pnpm/@agentclientprotocol+sdk@1.4.0_zod@4.6.7/node_modules/@agentclientprotocol/sdk/dist/schema/index.js
|
|
23215
23317
|
var AGENT_METHODS = {
|
|
@@ -25370,11 +25472,11 @@ var Connection = class {
|
|
|
25370
25472
|
const id = this.nextRequestId++;
|
|
25371
25473
|
let cancel = () => {
|
|
25372
25474
|
};
|
|
25373
|
-
const response = new Promise((
|
|
25475
|
+
const response = new Promise((resolve21, reject2) => {
|
|
25374
25476
|
const pendingResponse = {
|
|
25375
25477
|
resolve: (value) => {
|
|
25376
25478
|
try {
|
|
25377
|
-
|
|
25479
|
+
resolve21(mapResponse ? mapResponse(value) : value);
|
|
25378
25480
|
} catch (error62) {
|
|
25379
25481
|
reject2(error62);
|
|
25380
25482
|
}
|
|
@@ -25431,8 +25533,8 @@ var Connection = class {
|
|
|
25431
25533
|
this.stream = stream;
|
|
25432
25534
|
this.staticHandlers = handlers;
|
|
25433
25535
|
this.allowBatches = options?.allowBatches ?? true;
|
|
25434
|
-
this.closedPromise = new Promise((
|
|
25435
|
-
this.abortController.signal.addEventListener("abort", () =>
|
|
25536
|
+
this.closedPromise = new Promise((resolve21) => {
|
|
25537
|
+
this.abortController.signal.addEventListener("abort", () => resolve21());
|
|
25436
25538
|
});
|
|
25437
25539
|
void this.receive();
|
|
25438
25540
|
}
|
|
@@ -26354,8 +26456,8 @@ var AsyncQueue = class {
|
|
|
26354
26456
|
if (this.failed) {
|
|
26355
26457
|
return Promise.reject(this.failure);
|
|
26356
26458
|
}
|
|
26357
|
-
return new Promise((
|
|
26358
|
-
this.waiters.push({ resolve:
|
|
26459
|
+
return new Promise((resolve21, reject2) => {
|
|
26460
|
+
this.waiters.push({ resolve: resolve21, reject: reject2 });
|
|
26359
26461
|
});
|
|
26360
26462
|
}
|
|
26361
26463
|
};
|
|
@@ -27966,7 +28068,7 @@ function createWritableAcpStream(output2) {
|
|
|
27966
28068
|
if (outputFailure !== void 0) {
|
|
27967
28069
|
return Promise.reject(outputFailure);
|
|
27968
28070
|
}
|
|
27969
|
-
return new Promise((
|
|
28071
|
+
return new Promise((resolve21, reject2) => {
|
|
27970
28072
|
pendingWriteFailures.add(reject2);
|
|
27971
28073
|
output2.write(chunk, (error62) => {
|
|
27972
28074
|
pendingWriteFailures.delete(reject2);
|
|
@@ -27979,7 +28081,7 @@ function createWritableAcpStream(output2) {
|
|
|
27979
28081
|
reject2(outputFailure);
|
|
27980
28082
|
return;
|
|
27981
28083
|
}
|
|
27982
|
-
|
|
28084
|
+
resolve21();
|
|
27983
28085
|
});
|
|
27984
28086
|
});
|
|
27985
28087
|
},
|
|
@@ -66768,11 +66870,11 @@ var Pushable = class {
|
|
|
66768
66870
|
done = false;
|
|
66769
66871
|
push(item) {
|
|
66770
66872
|
if (this.resolvers.length > 0) {
|
|
66771
|
-
const
|
|
66772
|
-
if (
|
|
66873
|
+
const resolve21 = this.resolvers.shift();
|
|
66874
|
+
if (resolve21 === void 0) {
|
|
66773
66875
|
return;
|
|
66774
66876
|
}
|
|
66775
|
-
|
|
66877
|
+
resolve21({ value: item, done: false });
|
|
66776
66878
|
} else {
|
|
66777
66879
|
this.queue.push(item);
|
|
66778
66880
|
}
|
|
@@ -66780,8 +66882,8 @@ var Pushable = class {
|
|
|
66780
66882
|
end() {
|
|
66781
66883
|
this.done = true;
|
|
66782
66884
|
while (this.resolvers.length > 0) {
|
|
66783
|
-
const
|
|
66784
|
-
|
|
66885
|
+
const resolve21 = this.resolvers.shift();
|
|
66886
|
+
resolve21?.({ done: true, value: void 0 });
|
|
66785
66887
|
}
|
|
66786
66888
|
}
|
|
66787
66889
|
[Symbol.asyncIterator]() {
|
|
@@ -66797,8 +66899,8 @@ var Pushable = class {
|
|
|
66797
66899
|
if (this.done) {
|
|
66798
66900
|
return Promise.resolve({ done: true, value: void 0 });
|
|
66799
66901
|
}
|
|
66800
|
-
return new Promise((
|
|
66801
|
-
this.resolvers.push(
|
|
66902
|
+
return new Promise((resolve21) => {
|
|
66903
|
+
this.resolvers.push(resolve21);
|
|
66802
66904
|
});
|
|
66803
66905
|
}
|
|
66804
66906
|
};
|
|
@@ -66816,14 +66918,14 @@ function unreachable(value, logger = console) {
|
|
|
66816
66918
|
async function withDeadline(signal, timeoutMilliseconds, operation) {
|
|
66817
66919
|
const deadline = AbortSignal.any([signal, AbortSignal.timeout(timeoutMilliseconds)]);
|
|
66818
66920
|
deadline.throwIfAborted();
|
|
66819
|
-
return await new Promise((
|
|
66921
|
+
return await new Promise((resolve21, reject2) => {
|
|
66820
66922
|
const settle2 = (callback) => {
|
|
66821
66923
|
deadline.removeEventListener("abort", onAbort);
|
|
66822
66924
|
callback();
|
|
66823
66925
|
};
|
|
66824
66926
|
const onAbort = () => settle2(() => reject2(deadline.reason));
|
|
66825
66927
|
deadline.addEventListener("abort", onAbort, { once: true });
|
|
66826
|
-
operation().then((value) => settle2(() =>
|
|
66928
|
+
operation().then((value) => settle2(() => resolve21(value)), (error62) => settle2(() => reject2(error62)));
|
|
66827
66929
|
});
|
|
66828
66930
|
}
|
|
66829
66931
|
var environmentChain = Promise.resolve();
|
|
@@ -69728,14 +69830,14 @@ function waitUnlessAborted(milliseconds, signal) {
|
|
|
69728
69830
|
if (signal.aborted) {
|
|
69729
69831
|
return Promise.resolve(false);
|
|
69730
69832
|
}
|
|
69731
|
-
return new Promise((
|
|
69833
|
+
return new Promise((resolve21) => {
|
|
69732
69834
|
const timer = setTimeout(() => {
|
|
69733
69835
|
signal.removeEventListener("abort", onAbort);
|
|
69734
|
-
|
|
69836
|
+
resolve21(true);
|
|
69735
69837
|
}, milliseconds);
|
|
69736
69838
|
const onAbort = () => {
|
|
69737
69839
|
clearTimeout(timer);
|
|
69738
|
-
|
|
69840
|
+
resolve21(false);
|
|
69739
69841
|
};
|
|
69740
69842
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
69741
69843
|
});
|
|
@@ -69996,7 +70098,7 @@ var ClientConnection = class {
|
|
|
69996
70098
|
}
|
|
69997
70099
|
};
|
|
69998
70100
|
function raceWithAbort(operation, signal) {
|
|
69999
|
-
return new Promise((
|
|
70101
|
+
return new Promise((resolve21, reject2) => {
|
|
70000
70102
|
const cleanup = () => signal.removeEventListener("abort", onAbort);
|
|
70001
70103
|
const onAbort = () => {
|
|
70002
70104
|
cleanup();
|
|
@@ -70008,7 +70110,7 @@ function raceWithAbort(operation, signal) {
|
|
|
70008
70110
|
}
|
|
70009
70111
|
void operation.then((value) => {
|
|
70010
70112
|
cleanup();
|
|
70011
|
-
|
|
70113
|
+
resolve21(value);
|
|
70012
70114
|
}, (error62) => {
|
|
70013
70115
|
cleanup();
|
|
70014
70116
|
reject2(error62);
|
|
@@ -70130,6 +70232,7 @@ var ClaudeAcpAgent = class {
|
|
|
70130
70232
|
spawnClaudeCodeProcess;
|
|
70131
70233
|
onBackgroundActivity;
|
|
70132
70234
|
onPromptSuggestion;
|
|
70235
|
+
onRateLimitEvent;
|
|
70133
70236
|
pendingSubmissions = /* @__PURE__ */ new Map();
|
|
70134
70237
|
sessions;
|
|
70135
70238
|
client;
|
|
@@ -70157,10 +70260,11 @@ var ClaudeAcpAgent = class {
|
|
|
70157
70260
|
* return "cancelled". See {@link DEFAULT_FORCE_CANCEL_GRACE_MS}. Mutable so
|
|
70158
70261
|
* tests can shrink it. */
|
|
70159
70262
|
forceCancelGraceMs = DEFAULT_FORCE_CANCEL_GRACE_MS;
|
|
70160
|
-
constructor(client2, logger, environment = process.env, spawnClaudeCodeProcess, onBackgroundActivity, onPromptSuggestion) {
|
|
70263
|
+
constructor(client2, logger, environment = process.env, spawnClaudeCodeProcess, onBackgroundActivity, onPromptSuggestion, onRateLimitEvent) {
|
|
70161
70264
|
this.spawnClaudeCodeProcess = spawnClaudeCodeProcess;
|
|
70162
70265
|
this.onBackgroundActivity = onBackgroundActivity;
|
|
70163
70266
|
this.onPromptSuggestion = onPromptSuggestion;
|
|
70267
|
+
this.onRateLimitEvent = onRateLimitEvent;
|
|
70164
70268
|
this.sessions = {};
|
|
70165
70269
|
this.client = client2;
|
|
70166
70270
|
this.logger = logger ?? console;
|
|
@@ -70623,12 +70727,12 @@ var ClaudeAcpAgent = class {
|
|
|
70623
70727
|
}
|
|
70624
70728
|
};
|
|
70625
70729
|
let completeTurn;
|
|
70626
|
-
turn.completion = new Promise((
|
|
70627
|
-
completeTurn =
|
|
70730
|
+
turn.completion = new Promise((resolve21) => {
|
|
70731
|
+
completeTurn = resolve21;
|
|
70628
70732
|
});
|
|
70629
|
-
const response = new Promise((
|
|
70733
|
+
const response = new Promise((resolve21, reject2) => {
|
|
70630
70734
|
turn.resolve = (result) => {
|
|
70631
|
-
|
|
70735
|
+
resolve21(result);
|
|
70632
70736
|
completeTurn();
|
|
70633
70737
|
};
|
|
70634
70738
|
turn.reject = (error62) => {
|
|
@@ -71205,8 +71309,8 @@ var ClaudeAcpAgent = class {
|
|
|
71205
71309
|
pendingNext ??= session.query.next().then((result) => ({ kind: "message", result }));
|
|
71206
71310
|
const nextMessage = pendingNext;
|
|
71207
71311
|
let onAbort;
|
|
71208
|
-
const abortRace = new Promise((
|
|
71209
|
-
onAbort = () =>
|
|
71312
|
+
const abortRace = new Promise((resolve21) => {
|
|
71313
|
+
onAbort = () => resolve21("abort");
|
|
71210
71314
|
cancelController.signal.addEventListener("abort", onAbort, { once: true });
|
|
71211
71315
|
});
|
|
71212
71316
|
const raced = await Promise.race([nextMessage, abortRace]);
|
|
@@ -72161,6 +72265,7 @@ ${message.api_refusal_explanation}` : "";
|
|
|
72161
72265
|
break;
|
|
72162
72266
|
}
|
|
72163
72267
|
case "rate_limit_event": {
|
|
72268
|
+
this.onRateLimitEvent?.(message.rate_limit_info);
|
|
72164
72269
|
if (lastAssistantTotalUsage !== null) {
|
|
72165
72270
|
await sendUpdate({
|
|
72166
72271
|
sessionId: message.session_id,
|
|
@@ -74702,7 +74807,7 @@ var AGENT_TURN_META2 = "mobius.agentTurn";
|
|
|
74702
74807
|
function createClaudeAcpApp(options = {}) {
|
|
74703
74808
|
let agent2 = null;
|
|
74704
74809
|
const app = agent({ name: "claude-code-acp" }).onConnect((connection) => {
|
|
74705
|
-
agent2 = new ClaudeAcpAgent(new ClientConnection(connection.client, options.onSessionUpdate), options.logger, options.environment, options.spawnClaudeCodeProcess, options.onBackgroundActivity, options.onPromptSuggestion);
|
|
74810
|
+
agent2 = new ClaudeAcpAgent(new ClientConnection(connection.client, options.onSessionUpdate), options.logger, options.environment, options.spawnClaudeCodeProcess, options.onBackgroundActivity, options.onPromptSuggestion, options.onRateLimitEvent);
|
|
74706
74811
|
options.onConnect?.(connection);
|
|
74707
74812
|
}).onRequest(methods.agent.initialize, (ctx) => requiredAgent(agent2).initialize(ctx.params)).onRequest(methods.agent.session.new, (ctx) => requiredAgent(agent2).newSession(ctx.params)).onRequest(methods.agent.session.load, (ctx) => requiredAgent(agent2).loadSession(ctx.params, ctx.signal)).onRequest(methods.agent.session.fork, (ctx) => requiredAgent(agent2).unstable_forkSession(ctx.params, ctx.signal)).onRequest(methods.agent.session.list, (ctx) => requiredAgent(agent2).listSessions(ctx.params, ctx.signal)).onRequest(methods.agent.session.delete, (ctx) => requiredAgent(agent2).deleteSession(ctx.params)).onRequest(methods.agent.session.resume, (ctx) => requiredAgent(agent2).resumeSession(ctx.params)).onRequest(methods.agent.session.close, (ctx) => requiredAgent(agent2).closeSession(ctx.params)).onRequest(methods.agent.session.setMode, (ctx) => requiredAgent(agent2).setSessionMode(ctx.params)).onRequest(methods.agent.session.setConfigOption, (ctx) => requiredAgent(agent2).setSessionConfigOption(ctx.params)).onRequest(methods.agent.authenticate, (ctx) => requiredAgent(agent2).authenticate(ctx.params)).onRequest(methods.agent.providers.list, (ctx) => requiredAgent(agent2).unstable_listProviders(ctx.params)).onRequest(methods.agent.providers.set, (ctx) => requiredAgent(agent2).unstable_setProvider(ctx.params)).onRequest(methods.agent.providers.disable, (ctx) => requiredAgent(agent2).unstable_disableProvider(ctx.params)).onRequest(methods.agent.logout, (ctx) => requiredAgent(agent2).logout(ctx.params)).onRequest(methods.agent.session.prompt, (ctx) => runPromptWithCancellation(requiredAgent(agent2), ctx.params, ctx.signal)).onNotification(methods.agent.session.cancel, (ctx) => requiredAgent(agent2).cancel(ctx.params)).onRequest(STEER_METHOD, { parse: parseSteerRequest }, (ctx) => requiredAgent(agent2).steer(ctx.params)).onRequest(RENAME_METHOD, { parse: parseRenameRequest }, (ctx) => requiredAgent(agent2).renameSession(ctx.params)).onRequest(REVISION_METHOD, { parse: parseRevisionRequest }, (ctx) => requiredAgent(agent2).readSessionRevision(ctx.params, ctx.signal)).onRequest(MODEL_SETTINGS_METHOD, { parse: parseModelSettingsRequest }, (ctx) => requiredAgent(agent2).readModelSettings(ctx.params)).onRequest(GOAL_CONTROL_METHOD, { parse: parseGoalRequest }, (ctx) => requiredAgent(agent2).goal(ctx.params));
|
|
74708
74813
|
return { agent: () => agent2, app };
|
|
@@ -74814,6 +74919,881 @@ function getMatchingModelUsage(modelUsage, currentModel) {
|
|
|
74814
74919
|
}
|
|
74815
74920
|
}
|
|
74816
74921
|
|
|
74922
|
+
// src/engine/acp/harness/claude/usage-quota.ts
|
|
74923
|
+
import { spawn as spawn5 } from "node:child_process";
|
|
74924
|
+
var CLAUDE_AUTH_TIMEOUT_MILLISECONDS = 1e4;
|
|
74925
|
+
var CLAUDE_USAGE_TIMEOUT_MILLISECONDS = 2e4;
|
|
74926
|
+
var MAX_CLI_OUTPUT_BYTES = 256 * 1024;
|
|
74927
|
+
var SESSION_WINDOW_MINUTES = 5 * 60;
|
|
74928
|
+
var WEEKLY_WINDOW_MINUTES = 7 * 24 * 60;
|
|
74929
|
+
var authStatusSchema = external_exports.object({
|
|
74930
|
+
loggedIn: external_exports.boolean(),
|
|
74931
|
+
authMethod: external_exports.string().nullish(),
|
|
74932
|
+
apiProvider: external_exports.string().nullish(),
|
|
74933
|
+
email: external_exports.string().nullish(),
|
|
74934
|
+
subscriptionType: external_exports.string().nullish(),
|
|
74935
|
+
planTier: external_exports.string().nullish()
|
|
74936
|
+
});
|
|
74937
|
+
var utilizationWindowSchema = external_exports.object({
|
|
74938
|
+
utilization: external_exports.number().nullish(),
|
|
74939
|
+
resets_at: external_exports.string().nullish()
|
|
74940
|
+
});
|
|
74941
|
+
var modelScopedWindowSchema = external_exports.object({
|
|
74942
|
+
display_name: external_exports.string().min(1),
|
|
74943
|
+
utilization: external_exports.number().nullish(),
|
|
74944
|
+
resets_at: external_exports.string().nullish()
|
|
74945
|
+
});
|
|
74946
|
+
var spendMoneySchema = external_exports.object({
|
|
74947
|
+
amount_minor: external_exports.number().int().nonnegative(),
|
|
74948
|
+
currency: external_exports.string().min(1),
|
|
74949
|
+
exponent: external_exports.number().int().nonnegative()
|
|
74950
|
+
});
|
|
74951
|
+
var spendBudgetSchema = external_exports.object({
|
|
74952
|
+
enabled: external_exports.boolean(),
|
|
74953
|
+
used: spendMoneySchema,
|
|
74954
|
+
limit: spendMoneySchema
|
|
74955
|
+
});
|
|
74956
|
+
var extraUsageSchema = external_exports.object({
|
|
74957
|
+
is_enabled: external_exports.boolean(),
|
|
74958
|
+
monthly_limit: external_exports.number().nullish(),
|
|
74959
|
+
used_credits: external_exports.number().nullish(),
|
|
74960
|
+
utilization: external_exports.number().nullish()
|
|
74961
|
+
});
|
|
74962
|
+
var rateLimitsSchema = external_exports.object({
|
|
74963
|
+
five_hour: utilizationWindowSchema.nullish(),
|
|
74964
|
+
seven_day: utilizationWindowSchema.nullish(),
|
|
74965
|
+
seven_day_opus: utilizationWindowSchema.nullish(),
|
|
74966
|
+
seven_day_sonnet: utilizationWindowSchema.nullish(),
|
|
74967
|
+
seven_day_oauth_apps: utilizationWindowSchema.nullish(),
|
|
74968
|
+
model_scoped: external_exports.array(modelScopedWindowSchema).nullish(),
|
|
74969
|
+
extra_usage: extraUsageSchema.nullish(),
|
|
74970
|
+
spend: spendBudgetSchema.nullish()
|
|
74971
|
+
});
|
|
74972
|
+
var getUsageResponseSchema = external_exports.object({
|
|
74973
|
+
subscription_type: external_exports.string().nullish(),
|
|
74974
|
+
rate_limits_available: external_exports.boolean(),
|
|
74975
|
+
rate_limits: rateLimitsSchema.nullish()
|
|
74976
|
+
});
|
|
74977
|
+
function clampPercent(value) {
|
|
74978
|
+
if (!Number.isFinite(value)) {
|
|
74979
|
+
return 0;
|
|
74980
|
+
}
|
|
74981
|
+
const clamped = Math.max(0, Math.min(100, value));
|
|
74982
|
+
return Math.round(clamped * 100) / 100;
|
|
74983
|
+
}
|
|
74984
|
+
function normalizeIsoTimestamp(value) {
|
|
74985
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
74986
|
+
return void 0;
|
|
74987
|
+
}
|
|
74988
|
+
const parsed = Date.parse(value);
|
|
74989
|
+
if (!Number.isFinite(parsed)) {
|
|
74990
|
+
return void 0;
|
|
74991
|
+
}
|
|
74992
|
+
return new Date(parsed).toISOString();
|
|
74993
|
+
}
|
|
74994
|
+
function isoFromEpochSeconds(value) {
|
|
74995
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
74996
|
+
return void 0;
|
|
74997
|
+
}
|
|
74998
|
+
const date5 = new Date(value * 1e3);
|
|
74999
|
+
return Number.isNaN(date5.getTime()) ? void 0 : date5.toISOString();
|
|
75000
|
+
}
|
|
75001
|
+
function formatPlanLabel(planTier, subscriptionType) {
|
|
75002
|
+
const tier = planTier?.trim().toLowerCase();
|
|
75003
|
+
if (tier !== void 0 && tier.length > 0) {
|
|
75004
|
+
if (tier === "max_20x") {
|
|
75005
|
+
return "Max 20x";
|
|
75006
|
+
}
|
|
75007
|
+
if (tier === "max_5x") {
|
|
75008
|
+
return "Max 5x";
|
|
75009
|
+
}
|
|
75010
|
+
if (tier.startsWith("default_claude_")) {
|
|
75011
|
+
const suffix = tier.slice("default_claude_".length).replace(/_/gu, " ");
|
|
75012
|
+
return suffix.replace(/\b[a-z]/gu, (ch) => ch.toUpperCase()).slice(0, 64);
|
|
75013
|
+
}
|
|
75014
|
+
return tier.replace(/_/gu, " ").replace(/\b[a-z]/gu, (ch) => ch.toUpperCase()).slice(0, 64);
|
|
75015
|
+
}
|
|
75016
|
+
const sub = subscriptionType?.trim().toLowerCase();
|
|
75017
|
+
if (sub === void 0 || sub.length === 0) {
|
|
75018
|
+
return void 0;
|
|
75019
|
+
}
|
|
75020
|
+
switch (sub) {
|
|
75021
|
+
case "pro":
|
|
75022
|
+
return "Pro";
|
|
75023
|
+
case "max":
|
|
75024
|
+
return "Max";
|
|
75025
|
+
case "team":
|
|
75026
|
+
return "Team";
|
|
75027
|
+
case "enterprise":
|
|
75028
|
+
return "Enterprise";
|
|
75029
|
+
default:
|
|
75030
|
+
return sub.slice(0, 64);
|
|
75031
|
+
}
|
|
75032
|
+
}
|
|
75033
|
+
function scopeToken(displayName) {
|
|
75034
|
+
return displayName.toLowerCase().replace(/[^a-z0-9]+/gu, "_").replace(/^_+|_+$/gu, "");
|
|
75035
|
+
}
|
|
75036
|
+
function formatMinorCurrency(amountMinor, currency, exponent) {
|
|
75037
|
+
const divisor = 10 ** exponent;
|
|
75038
|
+
const major = amountMinor / divisor;
|
|
75039
|
+
const prefix = currency.toUpperCase() === "USD" ? "$" : `${currency.toUpperCase()} `;
|
|
75040
|
+
return `${prefix}${major.toFixed(exponent)}`;
|
|
75041
|
+
}
|
|
75042
|
+
function buildWindow(params) {
|
|
75043
|
+
const usedPercent = clampPercent(params.usedPercent);
|
|
75044
|
+
const remainingPercent = clampPercent(100 - usedPercent);
|
|
75045
|
+
return {
|
|
75046
|
+
id: params.id,
|
|
75047
|
+
kind: params.kind,
|
|
75048
|
+
label: params.label,
|
|
75049
|
+
...params.group === void 0 ? {} : { group: params.group },
|
|
75050
|
+
usedPercent,
|
|
75051
|
+
remainingPercent,
|
|
75052
|
+
...params.resetsAt === void 0 ? {} : { resetsAt: params.resetsAt },
|
|
75053
|
+
...params.windowDurationMins === void 0 ? {} : { windowDurationMins: params.windowDurationMins },
|
|
75054
|
+
...params.isExtra === void 0 ? {} : { isExtra: params.isExtra }
|
|
75055
|
+
};
|
|
75056
|
+
}
|
|
75057
|
+
function extractExtraUsage(rateLimits) {
|
|
75058
|
+
const spend = rateLimits.spend;
|
|
75059
|
+
if (spend?.enabled && spend.used.currency.trim() === spend.limit.currency.trim() && spend.used.exponent === spend.limit.exponent) {
|
|
75060
|
+
if (spend.limit.amount_minor === 0) {
|
|
75061
|
+
return {
|
|
75062
|
+
credits: {
|
|
75063
|
+
unlimited: false,
|
|
75064
|
+
zeroSpendCap: true
|
|
75065
|
+
}
|
|
75066
|
+
};
|
|
75067
|
+
}
|
|
75068
|
+
const percent2 = clampPercent(spend.used.amount_minor / spend.limit.amount_minor * 100);
|
|
75069
|
+
const usedText = formatMinorCurrency(spend.used.amount_minor, spend.used.currency, spend.used.exponent);
|
|
75070
|
+
const limitText = formatMinorCurrency(spend.limit.amount_minor, spend.limit.currency, spend.limit.exponent);
|
|
75071
|
+
return {
|
|
75072
|
+
window: buildWindow({
|
|
75073
|
+
id: "monthly_spend",
|
|
75074
|
+
kind: "monthly",
|
|
75075
|
+
label: "Extra usage",
|
|
75076
|
+
usedPercent: percent2,
|
|
75077
|
+
isExtra: true
|
|
75078
|
+
}),
|
|
75079
|
+
credits: {
|
|
75080
|
+
unlimited: false,
|
|
75081
|
+
balanceDisplay: `${usedText} / ${limitText}`
|
|
75082
|
+
}
|
|
75083
|
+
};
|
|
75084
|
+
}
|
|
75085
|
+
const extra = rateLimits.extra_usage;
|
|
75086
|
+
if (extra === null || extra === void 0 || !extra.is_enabled) {
|
|
75087
|
+
return {};
|
|
75088
|
+
}
|
|
75089
|
+
if (extra.monthly_limit === 0) {
|
|
75090
|
+
return {
|
|
75091
|
+
credits: {
|
|
75092
|
+
unlimited: false,
|
|
75093
|
+
zeroSpendCap: true
|
|
75094
|
+
}
|
|
75095
|
+
};
|
|
75096
|
+
}
|
|
75097
|
+
const percent = typeof extra.used_credits === "number" && typeof extra.monthly_limit === "number" && Number.isFinite(extra.used_credits) && Number.isFinite(extra.monthly_limit) && extra.monthly_limit > 0 ? clampPercent(extra.used_credits / extra.monthly_limit * 100) : typeof extra.utilization === "number" && Number.isFinite(extra.utilization) ? clampPercent(extra.utilization) : void 0;
|
|
75098
|
+
const balanceDisplay = typeof extra.used_credits === "number" && typeof extra.monthly_limit === "number" && Number.isFinite(extra.used_credits) && Number.isFinite(extra.monthly_limit) && extra.monthly_limit > 0 ? `$${(extra.used_credits / 100).toFixed(2)} / $${(extra.monthly_limit / 100).toFixed(2)}` : void 0;
|
|
75099
|
+
return {
|
|
75100
|
+
...percent === void 0 ? {} : {
|
|
75101
|
+
window: buildWindow({
|
|
75102
|
+
id: "monthly_spend",
|
|
75103
|
+
kind: "monthly",
|
|
75104
|
+
label: "Extra usage",
|
|
75105
|
+
usedPercent: percent,
|
|
75106
|
+
isExtra: true
|
|
75107
|
+
})
|
|
75108
|
+
},
|
|
75109
|
+
...balanceDisplay === void 0 ? {} : {
|
|
75110
|
+
credits: {
|
|
75111
|
+
unlimited: false,
|
|
75112
|
+
balanceDisplay
|
|
75113
|
+
}
|
|
75114
|
+
}
|
|
75115
|
+
};
|
|
75116
|
+
}
|
|
75117
|
+
function claudeRateLimitEventToReport(info, observedAt) {
|
|
75118
|
+
const type = info.rateLimitType;
|
|
75119
|
+
if (type === void 0 || typeof info.utilization !== "number" || !Number.isFinite(info.utilization)) {
|
|
75120
|
+
return null;
|
|
75121
|
+
}
|
|
75122
|
+
const usedPercent = clampPercent(info.utilization <= 1 ? info.utilization * 100 : info.utilization);
|
|
75123
|
+
const resetsAt = isoFromEpochSeconds(info.resetsAt);
|
|
75124
|
+
switch (type) {
|
|
75125
|
+
case "five_hour":
|
|
75126
|
+
return {
|
|
75127
|
+
agentId: "claude",
|
|
75128
|
+
observedAt,
|
|
75129
|
+
windows: [
|
|
75130
|
+
buildWindow({
|
|
75131
|
+
id: "five_hour",
|
|
75132
|
+
kind: "session",
|
|
75133
|
+
label: "Session",
|
|
75134
|
+
usedPercent,
|
|
75135
|
+
windowDurationMins: SESSION_WINDOW_MINUTES,
|
|
75136
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
75137
|
+
})
|
|
75138
|
+
]
|
|
75139
|
+
};
|
|
75140
|
+
case "seven_day":
|
|
75141
|
+
return {
|
|
75142
|
+
agentId: "claude",
|
|
75143
|
+
observedAt,
|
|
75144
|
+
windows: [
|
|
75145
|
+
buildWindow({
|
|
75146
|
+
id: "seven_day",
|
|
75147
|
+
kind: "weekly",
|
|
75148
|
+
label: "Weekly",
|
|
75149
|
+
usedPercent,
|
|
75150
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
75151
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
75152
|
+
})
|
|
75153
|
+
]
|
|
75154
|
+
};
|
|
75155
|
+
case "seven_day_opus":
|
|
75156
|
+
return {
|
|
75157
|
+
agentId: "claude",
|
|
75158
|
+
observedAt,
|
|
75159
|
+
windows: [
|
|
75160
|
+
buildWindow({
|
|
75161
|
+
id: "seven_day_opus",
|
|
75162
|
+
kind: "weekly",
|
|
75163
|
+
label: "Weekly \xB7 Opus",
|
|
75164
|
+
group: "Models",
|
|
75165
|
+
usedPercent,
|
|
75166
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
75167
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
75168
|
+
})
|
|
75169
|
+
]
|
|
75170
|
+
};
|
|
75171
|
+
case "seven_day_sonnet":
|
|
75172
|
+
return {
|
|
75173
|
+
agentId: "claude",
|
|
75174
|
+
observedAt,
|
|
75175
|
+
windows: [
|
|
75176
|
+
buildWindow({
|
|
75177
|
+
id: "seven_day_sonnet",
|
|
75178
|
+
kind: "weekly",
|
|
75179
|
+
label: "Weekly \xB7 Sonnet",
|
|
75180
|
+
group: "Models",
|
|
75181
|
+
usedPercent,
|
|
75182
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
75183
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
75184
|
+
})
|
|
75185
|
+
]
|
|
75186
|
+
};
|
|
75187
|
+
case "seven_day_overage_included":
|
|
75188
|
+
return {
|
|
75189
|
+
agentId: "claude",
|
|
75190
|
+
observedAt,
|
|
75191
|
+
windows: [
|
|
75192
|
+
buildWindow({
|
|
75193
|
+
id: "seven_day_overage_included",
|
|
75194
|
+
kind: "weekly",
|
|
75195
|
+
label: "Weekly \xB7 Model",
|
|
75196
|
+
group: "Models",
|
|
75197
|
+
usedPercent,
|
|
75198
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
75199
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
75200
|
+
})
|
|
75201
|
+
]
|
|
75202
|
+
};
|
|
75203
|
+
default:
|
|
75204
|
+
return null;
|
|
75205
|
+
}
|
|
75206
|
+
}
|
|
75207
|
+
async function runCliCommand(params) {
|
|
75208
|
+
params.signal.throwIfAborted();
|
|
75209
|
+
const launch = executableLaunch2(params.command, [...params.args]);
|
|
75210
|
+
const child = spawn5(launch.command, [...launch.arguments], {
|
|
75211
|
+
cwd: params.cwd,
|
|
75212
|
+
...platformSpawnOptions,
|
|
75213
|
+
env: { ...process.env, ...params.environment },
|
|
75214
|
+
shell: false,
|
|
75215
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
75216
|
+
});
|
|
75217
|
+
const processTreePromise = captureProcessTree(child).catch(() => []);
|
|
75218
|
+
const timeoutSignal = AbortSignal.any([params.signal, AbortSignal.timeout(params.timeoutMs)]);
|
|
75219
|
+
let stdout = "";
|
|
75220
|
+
let stderr = "";
|
|
75221
|
+
let stdoutBytes = 0;
|
|
75222
|
+
let stderrBytes = 0;
|
|
75223
|
+
return await new Promise((resolve21, reject2) => {
|
|
75224
|
+
let settled = false;
|
|
75225
|
+
const finish = (outcome) => {
|
|
75226
|
+
if (settled) {
|
|
75227
|
+
return;
|
|
75228
|
+
}
|
|
75229
|
+
settled = true;
|
|
75230
|
+
timeoutSignal.removeEventListener("abort", onAbort);
|
|
75231
|
+
outcome();
|
|
75232
|
+
};
|
|
75233
|
+
const onAbort = () => {
|
|
75234
|
+
void processTreePromise.then(async (processTree) => await stopProcessTree(child, processTree)).catch(() => void 0).finally(() => {
|
|
75235
|
+
finish(() => reject2(timeoutSignal.reason ?? new Error("Claude command aborted")));
|
|
75236
|
+
});
|
|
75237
|
+
};
|
|
75238
|
+
timeoutSignal.addEventListener("abort", onAbort, { once: true });
|
|
75239
|
+
child.stdout?.setEncoding("utf8");
|
|
75240
|
+
child.stdout?.on("data", (chunk) => {
|
|
75241
|
+
if (stdoutBytes < MAX_CLI_OUTPUT_BYTES) {
|
|
75242
|
+
stdout += chunk;
|
|
75243
|
+
stdoutBytes += Buffer.byteLength(chunk);
|
|
75244
|
+
}
|
|
75245
|
+
});
|
|
75246
|
+
child.stderr?.setEncoding("utf8");
|
|
75247
|
+
child.stderr?.on("data", (chunk) => {
|
|
75248
|
+
if (stderrBytes < MAX_CLI_OUTPUT_BYTES) {
|
|
75249
|
+
stderr += chunk;
|
|
75250
|
+
stderrBytes += Buffer.byteLength(chunk);
|
|
75251
|
+
}
|
|
75252
|
+
});
|
|
75253
|
+
child.once("error", (error62) => {
|
|
75254
|
+
finish(() => reject2(error62));
|
|
75255
|
+
});
|
|
75256
|
+
child.once("close", (code) => {
|
|
75257
|
+
finish(() => resolve21({ stdout, stderr, exitCode: code }));
|
|
75258
|
+
});
|
|
75259
|
+
});
|
|
75260
|
+
}
|
|
75261
|
+
async function readClaudeAuthStatus(options) {
|
|
75262
|
+
try {
|
|
75263
|
+
const result = await runCliCommand({
|
|
75264
|
+
command: options.command,
|
|
75265
|
+
args: ["auth", "status"],
|
|
75266
|
+
cwd: options.cwd,
|
|
75267
|
+
environment: options.environment,
|
|
75268
|
+
signal: options.signal,
|
|
75269
|
+
timeoutMs: CLAUDE_AUTH_TIMEOUT_MILLISECONDS
|
|
75270
|
+
});
|
|
75271
|
+
const trimmed = result.stdout.trim();
|
|
75272
|
+
if (trimmed.length === 0) {
|
|
75273
|
+
return null;
|
|
75274
|
+
}
|
|
75275
|
+
const parsed = authStatusSchema.safeParse(JSON.parse(trimmed));
|
|
75276
|
+
return parsed.success ? parsed.data : null;
|
|
75277
|
+
} catch (error62) {
|
|
75278
|
+
if (options.signal.aborted) {
|
|
75279
|
+
throw options.signal.reason ?? error62;
|
|
75280
|
+
}
|
|
75281
|
+
return null;
|
|
75282
|
+
}
|
|
75283
|
+
}
|
|
75284
|
+
function createIdlePromptStream(signal) {
|
|
75285
|
+
return {
|
|
75286
|
+
[Symbol.asyncIterator]() {
|
|
75287
|
+
return {
|
|
75288
|
+
next: () => new Promise((resolve21) => {
|
|
75289
|
+
if (signal.aborted) {
|
|
75290
|
+
resolve21({ done: true, value: void 0 });
|
|
75291
|
+
return;
|
|
75292
|
+
}
|
|
75293
|
+
signal.addEventListener("abort", () => resolve21({ done: true, value: void 0 }), {
|
|
75294
|
+
once: true
|
|
75295
|
+
});
|
|
75296
|
+
})
|
|
75297
|
+
};
|
|
75298
|
+
}
|
|
75299
|
+
};
|
|
75300
|
+
}
|
|
75301
|
+
function raceWithAbort2(promise2, signal) {
|
|
75302
|
+
if (signal.aborted) {
|
|
75303
|
+
return Promise.reject(signal.reason ?? new Error("Operation aborted"));
|
|
75304
|
+
}
|
|
75305
|
+
return new Promise((resolve21, reject2) => {
|
|
75306
|
+
const onAbort = () => {
|
|
75307
|
+
reject2(signal.reason ?? new Error("Operation aborted"));
|
|
75308
|
+
};
|
|
75309
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
75310
|
+
promise2.then(
|
|
75311
|
+
(value) => {
|
|
75312
|
+
signal.removeEventListener("abort", onAbort);
|
|
75313
|
+
resolve21(value);
|
|
75314
|
+
},
|
|
75315
|
+
(error62) => {
|
|
75316
|
+
signal.removeEventListener("abort", onAbort);
|
|
75317
|
+
reject2(error62);
|
|
75318
|
+
}
|
|
75319
|
+
);
|
|
75320
|
+
});
|
|
75321
|
+
}
|
|
75322
|
+
function mapSdkUsageResponse(raw, auth, checkedAt) {
|
|
75323
|
+
const parsed = getUsageResponseSchema.parse(raw);
|
|
75324
|
+
if (!parsed.rate_limits_available) {
|
|
75325
|
+
return {
|
|
75326
|
+
agentId: "claude",
|
|
75327
|
+
status: "unsupported",
|
|
75328
|
+
checkedAt,
|
|
75329
|
+
reason: "no_subscription_quota",
|
|
75330
|
+
message: "Claude Code is not using a subscription plan with rolling usage windows."
|
|
75331
|
+
};
|
|
75332
|
+
}
|
|
75333
|
+
const rateLimits = parsed.rate_limits;
|
|
75334
|
+
if (rateLimits === null || rateLimits === void 0) {
|
|
75335
|
+
return {
|
|
75336
|
+
agentId: "claude",
|
|
75337
|
+
status: "unavailable",
|
|
75338
|
+
checkedAt,
|
|
75339
|
+
errorCode: "claude_usage_empty",
|
|
75340
|
+
errorMessage: "Claude Code returned no usage quota windows."
|
|
75341
|
+
};
|
|
75342
|
+
}
|
|
75343
|
+
const windows = [];
|
|
75344
|
+
if (typeof rateLimits.five_hour?.utilization === "number") {
|
|
75345
|
+
const resetsAt = normalizeIsoTimestamp(rateLimits.five_hour.resets_at);
|
|
75346
|
+
windows.push(
|
|
75347
|
+
buildWindow({
|
|
75348
|
+
id: "five_hour",
|
|
75349
|
+
kind: "session",
|
|
75350
|
+
label: "Session",
|
|
75351
|
+
usedPercent: rateLimits.five_hour.utilization,
|
|
75352
|
+
windowDurationMins: SESSION_WINDOW_MINUTES,
|
|
75353
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
75354
|
+
})
|
|
75355
|
+
);
|
|
75356
|
+
}
|
|
75357
|
+
if (typeof rateLimits.seven_day?.utilization === "number") {
|
|
75358
|
+
const resetsAt = normalizeIsoTimestamp(rateLimits.seven_day.resets_at);
|
|
75359
|
+
windows.push(
|
|
75360
|
+
buildWindow({
|
|
75361
|
+
id: "seven_day",
|
|
75362
|
+
kind: "weekly",
|
|
75363
|
+
label: "Weekly",
|
|
75364
|
+
usedPercent: rateLimits.seven_day.utilization,
|
|
75365
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
75366
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
75367
|
+
})
|
|
75368
|
+
);
|
|
75369
|
+
}
|
|
75370
|
+
if (typeof rateLimits.seven_day_sonnet?.utilization === "number") {
|
|
75371
|
+
const resetsAt = normalizeIsoTimestamp(rateLimits.seven_day_sonnet.resets_at);
|
|
75372
|
+
windows.push(
|
|
75373
|
+
buildWindow({
|
|
75374
|
+
id: "seven_day_sonnet",
|
|
75375
|
+
kind: "weekly",
|
|
75376
|
+
label: "Weekly \xB7 Sonnet",
|
|
75377
|
+
group: "Models",
|
|
75378
|
+
usedPercent: rateLimits.seven_day_sonnet.utilization,
|
|
75379
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
75380
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
75381
|
+
})
|
|
75382
|
+
);
|
|
75383
|
+
}
|
|
75384
|
+
if (typeof rateLimits.seven_day_opus?.utilization === "number") {
|
|
75385
|
+
const resetsAt = normalizeIsoTimestamp(rateLimits.seven_day_opus.resets_at);
|
|
75386
|
+
windows.push(
|
|
75387
|
+
buildWindow({
|
|
75388
|
+
id: "seven_day_opus",
|
|
75389
|
+
kind: "weekly",
|
|
75390
|
+
label: "Weekly \xB7 Opus",
|
|
75391
|
+
group: "Models",
|
|
75392
|
+
usedPercent: rateLimits.seven_day_opus.utilization,
|
|
75393
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
75394
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
75395
|
+
})
|
|
75396
|
+
);
|
|
75397
|
+
}
|
|
75398
|
+
if (typeof rateLimits.seven_day_oauth_apps?.utilization === "number") {
|
|
75399
|
+
const resetsAt = normalizeIsoTimestamp(rateLimits.seven_day_oauth_apps.resets_at);
|
|
75400
|
+
windows.push(
|
|
75401
|
+
buildWindow({
|
|
75402
|
+
id: "seven_day_oauth_apps",
|
|
75403
|
+
kind: "weekly",
|
|
75404
|
+
label: "Weekly \xB7 OAuth apps",
|
|
75405
|
+
group: "Models",
|
|
75406
|
+
usedPercent: rateLimits.seven_day_oauth_apps.utilization,
|
|
75407
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
75408
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
75409
|
+
})
|
|
75410
|
+
);
|
|
75411
|
+
}
|
|
75412
|
+
const existingIds = new Set(windows.map((window2) => window2.id));
|
|
75413
|
+
for (const entry of rateLimits.model_scoped ?? []) {
|
|
75414
|
+
if (typeof entry.utilization !== "number") {
|
|
75415
|
+
continue;
|
|
75416
|
+
}
|
|
75417
|
+
const token = scopeToken(entry.display_name);
|
|
75418
|
+
const id = token.length > 0 ? `seven_day_${token}` : "seven_day_model";
|
|
75419
|
+
if (existingIds.has(id)) {
|
|
75420
|
+
continue;
|
|
75421
|
+
}
|
|
75422
|
+
existingIds.add(id);
|
|
75423
|
+
const resetsAt = normalizeIsoTimestamp(entry.resets_at);
|
|
75424
|
+
windows.push(
|
|
75425
|
+
buildWindow({
|
|
75426
|
+
id,
|
|
75427
|
+
kind: "weekly",
|
|
75428
|
+
label: `Weekly \xB7 ${entry.display_name.trim()}`,
|
|
75429
|
+
group: "Models",
|
|
75430
|
+
usedPercent: entry.utilization,
|
|
75431
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
75432
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
75433
|
+
})
|
|
75434
|
+
);
|
|
75435
|
+
}
|
|
75436
|
+
const extra = extractExtraUsage(rateLimits);
|
|
75437
|
+
if (extra.window !== void 0) {
|
|
75438
|
+
windows.push(extra.window);
|
|
75439
|
+
}
|
|
75440
|
+
const plan = formatPlanLabel(auth?.planTier, parsed.subscription_type ?? auth?.subscriptionType);
|
|
75441
|
+
const email3 = auth?.email?.trim();
|
|
75442
|
+
return {
|
|
75443
|
+
agentId: "claude",
|
|
75444
|
+
status: "available",
|
|
75445
|
+
checkedAt,
|
|
75446
|
+
...plan === void 0 ? {} : { plan },
|
|
75447
|
+
...email3 === void 0 || email3.length === 0 ? {} : { accountLabel: email3.slice(0, 128) },
|
|
75448
|
+
windows,
|
|
75449
|
+
...extra.credits === void 0 ? {} : { credits: extra.credits }
|
|
75450
|
+
};
|
|
75451
|
+
}
|
|
75452
|
+
var CLI_USAGE_LINE = /^Current (session|week(?: \(([^)]+)\))?):\s*([0-9.]+)% used(?:\s*·\s*resets (.+))?$/u;
|
|
75453
|
+
var CLI_EXTRA_LINE = /^Extra usage:\s*([0-9.]+)% used(?:\s*·\s*([^·]+))?/u;
|
|
75454
|
+
var CLI_MONTHS = [
|
|
75455
|
+
"jan",
|
|
75456
|
+
"feb",
|
|
75457
|
+
"mar",
|
|
75458
|
+
"apr",
|
|
75459
|
+
"may",
|
|
75460
|
+
"jun",
|
|
75461
|
+
"jul",
|
|
75462
|
+
"aug",
|
|
75463
|
+
"sep",
|
|
75464
|
+
"oct",
|
|
75465
|
+
"nov",
|
|
75466
|
+
"dec"
|
|
75467
|
+
];
|
|
75468
|
+
var CLI_DATE_RESET = /^([A-Za-z]{3})\s+(\d{1,2})(?:,\s*(\d{4}))?(?:\s+at|\s*,)\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)$/iu;
|
|
75469
|
+
var CLI_TIME_RESET = /^(\d{1,2})(?::(\d{2}))?\s*(am|pm)$/iu;
|
|
75470
|
+
var RESET_SLACK_MILLISECONDS = 2 * 60 * 60 * 1e3;
|
|
75471
|
+
function zonedParts(epochMs, timeZone) {
|
|
75472
|
+
try {
|
|
75473
|
+
const formatter = new Intl.DateTimeFormat("en-US", {
|
|
75474
|
+
timeZone,
|
|
75475
|
+
year: "numeric",
|
|
75476
|
+
month: "2-digit",
|
|
75477
|
+
day: "2-digit",
|
|
75478
|
+
hour: "2-digit",
|
|
75479
|
+
minute: "2-digit",
|
|
75480
|
+
hourCycle: "h23"
|
|
75481
|
+
});
|
|
75482
|
+
const parts = formatter.formatToParts(new Date(epochMs));
|
|
75483
|
+
const read = (type) => Number(parts.find((part) => part.type === type)?.value ?? Number.NaN);
|
|
75484
|
+
const year = read("year");
|
|
75485
|
+
const month = read("month");
|
|
75486
|
+
const day = read("day");
|
|
75487
|
+
const hour = read("hour") % 24;
|
|
75488
|
+
const minute = read("minute");
|
|
75489
|
+
if (![year, month, day, hour, minute].every(Number.isFinite)) {
|
|
75490
|
+
return null;
|
|
75491
|
+
}
|
|
75492
|
+
return { year, month, day, hour, minute };
|
|
75493
|
+
} catch {
|
|
75494
|
+
return null;
|
|
75495
|
+
}
|
|
75496
|
+
}
|
|
75497
|
+
function zonedDateTimeToUtcMs(target, timeZone) {
|
|
75498
|
+
const desiredWallMs = Date.UTC(target.year, target.month - 1, target.day, target.hour, target.minute, 0, 0);
|
|
75499
|
+
let candidate = desiredWallMs;
|
|
75500
|
+
for (let step = 0; step < 3; step += 1) {
|
|
75501
|
+
const actual = zonedParts(candidate, timeZone);
|
|
75502
|
+
if (actual === null) {
|
|
75503
|
+
return null;
|
|
75504
|
+
}
|
|
75505
|
+
const actualWallMs = Date.UTC(actual.year, actual.month - 1, actual.day, actual.hour, actual.minute, 0, 0);
|
|
75506
|
+
const diff = desiredWallMs - actualWallMs;
|
|
75507
|
+
if (diff === 0) {
|
|
75508
|
+
return candidate;
|
|
75509
|
+
}
|
|
75510
|
+
candidate += diff;
|
|
75511
|
+
}
|
|
75512
|
+
const verified = zonedParts(candidate, timeZone);
|
|
75513
|
+
if (verified === null || verified.year !== target.year || verified.month !== target.month || verified.day !== target.day || verified.hour !== target.hour || verified.minute !== target.minute) {
|
|
75514
|
+
return null;
|
|
75515
|
+
}
|
|
75516
|
+
return candidate;
|
|
75517
|
+
}
|
|
75518
|
+
function parseClaudeCliResetText(raw, nowMs, spanMinutes) {
|
|
75519
|
+
if (raw === void 0) {
|
|
75520
|
+
return void 0;
|
|
75521
|
+
}
|
|
75522
|
+
let text2 = raw.trim();
|
|
75523
|
+
if (text2.length === 0) {
|
|
75524
|
+
return void 0;
|
|
75525
|
+
}
|
|
75526
|
+
let timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
75527
|
+
const zoneStart = text2.lastIndexOf("(");
|
|
75528
|
+
if (zoneStart >= 0 && text2.endsWith(")")) {
|
|
75529
|
+
const candidateZone = text2.slice(zoneStart + 1, -1).trim();
|
|
75530
|
+
if (candidateZone.length > 0 && zonedParts(nowMs, candidateZone) !== null) {
|
|
75531
|
+
timeZone = candidateZone;
|
|
75532
|
+
}
|
|
75533
|
+
text2 = text2.slice(0, zoneStart).trim();
|
|
75534
|
+
}
|
|
75535
|
+
const ref = zonedParts(nowMs, timeZone);
|
|
75536
|
+
if (ref === null) {
|
|
75537
|
+
return void 0;
|
|
75538
|
+
}
|
|
75539
|
+
const latestMs = nowMs + spanMinutes * 6e4 + RESET_SLACK_MILLISECONDS;
|
|
75540
|
+
const dateMatch = CLI_DATE_RESET.exec(text2);
|
|
75541
|
+
if (dateMatch !== null) {
|
|
75542
|
+
const monthToken = (dateMatch[1] ?? "").toLowerCase();
|
|
75543
|
+
const monthIndex = CLI_MONTHS.indexOf(monthToken);
|
|
75544
|
+
const day = Number(dateMatch[2]);
|
|
75545
|
+
const explicitYear = dateMatch[3] === void 0 ? void 0 : Number(dateMatch[3]);
|
|
75546
|
+
const rawHour = Number(dateMatch[4]);
|
|
75547
|
+
const minute = dateMatch[5] === void 0 ? 0 : Number(dateMatch[5]);
|
|
75548
|
+
const meridiem = (dateMatch[6] ?? "").toLowerCase();
|
|
75549
|
+
if (monthIndex < 0 || !Number.isFinite(day) || !Number.isFinite(rawHour) || !Number.isFinite(minute)) {
|
|
75550
|
+
return void 0;
|
|
75551
|
+
}
|
|
75552
|
+
const hour = rawHour % 12 + (meridiem === "pm" ? 12 : 0);
|
|
75553
|
+
if (explicitYear !== void 0) {
|
|
75554
|
+
const utcMs = zonedDateTimeToUtcMs(
|
|
75555
|
+
{ year: explicitYear, month: monthIndex + 1, day, hour, minute },
|
|
75556
|
+
timeZone
|
|
75557
|
+
);
|
|
75558
|
+
return utcMs === null ? void 0 : new Date(utcMs).toISOString();
|
|
75559
|
+
}
|
|
75560
|
+
let fallbackPast = null;
|
|
75561
|
+
for (const year of [ref.year - 1, ref.year, ref.year + 1]) {
|
|
75562
|
+
const utcMs = zonedDateTimeToUtcMs({ year, month: monthIndex + 1, day, hour, minute }, timeZone);
|
|
75563
|
+
if (utcMs === null) {
|
|
75564
|
+
continue;
|
|
75565
|
+
}
|
|
75566
|
+
if (utcMs >= nowMs - 24 * 60 * 60 * 1e3 && utcMs <= latestMs) {
|
|
75567
|
+
return new Date(utcMs).toISOString();
|
|
75568
|
+
}
|
|
75569
|
+
if (utcMs < nowMs) {
|
|
75570
|
+
fallbackPast = utcMs;
|
|
75571
|
+
}
|
|
75572
|
+
}
|
|
75573
|
+
return fallbackPast === null ? void 0 : new Date(fallbackPast).toISOString();
|
|
75574
|
+
}
|
|
75575
|
+
const timeMatch = CLI_TIME_RESET.exec(text2);
|
|
75576
|
+
if (timeMatch !== null) {
|
|
75577
|
+
const rawHour = Number(timeMatch[1]);
|
|
75578
|
+
const minute = timeMatch[2] === void 0 ? 0 : Number(timeMatch[2]);
|
|
75579
|
+
const meridiem = (timeMatch[3] ?? "").toLowerCase();
|
|
75580
|
+
if (!Number.isFinite(rawHour) || !Number.isFinite(minute)) {
|
|
75581
|
+
return void 0;
|
|
75582
|
+
}
|
|
75583
|
+
const hour = rawHour % 12 + (meridiem === "pm" ? 12 : 0);
|
|
75584
|
+
for (const dayOffset of [0, 1, 2]) {
|
|
75585
|
+
const base = new Date(Date.UTC(ref.year, ref.month - 1, ref.day + dayOffset));
|
|
75586
|
+
const utcMs = zonedDateTimeToUtcMs(
|
|
75587
|
+
{ year: base.getUTCFullYear(), month: base.getUTCMonth() + 1, day: base.getUTCDate(), hour, minute },
|
|
75588
|
+
timeZone
|
|
75589
|
+
);
|
|
75590
|
+
if (utcMs !== null && utcMs >= nowMs && utcMs <= latestMs) {
|
|
75591
|
+
return new Date(utcMs).toISOString();
|
|
75592
|
+
}
|
|
75593
|
+
}
|
|
75594
|
+
}
|
|
75595
|
+
return void 0;
|
|
75596
|
+
}
|
|
75597
|
+
function parseClaudeCliUsageOutput(output2, auth, checkedAt) {
|
|
75598
|
+
const nowMs = Date.parse(checkedAt);
|
|
75599
|
+
const windows = [];
|
|
75600
|
+
let credits;
|
|
75601
|
+
for (const rawLine of output2.split(/\r?\n/u)) {
|
|
75602
|
+
const line = rawLine.trim();
|
|
75603
|
+
const match = CLI_USAGE_LINE.exec(line);
|
|
75604
|
+
if (match !== null) {
|
|
75605
|
+
const period = match[1];
|
|
75606
|
+
const scope = match[2];
|
|
75607
|
+
const percent = Number(match[3]);
|
|
75608
|
+
const resetRaw = match[4];
|
|
75609
|
+
if (!Number.isFinite(percent)) {
|
|
75610
|
+
continue;
|
|
75611
|
+
}
|
|
75612
|
+
if (period === "session") {
|
|
75613
|
+
const resetsAt = parseClaudeCliResetText(resetRaw, nowMs, SESSION_WINDOW_MINUTES);
|
|
75614
|
+
windows.push(
|
|
75615
|
+
buildWindow({
|
|
75616
|
+
id: "five_hour",
|
|
75617
|
+
kind: "session",
|
|
75618
|
+
label: "Session",
|
|
75619
|
+
usedPercent: percent,
|
|
75620
|
+
windowDurationMins: SESSION_WINDOW_MINUTES,
|
|
75621
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
75622
|
+
})
|
|
75623
|
+
);
|
|
75624
|
+
} else if (scope === void 0 || scope.toLowerCase() === "all models") {
|
|
75625
|
+
const resetsAt = parseClaudeCliResetText(resetRaw, nowMs, WEEKLY_WINDOW_MINUTES);
|
|
75626
|
+
windows.push(
|
|
75627
|
+
buildWindow({
|
|
75628
|
+
id: "seven_day",
|
|
75629
|
+
kind: "weekly",
|
|
75630
|
+
label: "Weekly",
|
|
75631
|
+
usedPercent: percent,
|
|
75632
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
75633
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
75634
|
+
})
|
|
75635
|
+
);
|
|
75636
|
+
} else {
|
|
75637
|
+
const token = scopeToken(scope);
|
|
75638
|
+
const resetsAt = parseClaudeCliResetText(resetRaw, nowMs, WEEKLY_WINDOW_MINUTES);
|
|
75639
|
+
windows.push(
|
|
75640
|
+
buildWindow({
|
|
75641
|
+
id: token.length > 0 ? `seven_day_${token}` : "seven_day_model",
|
|
75642
|
+
kind: "weekly",
|
|
75643
|
+
label: `Weekly \xB7 ${scope.trim()}`,
|
|
75644
|
+
group: "Models",
|
|
75645
|
+
usedPercent: percent,
|
|
75646
|
+
windowDurationMins: WEEKLY_WINDOW_MINUTES,
|
|
75647
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
75648
|
+
})
|
|
75649
|
+
);
|
|
75650
|
+
}
|
|
75651
|
+
continue;
|
|
75652
|
+
}
|
|
75653
|
+
const extraMatch = CLI_EXTRA_LINE.exec(line);
|
|
75654
|
+
if (extraMatch !== null) {
|
|
75655
|
+
const percent = Number(extraMatch[1]);
|
|
75656
|
+
const detail = extraMatch[2]?.trim();
|
|
75657
|
+
if (Number.isFinite(percent)) {
|
|
75658
|
+
windows.push(
|
|
75659
|
+
buildWindow({
|
|
75660
|
+
id: "monthly_spend",
|
|
75661
|
+
kind: "monthly",
|
|
75662
|
+
label: "Extra usage",
|
|
75663
|
+
usedPercent: percent,
|
|
75664
|
+
isExtra: true
|
|
75665
|
+
})
|
|
75666
|
+
);
|
|
75667
|
+
}
|
|
75668
|
+
if (detail !== void 0 && detail.length > 0) {
|
|
75669
|
+
credits = { unlimited: false, balanceDisplay: detail.slice(0, 64) };
|
|
75670
|
+
}
|
|
75671
|
+
}
|
|
75672
|
+
}
|
|
75673
|
+
if (windows.length === 0) {
|
|
75674
|
+
return {
|
|
75675
|
+
agentId: "claude",
|
|
75676
|
+
status: "unavailable",
|
|
75677
|
+
checkedAt,
|
|
75678
|
+
errorCode: "claude_usage_unavailable",
|
|
75679
|
+
errorMessage: "Claude Code did not report subscription usage figures."
|
|
75680
|
+
};
|
|
75681
|
+
}
|
|
75682
|
+
const plan = formatPlanLabel(auth?.planTier, auth?.subscriptionType);
|
|
75683
|
+
const email3 = auth?.email?.trim();
|
|
75684
|
+
return {
|
|
75685
|
+
agentId: "claude",
|
|
75686
|
+
status: "available",
|
|
75687
|
+
checkedAt,
|
|
75688
|
+
...plan === void 0 ? {} : { plan },
|
|
75689
|
+
...email3 === void 0 || email3.length === 0 ? {} : { accountLabel: email3.slice(0, 128) },
|
|
75690
|
+
windows,
|
|
75691
|
+
...credits === void 0 ? {} : { credits }
|
|
75692
|
+
};
|
|
75693
|
+
}
|
|
75694
|
+
async function readClaudeUsageViaSdk(options, auth, checkedAt) {
|
|
75695
|
+
const probeController = new AbortController();
|
|
75696
|
+
const timeoutSignal = AbortSignal.any([
|
|
75697
|
+
options.signal,
|
|
75698
|
+
probeController.signal,
|
|
75699
|
+
AbortSignal.timeout(CLAUDE_USAGE_TIMEOUT_MILLISECONDS)
|
|
75700
|
+
]);
|
|
75701
|
+
const forwardAbort = () => {
|
|
75702
|
+
probeController.abort(timeoutSignal.reason);
|
|
75703
|
+
};
|
|
75704
|
+
timeoutSignal.addEventListener("abort", forwardAbort, { once: true });
|
|
75705
|
+
const q2 = MZt({
|
|
75706
|
+
prompt: createIdlePromptStream(probeController.signal),
|
|
75707
|
+
options: {
|
|
75708
|
+
abortController: probeController,
|
|
75709
|
+
cwd: options.cwd,
|
|
75710
|
+
env: {
|
|
75711
|
+
...process.env,
|
|
75712
|
+
...options.environment,
|
|
75713
|
+
CLAUDE_CODE_EXECUTABLE: options.command
|
|
75714
|
+
},
|
|
75715
|
+
pathToClaudeCodeExecutable: options.command,
|
|
75716
|
+
persistSession: false,
|
|
75717
|
+
settingSources: [],
|
|
75718
|
+
spawnClaudeCodeProcess: spawnClaudeWithParentLifeline
|
|
75719
|
+
}
|
|
75720
|
+
});
|
|
75721
|
+
try {
|
|
75722
|
+
const init = await raceWithAbort2(q2.initializationResult(), timeoutSignal);
|
|
75723
|
+
const response = await raceWithAbort2(
|
|
75724
|
+
q2.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(),
|
|
75725
|
+
timeoutSignal
|
|
75726
|
+
);
|
|
75727
|
+
const mergedAuth = auth ?? (init.account === void 0 ? null : {
|
|
75728
|
+
loggedIn: true,
|
|
75729
|
+
email: init.account.email,
|
|
75730
|
+
subscriptionType: init.account.subscriptionType,
|
|
75731
|
+
apiProvider: init.account.apiProvider
|
|
75732
|
+
});
|
|
75733
|
+
return mapSdkUsageResponse(response, mergedAuth, checkedAt);
|
|
75734
|
+
} finally {
|
|
75735
|
+
timeoutSignal.removeEventListener("abort", forwardAbort);
|
|
75736
|
+
probeController.abort();
|
|
75737
|
+
q2.close();
|
|
75738
|
+
}
|
|
75739
|
+
}
|
|
75740
|
+
async function readClaudeUsageQuota(options) {
|
|
75741
|
+
options.signal.throwIfAborted();
|
|
75742
|
+
const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
75743
|
+
const auth = await readClaudeAuthStatus(options);
|
|
75744
|
+
if (auth !== null) {
|
|
75745
|
+
if (!auth.loggedIn) {
|
|
75746
|
+
return {
|
|
75747
|
+
agentId: "claude",
|
|
75748
|
+
status: "unauthenticated",
|
|
75749
|
+
checkedAt,
|
|
75750
|
+
message: "Sign in to Claude Code on this computer to view subscription quotas."
|
|
75751
|
+
};
|
|
75752
|
+
}
|
|
75753
|
+
const provider = auth.apiProvider?.trim();
|
|
75754
|
+
const method = auth.authMethod?.trim();
|
|
75755
|
+
if (provider !== void 0 && provider.length > 0 && provider !== "firstParty" || method !== void 0 && method.length > 0 && method !== "claude.ai" && method !== "oauth") {
|
|
75756
|
+
return {
|
|
75757
|
+
agentId: "claude",
|
|
75758
|
+
status: "unsupported",
|
|
75759
|
+
checkedAt,
|
|
75760
|
+
reason: "api_key",
|
|
75761
|
+
message: "Claude Code is not using a Claude.ai subscription."
|
|
75762
|
+
};
|
|
75763
|
+
}
|
|
75764
|
+
}
|
|
75765
|
+
try {
|
|
75766
|
+
return await readClaudeUsageViaSdk(options, auth, checkedAt);
|
|
75767
|
+
} catch (sdkError) {
|
|
75768
|
+
if (options.signal.aborted) {
|
|
75769
|
+
throw options.signal.reason ?? sdkError;
|
|
75770
|
+
}
|
|
75771
|
+
try {
|
|
75772
|
+
const cliResult = await runCliCommand({
|
|
75773
|
+
command: options.command,
|
|
75774
|
+
args: ["-p", "/usage"],
|
|
75775
|
+
cwd: options.cwd,
|
|
75776
|
+
environment: options.environment,
|
|
75777
|
+
signal: options.signal,
|
|
75778
|
+
timeoutMs: CLAUDE_USAGE_TIMEOUT_MILLISECONDS
|
|
75779
|
+
});
|
|
75780
|
+
return parseClaudeCliUsageOutput(cliResult.stdout, auth, checkedAt);
|
|
75781
|
+
} catch (cliError) {
|
|
75782
|
+
if (options.signal.aborted) {
|
|
75783
|
+
throw options.signal.reason ?? cliError;
|
|
75784
|
+
}
|
|
75785
|
+
const message = sdkError instanceof Error && sdkError.message.trim().length > 0 ? sdkError.message.trim().slice(0, 256) : "Claude Code could not report subscription usage quotas.";
|
|
75786
|
+
return {
|
|
75787
|
+
agentId: "claude",
|
|
75788
|
+
status: "unavailable",
|
|
75789
|
+
checkedAt,
|
|
75790
|
+
errorCode: "claude_usage_probe_failed",
|
|
75791
|
+
errorMessage: message
|
|
75792
|
+
};
|
|
75793
|
+
}
|
|
75794
|
+
}
|
|
75795
|
+
}
|
|
75796
|
+
|
|
74817
75797
|
// src/engine/acp/harness/claude/endpoint.ts
|
|
74818
75798
|
var ClaudeAcpEndpoint = class {
|
|
74819
75799
|
#agent;
|
|
@@ -74839,6 +75819,14 @@ var ClaudeAcpEndpoint = class {
|
|
|
74839
75819
|
onSessionUpdate: options.onSessionUpdate,
|
|
74840
75820
|
onBackgroundActivity: (activity) => options.onBackgroundActivity?.(activity),
|
|
74841
75821
|
onPromptSuggestion: (report) => options.onPromptSuggestion?.(report),
|
|
75822
|
+
onRateLimitEvent: (info) => {
|
|
75823
|
+
if (this.#closePromise === null) {
|
|
75824
|
+
const report = claudeRateLimitEventToReport(info, (/* @__PURE__ */ new Date()).toISOString());
|
|
75825
|
+
if (report !== null) {
|
|
75826
|
+
options.onUsageQuota?.(report);
|
|
75827
|
+
}
|
|
75828
|
+
}
|
|
75829
|
+
},
|
|
74842
75830
|
onConnect: (connection) => {
|
|
74843
75831
|
this.#connection = connection;
|
|
74844
75832
|
}
|
|
@@ -74876,7 +75864,8 @@ var ClaudeAgentConnection = class extends EndpointAgentConnection {
|
|
|
74876
75864
|
await options.client.onUpdate(notification);
|
|
74877
75865
|
},
|
|
74878
75866
|
onBackgroundActivity: (activity) => options.onBackgroundActivity?.(activity),
|
|
74879
|
-
onPromptSuggestion: (report) => options.onPromptSuggestion?.(report)
|
|
75867
|
+
onPromptSuggestion: (report) => options.onPromptSuggestion?.(report),
|
|
75868
|
+
onUsageQuota: (report) => options.onUsageQuota?.(report)
|
|
74880
75869
|
});
|
|
74881
75870
|
super(endpoint, options.client);
|
|
74882
75871
|
}
|
|
@@ -74910,7 +75899,7 @@ var ClaudeCodeAgentSpecification = class extends InProcessAcpAgentSpecification
|
|
|
74910
75899
|
};
|
|
74911
75900
|
|
|
74912
75901
|
// src/engine/acp/harness/codex/app-server-client.ts
|
|
74913
|
-
import { spawn as
|
|
75902
|
+
import { spawn as spawn6 } from "node:child_process";
|
|
74914
75903
|
|
|
74915
75904
|
// src/engine/acp/harness/codex/app-server-protocol.ts
|
|
74916
75905
|
import { isAbsolute as isAbsolute9 } from "node:path";
|
|
@@ -75252,7 +76241,7 @@ var CodexAppServerClient = class {
|
|
|
75252
76241
|
constructor(options) {
|
|
75253
76242
|
this.#handlers = options.handlers;
|
|
75254
76243
|
const launch = executableLaunch2(options.command, ["app-server"]);
|
|
75255
|
-
this.#child =
|
|
76244
|
+
this.#child = spawn6(launch.command, [...launch.arguments], {
|
|
75256
76245
|
cwd: options.cwd,
|
|
75257
76246
|
...platformSpawnOptions,
|
|
75258
76247
|
env: { ...process.env, ...options.environment },
|
|
@@ -75642,12 +76631,12 @@ function presentToolItem(item) {
|
|
|
75642
76631
|
};
|
|
75643
76632
|
}
|
|
75644
76633
|
if (item.type === "collabAgentToolCall") {
|
|
75645
|
-
const
|
|
76634
|
+
const spawn9 = item.tool === "spawnAgent";
|
|
75646
76635
|
return {
|
|
75647
76636
|
content: [],
|
|
75648
76637
|
kind: "other",
|
|
75649
76638
|
locations: [],
|
|
75650
|
-
rawInput:
|
|
76639
|
+
rawInput: spawn9 ? {
|
|
75651
76640
|
model: item.model,
|
|
75652
76641
|
prompt: item.prompt,
|
|
75653
76642
|
reasoningEffort: item.reasoningEffort,
|
|
@@ -75655,10 +76644,10 @@ function presentToolItem(item) {
|
|
|
75655
76644
|
} : { receiverThreadIds: item.receiverThreadIds, senderThreadId: item.senderThreadId },
|
|
75656
76645
|
rawOutput: {
|
|
75657
76646
|
agentsStates: item.agentsStates,
|
|
75658
|
-
...
|
|
76647
|
+
...spawn9 ? { receiverThreadIds: item.receiverThreadIds } : {}
|
|
75659
76648
|
},
|
|
75660
76649
|
status: collaborationStatus(item.status),
|
|
75661
|
-
title:
|
|
76650
|
+
title: spawn9 ? "Dispatch subagent" : "Wait for subagent"
|
|
75662
76651
|
};
|
|
75663
76652
|
}
|
|
75664
76653
|
if (item.type === "subAgentActivity" && item.kind === "started") {
|
|
@@ -76634,10 +77623,10 @@ function turnRunning(turn) {
|
|
|
76634
77623
|
}
|
|
76635
77624
|
function waitForNextPoll(timer, signal) {
|
|
76636
77625
|
signal.throwIfAborted();
|
|
76637
|
-
return new Promise((
|
|
77626
|
+
return new Promise((resolve21, reject2) => {
|
|
76638
77627
|
const poll = timer.schedule(() => {
|
|
76639
77628
|
signal.removeEventListener("abort", abort);
|
|
76640
|
-
|
|
77629
|
+
resolve21();
|
|
76641
77630
|
}, POLL_INTERVAL);
|
|
76642
77631
|
const abort = () => {
|
|
76643
77632
|
poll.cancel();
|
|
@@ -77702,6 +78691,337 @@ var CodexSettings = class {
|
|
|
77702
78691
|
};
|
|
77703
78692
|
};
|
|
77704
78693
|
|
|
78694
|
+
// src/engine/acp/harness/codex/usage-quota.ts
|
|
78695
|
+
var CODEX_USAGE_REQUEST_TIMEOUT_MILLISECONDS = 2e4;
|
|
78696
|
+
var SESSION_WINDOW_MINUTES2 = 5 * 60;
|
|
78697
|
+
var WEEKLY_WINDOW_MINUTES2 = 7 * 24 * 60;
|
|
78698
|
+
var MONTHLY_WINDOW_MINUTES = 30 * 24 * 60;
|
|
78699
|
+
var rateLimitWindowSchema = external_exports.object({
|
|
78700
|
+
usedPercent: external_exports.number(),
|
|
78701
|
+
windowDurationMins: external_exports.number().nullish(),
|
|
78702
|
+
resetsAt: external_exports.number().nullish()
|
|
78703
|
+
});
|
|
78704
|
+
var creditsSnapshotSchema = external_exports.object({
|
|
78705
|
+
hasCredits: external_exports.boolean(),
|
|
78706
|
+
unlimited: external_exports.boolean(),
|
|
78707
|
+
balance: external_exports.string().nullish()
|
|
78708
|
+
});
|
|
78709
|
+
var spendControlLimitSchema = external_exports.object({
|
|
78710
|
+
remainingPercent: external_exports.number(),
|
|
78711
|
+
resetsAt: external_exports.number()
|
|
78712
|
+
});
|
|
78713
|
+
var rateLimitSnapshotSchema = external_exports.object({
|
|
78714
|
+
limitId: external_exports.string().nullish(),
|
|
78715
|
+
planType: external_exports.string().nullish(),
|
|
78716
|
+
primary: rateLimitWindowSchema.nullish(),
|
|
78717
|
+
secondary: rateLimitWindowSchema.nullish(),
|
|
78718
|
+
credits: creditsSnapshotSchema.nullish(),
|
|
78719
|
+
individualLimit: spendControlLimitSchema.nullish()
|
|
78720
|
+
});
|
|
78721
|
+
var resetCreditsSummarySchema = external_exports.object({
|
|
78722
|
+
availableCount: external_exports.number(),
|
|
78723
|
+
credits: external_exports.array(
|
|
78724
|
+
external_exports.object({
|
|
78725
|
+
status: external_exports.string(),
|
|
78726
|
+
expiresAt: external_exports.number().nullish()
|
|
78727
|
+
})
|
|
78728
|
+
).nullish()
|
|
78729
|
+
});
|
|
78730
|
+
var getAccountResponseSchema = external_exports.object({
|
|
78731
|
+
account: external_exports.union([
|
|
78732
|
+
external_exports.object({
|
|
78733
|
+
type: external_exports.literal("chatgpt"),
|
|
78734
|
+
email: external_exports.string().nullish(),
|
|
78735
|
+
planType: external_exports.string().nullish()
|
|
78736
|
+
}),
|
|
78737
|
+
external_exports.object({ type: external_exports.literal("apiKey") }),
|
|
78738
|
+
external_exports.object({ type: external_exports.literal("amazonBedrock") })
|
|
78739
|
+
]).nullish()
|
|
78740
|
+
});
|
|
78741
|
+
var getRateLimitsResponseSchema = external_exports.object({
|
|
78742
|
+
rateLimits: rateLimitSnapshotSchema,
|
|
78743
|
+
rateLimitsByLimitId: external_exports.record(external_exports.string(), rateLimitSnapshotSchema.optional()).nullish(),
|
|
78744
|
+
rateLimitResetCredits: resetCreditsSummarySchema.nullish()
|
|
78745
|
+
});
|
|
78746
|
+
var rateLimitsUpdatedNotificationSchema = external_exports.object({
|
|
78747
|
+
rateLimits: rateLimitSnapshotSchema
|
|
78748
|
+
});
|
|
78749
|
+
function clampPercent2(value) {
|
|
78750
|
+
if (!Number.isFinite(value)) {
|
|
78751
|
+
return 0;
|
|
78752
|
+
}
|
|
78753
|
+
const clamped = Math.max(0, Math.min(100, value));
|
|
78754
|
+
return Math.round(clamped * 100) / 100;
|
|
78755
|
+
}
|
|
78756
|
+
function isoFromEpochSeconds2(seconds) {
|
|
78757
|
+
if (typeof seconds !== "number" || !Number.isFinite(seconds) || seconds <= 0) {
|
|
78758
|
+
return void 0;
|
|
78759
|
+
}
|
|
78760
|
+
const date5 = new Date(seconds * 1e3);
|
|
78761
|
+
return Number.isNaN(date5.getTime()) ? void 0 : date5.toISOString();
|
|
78762
|
+
}
|
|
78763
|
+
function windowKindForMinutes(minutes) {
|
|
78764
|
+
if (minutes >= MONTHLY_WINDOW_MINUTES) {
|
|
78765
|
+
return "monthly";
|
|
78766
|
+
}
|
|
78767
|
+
if (minutes >= WEEKLY_WINDOW_MINUTES2) {
|
|
78768
|
+
return "weekly";
|
|
78769
|
+
}
|
|
78770
|
+
return "session";
|
|
78771
|
+
}
|
|
78772
|
+
function windowLabelForKind(kind) {
|
|
78773
|
+
switch (kind) {
|
|
78774
|
+
case "session":
|
|
78775
|
+
return "Session";
|
|
78776
|
+
case "weekly":
|
|
78777
|
+
return "Weekly";
|
|
78778
|
+
case "monthly":
|
|
78779
|
+
return "Monthly";
|
|
78780
|
+
case "other":
|
|
78781
|
+
return "Allowance";
|
|
78782
|
+
}
|
|
78783
|
+
}
|
|
78784
|
+
function formatPlanLabel2(planType) {
|
|
78785
|
+
if (typeof planType !== "string") {
|
|
78786
|
+
return void 0;
|
|
78787
|
+
}
|
|
78788
|
+
const normalized = planType.trim().toLowerCase();
|
|
78789
|
+
if (normalized.length === 0 || normalized === "unknown") {
|
|
78790
|
+
return void 0;
|
|
78791
|
+
}
|
|
78792
|
+
switch (normalized) {
|
|
78793
|
+
case "free":
|
|
78794
|
+
return "Free";
|
|
78795
|
+
case "go":
|
|
78796
|
+
return "Go";
|
|
78797
|
+
case "plus":
|
|
78798
|
+
return "Plus";
|
|
78799
|
+
case "pro":
|
|
78800
|
+
return "Pro";
|
|
78801
|
+
case "prolite":
|
|
78802
|
+
return "Pro Lite";
|
|
78803
|
+
case "promax":
|
|
78804
|
+
return "Pro Max";
|
|
78805
|
+
case "team":
|
|
78806
|
+
return "Team";
|
|
78807
|
+
case "business":
|
|
78808
|
+
return "Business";
|
|
78809
|
+
case "enterprise":
|
|
78810
|
+
return "Enterprise";
|
|
78811
|
+
case "edu":
|
|
78812
|
+
case "education":
|
|
78813
|
+
return "Edu";
|
|
78814
|
+
default:
|
|
78815
|
+
return normalized.slice(0, 64);
|
|
78816
|
+
}
|
|
78817
|
+
}
|
|
78818
|
+
function formatCreditsBalance(balance) {
|
|
78819
|
+
if (typeof balance !== "string") {
|
|
78820
|
+
return void 0;
|
|
78821
|
+
}
|
|
78822
|
+
const trimmed = balance.trim();
|
|
78823
|
+
if (trimmed.length === 0) {
|
|
78824
|
+
return void 0;
|
|
78825
|
+
}
|
|
78826
|
+
const numeric2 = Number(trimmed);
|
|
78827
|
+
if (!Number.isFinite(numeric2) || numeric2 <= 0) {
|
|
78828
|
+
return void 0;
|
|
78829
|
+
}
|
|
78830
|
+
const rounded = Math.round(numeric2 * 100) / 100;
|
|
78831
|
+
const formatted = Number.isInteger(rounded) ? rounded.toLocaleString("en-US") : rounded.toLocaleString("en-US");
|
|
78832
|
+
return `${formatted} credits`;
|
|
78833
|
+
}
|
|
78834
|
+
function mapCredits(credits) {
|
|
78835
|
+
if (credits === null || credits === void 0) {
|
|
78836
|
+
return void 0;
|
|
78837
|
+
}
|
|
78838
|
+
if (!credits.hasCredits && !credits.unlimited) {
|
|
78839
|
+
return void 0;
|
|
78840
|
+
}
|
|
78841
|
+
const balanceDisplay = credits.unlimited ? void 0 : formatCreditsBalance(credits.balance);
|
|
78842
|
+
if (!credits.unlimited && balanceDisplay === void 0) {
|
|
78843
|
+
return void 0;
|
|
78844
|
+
}
|
|
78845
|
+
return {
|
|
78846
|
+
unlimited: credits.unlimited,
|
|
78847
|
+
...balanceDisplay === void 0 ? {} : { balanceDisplay }
|
|
78848
|
+
};
|
|
78849
|
+
}
|
|
78850
|
+
function mapResetCredits(summary) {
|
|
78851
|
+
if (summary === null || summary === void 0) {
|
|
78852
|
+
return void 0;
|
|
78853
|
+
}
|
|
78854
|
+
const availableCount = Math.max(0, Math.floor(summary.availableCount));
|
|
78855
|
+
if (availableCount === 0) {
|
|
78856
|
+
return void 0;
|
|
78857
|
+
}
|
|
78858
|
+
const expiries = (summary.credits ?? []).filter((credit) => credit.status === "available").map((credit) => credit.expiresAt).filter((value) => typeof value === "number" && Number.isFinite(value) && value > 0);
|
|
78859
|
+
const nextExpiresAt = expiries.length > 0 ? isoFromEpochSeconds2(Math.min(...expiries)) : void 0;
|
|
78860
|
+
return {
|
|
78861
|
+
availableCount,
|
|
78862
|
+
...nextExpiresAt === void 0 ? {} : { nextExpiresAt }
|
|
78863
|
+
};
|
|
78864
|
+
}
|
|
78865
|
+
function codexSnapshotToWindows(snapshot) {
|
|
78866
|
+
if (snapshot.limitId !== null && snapshot.limitId !== void 0 && snapshot.limitId !== "codex") {
|
|
78867
|
+
return [];
|
|
78868
|
+
}
|
|
78869
|
+
const planType = snapshot.planType?.toLowerCase();
|
|
78870
|
+
const isMonthlyPlan = planType === "free" || planType === "go";
|
|
78871
|
+
const candidates = [
|
|
78872
|
+
["primary", snapshot.primary, isMonthlyPlan ? MONTHLY_WINDOW_MINUTES : SESSION_WINDOW_MINUTES2],
|
|
78873
|
+
["secondary", snapshot.secondary, WEEKLY_WINDOW_MINUTES2]
|
|
78874
|
+
];
|
|
78875
|
+
const windows = [];
|
|
78876
|
+
for (const [id, window2, fallbackMinutes] of candidates) {
|
|
78877
|
+
if (window2 === null || window2 === void 0 || !Number.isFinite(window2.usedPercent)) {
|
|
78878
|
+
continue;
|
|
78879
|
+
}
|
|
78880
|
+
const duration3 = typeof window2.windowDurationMins === "number" && Number.isFinite(window2.windowDurationMins) && window2.windowDurationMins > 0 ? Math.round(window2.windowDurationMins) : fallbackMinutes;
|
|
78881
|
+
const kind = windowKindForMinutes(duration3);
|
|
78882
|
+
const usedPercent = clampPercent2(window2.usedPercent);
|
|
78883
|
+
const remainingPercent = clampPercent2(100 - usedPercent);
|
|
78884
|
+
const resetsAt = isoFromEpochSeconds2(window2.resetsAt);
|
|
78885
|
+
windows.push({
|
|
78886
|
+
id,
|
|
78887
|
+
kind,
|
|
78888
|
+
label: windowLabelForKind(kind),
|
|
78889
|
+
usedPercent,
|
|
78890
|
+
remainingPercent,
|
|
78891
|
+
windowDurationMins: duration3,
|
|
78892
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
78893
|
+
});
|
|
78894
|
+
}
|
|
78895
|
+
if (snapshot.individualLimit !== null && snapshot.individualLimit !== void 0 && Number.isFinite(snapshot.individualLimit.remainingPercent)) {
|
|
78896
|
+
const remainingPercent = clampPercent2(snapshot.individualLimit.remainingPercent);
|
|
78897
|
+
const usedPercent = clampPercent2(100 - remainingPercent);
|
|
78898
|
+
const resetsAt = isoFromEpochSeconds2(snapshot.individualLimit.resetsAt);
|
|
78899
|
+
windows.push({
|
|
78900
|
+
id: "individual",
|
|
78901
|
+
kind: "monthly",
|
|
78902
|
+
label: "Monthly credit limit",
|
|
78903
|
+
usedPercent,
|
|
78904
|
+
remainingPercent,
|
|
78905
|
+
...resetsAt === void 0 ? {} : { resetsAt }
|
|
78906
|
+
});
|
|
78907
|
+
}
|
|
78908
|
+
return windows;
|
|
78909
|
+
}
|
|
78910
|
+
function parseCodexRateLimitsNotification(params, observedAt) {
|
|
78911
|
+
const parsed = rateLimitsUpdatedNotificationSchema.safeParse(params);
|
|
78912
|
+
if (!parsed.success) {
|
|
78913
|
+
return null;
|
|
78914
|
+
}
|
|
78915
|
+
const snapshot = parsed.data.rateLimits;
|
|
78916
|
+
const windows = codexSnapshotToWindows(snapshot);
|
|
78917
|
+
const credits = mapCredits(snapshot.credits);
|
|
78918
|
+
const plan = formatPlanLabel2(snapshot.planType);
|
|
78919
|
+
if (windows.length === 0 && credits === void 0) {
|
|
78920
|
+
return null;
|
|
78921
|
+
}
|
|
78922
|
+
return {
|
|
78923
|
+
agentId: "codex",
|
|
78924
|
+
observedAt,
|
|
78925
|
+
windows,
|
|
78926
|
+
...plan === void 0 ? {} : { plan },
|
|
78927
|
+
...credits === void 0 ? {} : { credits }
|
|
78928
|
+
};
|
|
78929
|
+
}
|
|
78930
|
+
async function readCodexUsageQuota(options) {
|
|
78931
|
+
options.signal.throwIfAborted();
|
|
78932
|
+
const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
78933
|
+
const client2 = new CodexAppServerClient({
|
|
78934
|
+
command: options.command,
|
|
78935
|
+
cwd: options.cwd,
|
|
78936
|
+
environment: options.environment,
|
|
78937
|
+
handlers: {
|
|
78938
|
+
onNotification: async () => void 0,
|
|
78939
|
+
onServerRequest: async (request) => {
|
|
78940
|
+
client2.respondWithError(request.id, -32601, "Method not supported during usage probe");
|
|
78941
|
+
}
|
|
78942
|
+
}
|
|
78943
|
+
});
|
|
78944
|
+
const processTreePromise = captureProcessTree(client2.child()).catch(() => []);
|
|
78945
|
+
const requestSignal = AbortSignal.any([
|
|
78946
|
+
options.signal,
|
|
78947
|
+
AbortSignal.timeout(CODEX_USAGE_REQUEST_TIMEOUT_MILLISECONDS)
|
|
78948
|
+
]);
|
|
78949
|
+
try {
|
|
78950
|
+
await client2.initialize(requestSignal);
|
|
78951
|
+
const rawAccount = await client2.request("account/read", { refreshToken: false }, requestSignal);
|
|
78952
|
+
const accountResponse = getAccountResponseSchema.safeParse(rawAccount);
|
|
78953
|
+
if (accountResponse.success) {
|
|
78954
|
+
const account = accountResponse.data.account;
|
|
78955
|
+
if (account === null || account === void 0) {
|
|
78956
|
+
return {
|
|
78957
|
+
agentId: "codex",
|
|
78958
|
+
status: "unauthenticated",
|
|
78959
|
+
checkedAt,
|
|
78960
|
+
message: "Sign in to Codex on this computer to view subscription quotas."
|
|
78961
|
+
};
|
|
78962
|
+
}
|
|
78963
|
+
if (account.type === "apiKey" || account.type === "amazonBedrock") {
|
|
78964
|
+
return {
|
|
78965
|
+
agentId: "codex",
|
|
78966
|
+
status: "unsupported",
|
|
78967
|
+
checkedAt,
|
|
78968
|
+
reason: "api_key",
|
|
78969
|
+
message: "Codex is using API credentials without a subscription quota."
|
|
78970
|
+
};
|
|
78971
|
+
}
|
|
78972
|
+
const rawLimits2 = await client2.request("account/rateLimits/read", null, requestSignal);
|
|
78973
|
+
const limitsResponse2 = getRateLimitsResponseSchema.parse(rawLimits2);
|
|
78974
|
+
const mainSnapshot2 = limitsResponse2.rateLimitsByLimitId?.["codex"] ?? limitsResponse2.rateLimits;
|
|
78975
|
+
const windows = codexSnapshotToWindows(mainSnapshot2);
|
|
78976
|
+
const plan2 = formatPlanLabel2(account.planType ?? mainSnapshot2.planType);
|
|
78977
|
+
const email3 = account.email?.trim();
|
|
78978
|
+
const credits2 = mapCredits(mainSnapshot2.credits);
|
|
78979
|
+
const resetCredits2 = mapResetCredits(limitsResponse2.rateLimitResetCredits);
|
|
78980
|
+
return {
|
|
78981
|
+
agentId: "codex",
|
|
78982
|
+
status: "available",
|
|
78983
|
+
checkedAt,
|
|
78984
|
+
...plan2 === void 0 ? {} : { plan: plan2 },
|
|
78985
|
+
...email3 === void 0 || email3.length === 0 ? {} : { accountLabel: email3.slice(0, 128) },
|
|
78986
|
+
windows,
|
|
78987
|
+
...credits2 === void 0 ? {} : { credits: credits2 },
|
|
78988
|
+
...resetCredits2 === void 0 ? {} : { resetCredits: resetCredits2 }
|
|
78989
|
+
};
|
|
78990
|
+
}
|
|
78991
|
+
const rawLimits = await client2.request("account/rateLimits/read", null, requestSignal);
|
|
78992
|
+
const limitsResponse = getRateLimitsResponseSchema.parse(rawLimits);
|
|
78993
|
+
const mainSnapshot = limitsResponse.rateLimitsByLimitId?.["codex"] ?? limitsResponse.rateLimits;
|
|
78994
|
+
const plan = formatPlanLabel2(mainSnapshot.planType);
|
|
78995
|
+
const credits = mapCredits(mainSnapshot.credits);
|
|
78996
|
+
const resetCredits = mapResetCredits(limitsResponse.rateLimitResetCredits);
|
|
78997
|
+
return {
|
|
78998
|
+
agentId: "codex",
|
|
78999
|
+
status: "available",
|
|
79000
|
+
checkedAt,
|
|
79001
|
+
...plan === void 0 ? {} : { plan },
|
|
79002
|
+
windows: codexSnapshotToWindows(mainSnapshot),
|
|
79003
|
+
...credits === void 0 ? {} : { credits },
|
|
79004
|
+
...resetCredits === void 0 ? {} : { resetCredits }
|
|
79005
|
+
};
|
|
79006
|
+
} catch (error62) {
|
|
79007
|
+
if (options.signal.aborted) {
|
|
79008
|
+
throw options.signal.reason ?? error62;
|
|
79009
|
+
}
|
|
79010
|
+
const errorCode = error62 instanceof CodexAppServerError ? error62.code : requestSignal.aborted ? "usage_probe_timeout" : "codex_usage_probe_failed";
|
|
79011
|
+
const errorMessage = requestSignal.aborted ? "Codex did not answer the usage quota request in time." : error62 instanceof CodexAppServerError ? error62.message.slice(0, 256) : "Codex could not report subscription usage quotas.";
|
|
79012
|
+
return {
|
|
79013
|
+
agentId: "codex",
|
|
79014
|
+
status: "unavailable",
|
|
79015
|
+
checkedAt,
|
|
79016
|
+
errorCode,
|
|
79017
|
+
errorMessage
|
|
79018
|
+
};
|
|
79019
|
+
} finally {
|
|
79020
|
+
client2.detach();
|
|
79021
|
+
await stopProcessTree(client2.child(), await processTreePromise).catch(() => void 0);
|
|
79022
|
+
}
|
|
79023
|
+
}
|
|
79024
|
+
|
|
77705
79025
|
// src/engine/acp/harness/codex/agent.ts
|
|
77706
79026
|
import { randomUUID as randomUUID10 } from "node:crypto";
|
|
77707
79027
|
var APPROVAL_TIMEOUT_MILLISECONDS3 = 36e5;
|
|
@@ -77753,6 +79073,7 @@ var CodexAcpAgent = class {
|
|
|
77753
79073
|
#onBackgroundActivity;
|
|
77754
79074
|
#onPromptDelegation;
|
|
77755
79075
|
#onPromptSuggestion;
|
|
79076
|
+
#onUsageQuota;
|
|
77756
79077
|
/** Whether this app-server serves `thread/sample`, which predicts the member's next prompt. */
|
|
77757
79078
|
#promptSampling = false;
|
|
77758
79079
|
#nativeSessionId = "";
|
|
@@ -77763,12 +79084,19 @@ var CodexAcpAgent = class {
|
|
|
77763
79084
|
this.#onBackgroundActivity = options.onBackgroundActivity;
|
|
77764
79085
|
this.#onPromptDelegation = options.onPromptDelegation;
|
|
77765
79086
|
this.#onPromptSuggestion = options.onPromptSuggestion;
|
|
79087
|
+
this.#onUsageQuota = options.onUsageQuota;
|
|
77766
79088
|
this.#appServer = new CodexAppServerClient({
|
|
77767
79089
|
command: options.command,
|
|
77768
79090
|
cwd: options.cwd,
|
|
77769
79091
|
environment: options.environment,
|
|
77770
79092
|
handlers: {
|
|
77771
79093
|
onNotification: async (method, params) => {
|
|
79094
|
+
if (method === "account/rateLimits/updated" && this.#closePromise === null) {
|
|
79095
|
+
const report = parseCodexRateLimitsNotification(params, (/* @__PURE__ */ new Date()).toISOString());
|
|
79096
|
+
if (report !== null) {
|
|
79097
|
+
this.#onUsageQuota?.(report);
|
|
79098
|
+
}
|
|
79099
|
+
}
|
|
77772
79100
|
await this.#sessionAgent.onNotification(method, params);
|
|
77773
79101
|
},
|
|
77774
79102
|
onServerRequest: async (request) => {
|
|
@@ -78076,7 +79404,8 @@ var CodexAgentConnection = class extends EndpointAgentConnection {
|
|
|
78076
79404
|
onSessionUpdate: options.client.onUpdate,
|
|
78077
79405
|
onBackgroundActivity: (activity) => options.onBackgroundActivity?.(activity),
|
|
78078
79406
|
onPromptDelegation: async (stage) => await options.onPromptDelegation?.(stage),
|
|
78079
|
-
onPromptSuggestion: (report) => options.onPromptSuggestion?.(report)
|
|
79407
|
+
onPromptSuggestion: (report) => options.onPromptSuggestion?.(report),
|
|
79408
|
+
onUsageQuota: (report) => options.onUsageQuota?.(report)
|
|
78080
79409
|
});
|
|
78081
79410
|
super(endpoint, options.client);
|
|
78082
79411
|
}
|
|
@@ -78107,7 +79436,7 @@ import { existsSync as existsSync8, readdirSync as readdirSync6, readFileSync as
|
|
|
78107
79436
|
import { basename as basename6, dirname as dirname8, isAbsolute as isAbsolute13, join as join22 } from "node:path";
|
|
78108
79437
|
|
|
78109
79438
|
// src/engine/acp/harness/pi/upstream/dist/pi-rpc/process.js
|
|
78110
|
-
import { spawn as
|
|
79439
|
+
import { spawn as spawn7 } from "node:child_process";
|
|
78111
79440
|
import * as readline from "node:readline";
|
|
78112
79441
|
|
|
78113
79442
|
// src/engine/acp/harness/pi/upstream/dist/pi-rpc/command.js
|
|
@@ -78224,17 +79553,17 @@ var PiRpcProcess = class _PiRpcProcess {
|
|
|
78224
79553
|
args.push("--fork", params.origin.sessionPath);
|
|
78225
79554
|
break;
|
|
78226
79555
|
}
|
|
78227
|
-
const child =
|
|
79556
|
+
const child = spawn7(cmd, args, {
|
|
78228
79557
|
cwd: params.cwd,
|
|
78229
79558
|
stdio: "pipe",
|
|
78230
79559
|
env: params.environment,
|
|
78231
79560
|
shell: shouldUseShellForPiCommand(cmd)
|
|
78232
79561
|
});
|
|
78233
79562
|
try {
|
|
78234
|
-
await new Promise((
|
|
79563
|
+
await new Promise((resolve21, reject2) => {
|
|
78235
79564
|
const onSpawn = () => {
|
|
78236
79565
|
cleanup();
|
|
78237
|
-
|
|
79566
|
+
resolve21();
|
|
78238
79567
|
};
|
|
78239
79568
|
const onError = (err) => {
|
|
78240
79569
|
cleanup();
|
|
@@ -78436,7 +79765,7 @@ var PiRpcProcess = class _PiRpcProcess {
|
|
|
78436
79765
|
const timeoutMs = opts?.timeoutMs;
|
|
78437
79766
|
const line = `${JSON.stringify(withId)}
|
|
78438
79767
|
`;
|
|
78439
|
-
return new Promise((
|
|
79768
|
+
return new Promise((resolve21, reject2) => {
|
|
78440
79769
|
const signal = opts?.signal;
|
|
78441
79770
|
if (signal?.aborted === true) {
|
|
78442
79771
|
reject2(signal.reason);
|
|
@@ -78458,7 +79787,7 @@ var PiRpcProcess = class _PiRpcProcess {
|
|
|
78458
79787
|
this.pending.set(id, {
|
|
78459
79788
|
resolve: (res) => {
|
|
78460
79789
|
drop();
|
|
78461
|
-
|
|
79790
|
+
resolve21(res);
|
|
78462
79791
|
},
|
|
78463
79792
|
reject: (error62) => {
|
|
78464
79793
|
drop();
|
|
@@ -78491,14 +79820,14 @@ var PiRpcProcess = class _PiRpcProcess {
|
|
|
78491
79820
|
});
|
|
78492
79821
|
}
|
|
78493
79822
|
writeLine(line) {
|
|
78494
|
-
return new Promise((
|
|
79823
|
+
return new Promise((resolve21, reject2) => {
|
|
78495
79824
|
try {
|
|
78496
79825
|
this.child.stdin.write(line, (error62) => {
|
|
78497
79826
|
if (error62) {
|
|
78498
79827
|
reject2(error62);
|
|
78499
79828
|
return;
|
|
78500
79829
|
}
|
|
78501
|
-
|
|
79830
|
+
resolve21();
|
|
78502
79831
|
});
|
|
78503
79832
|
} catch (error62) {
|
|
78504
79833
|
reject2(error62);
|
|
@@ -79853,8 +81182,8 @@ var PiAcpSession = class {
|
|
|
79853
81182
|
}
|
|
79854
81183
|
async prompt(message, images = []) {
|
|
79855
81184
|
const expandedMessage = expandSlashCommand(message, this.fileCommands);
|
|
79856
|
-
const turnPromise = new Promise((
|
|
79857
|
-
const queued = { message: expandedMessage, images, resolve:
|
|
81185
|
+
const turnPromise = new Promise((resolve21, reject2) => {
|
|
81186
|
+
const queued = { message: expandedMessage, images, resolve: resolve21, reject: reject2 };
|
|
79858
81187
|
if (this.pendingTurn) {
|
|
79859
81188
|
this.turnQueue.push(queued);
|
|
79860
81189
|
this.emit({
|
|
@@ -82886,8 +84215,8 @@ var AdapterRegistry = class {
|
|
|
82886
84215
|
#resolve;
|
|
82887
84216
|
#dependencies;
|
|
82888
84217
|
#adapters = /* @__PURE__ */ new Map();
|
|
82889
|
-
constructor(
|
|
82890
|
-
this.#resolve =
|
|
84218
|
+
constructor(resolve21, dependencies) {
|
|
84219
|
+
this.#resolve = resolve21;
|
|
82891
84220
|
this.#dependencies = dependencies;
|
|
82892
84221
|
}
|
|
82893
84222
|
resolve = (agent2) => {
|
|
@@ -82919,11 +84248,615 @@ async function runCleanup(...actions) {
|
|
|
82919
84248
|
}
|
|
82920
84249
|
}
|
|
82921
84250
|
|
|
84251
|
+
// src/engine/acp/harness/antigravity/usage-quota.ts
|
|
84252
|
+
import { spawn as spawn8 } from "node:child_process";
|
|
84253
|
+
import { fetch as fetch2 } from "undici";
|
|
84254
|
+
|
|
84255
|
+
// src/engine/storage/antigravity-usage-credentials.ts
|
|
84256
|
+
import { readFile as readFile7 } from "node:fs/promises";
|
|
84257
|
+
import { homedir as homedir4 } from "node:os";
|
|
84258
|
+
import { join as join24, resolve as resolve14 } from "node:path";
|
|
84259
|
+
var agyOAuthTokenFileSchema = external_exports.object({
|
|
84260
|
+
auth_method: external_exports.string().optional(),
|
|
84261
|
+
id_token_email: external_exports.string().optional(),
|
|
84262
|
+
token: external_exports.object({
|
|
84263
|
+
access_token: external_exports.string().min(1),
|
|
84264
|
+
expiry: external_exports.string().optional(),
|
|
84265
|
+
refresh_token: external_exports.string().optional()
|
|
84266
|
+
})
|
|
84267
|
+
});
|
|
84268
|
+
var acpTokenFileSchema = external_exports.object({
|
|
84269
|
+
client_id: external_exports.string().min(1),
|
|
84270
|
+
client_secret: external_exports.string().min(1),
|
|
84271
|
+
refresh_token: external_exports.string().min(1),
|
|
84272
|
+
project_id: external_exports.string().optional()
|
|
84273
|
+
});
|
|
84274
|
+
var gatewaySettingsSchema = external_exports.object({
|
|
84275
|
+
gateway: external_exports.object({
|
|
84276
|
+
enabled: external_exports.boolean().optional()
|
|
84277
|
+
}).optional()
|
|
84278
|
+
});
|
|
84279
|
+
async function readTextIfPresent(filePath) {
|
|
84280
|
+
try {
|
|
84281
|
+
return await readFile7(filePath, "utf8");
|
|
84282
|
+
} catch {
|
|
84283
|
+
return null;
|
|
84284
|
+
}
|
|
84285
|
+
}
|
|
84286
|
+
function resolveGeminiHome2(environment) {
|
|
84287
|
+
const configured = environment["GEMINI_HOME"]?.trim();
|
|
84288
|
+
if (configured !== void 0 && configured.length > 0) {
|
|
84289
|
+
return resolve14(configured);
|
|
84290
|
+
}
|
|
84291
|
+
const home = environment["HOME"]?.trim() || environment["USERPROFILE"]?.trim() || homedir4();
|
|
84292
|
+
return join24(resolve14(home), ".gemini");
|
|
84293
|
+
}
|
|
84294
|
+
function classifyAuthMethod(raw) {
|
|
84295
|
+
const normalized = raw?.trim().toLowerCase() ?? "";
|
|
84296
|
+
if (normalized === "oauth-business" || normalized === "business" || normalized === "enterprise" || normalized === "gcp") {
|
|
84297
|
+
return "business";
|
|
84298
|
+
}
|
|
84299
|
+
return "consumer";
|
|
84300
|
+
}
|
|
84301
|
+
function hasGatewayEnabled(rawJson) {
|
|
84302
|
+
if (rawJson === null) {
|
|
84303
|
+
return false;
|
|
84304
|
+
}
|
|
84305
|
+
try {
|
|
84306
|
+
const parsed = gatewaySettingsSchema.safeParse(JSON.parse(rawJson));
|
|
84307
|
+
return parsed.success && parsed.data.gateway?.enabled === true;
|
|
84308
|
+
} catch {
|
|
84309
|
+
return false;
|
|
84310
|
+
}
|
|
84311
|
+
}
|
|
84312
|
+
async function readAntigravityStoredCredentials(environment) {
|
|
84313
|
+
const apiKey = environment["GEMINI_API_KEY"]?.trim() || environment["GOOGLE_API_KEY"]?.trim();
|
|
84314
|
+
if (apiKey !== void 0 && apiKey.length > 0) {
|
|
84315
|
+
return {
|
|
84316
|
+
kind: "api_key_or_gateway",
|
|
84317
|
+
message: "Antigravity is using an API key without a subscription quota."
|
|
84318
|
+
};
|
|
84319
|
+
}
|
|
84320
|
+
if (environment["AGY_LLM_GATEWAY_ENABLED"]?.trim().toLowerCase() === "true") {
|
|
84321
|
+
return {
|
|
84322
|
+
kind: "api_key_or_gateway",
|
|
84323
|
+
message: "Antigravity is configured to use a custom LLM gateway without a Google subscription quota."
|
|
84324
|
+
};
|
|
84325
|
+
}
|
|
84326
|
+
const geminiHome = resolveGeminiHome2(environment);
|
|
84327
|
+
const cliDir = join24(geminiHome, "antigravity-cli");
|
|
84328
|
+
const [cliSettingsRaw, sharedConfigRaw] = await Promise.all([
|
|
84329
|
+
readTextIfPresent(join24(cliDir, "settings.json")),
|
|
84330
|
+
readTextIfPresent(join24(geminiHome, "config", "config.json"))
|
|
84331
|
+
]);
|
|
84332
|
+
if (hasGatewayEnabled(cliSettingsRaw) || hasGatewayEnabled(sharedConfigRaw)) {
|
|
84333
|
+
return {
|
|
84334
|
+
kind: "api_key_or_gateway",
|
|
84335
|
+
message: "Antigravity is configured to use a custom LLM gateway without a Google subscription quota."
|
|
84336
|
+
};
|
|
84337
|
+
}
|
|
84338
|
+
const projectFromEnv = environment["ANTIGRAVITY_PROJECT_ID"]?.trim() || environment["AGY_ACP_CCPA_PROJECT"]?.trim() || environment["GOOGLE_CLOUD_PROJECT"]?.trim();
|
|
84339
|
+
const projectFromCache = (await readTextIfPresent(join24(cliDir, "cache", "default_project_id.txt")))?.trim();
|
|
84340
|
+
const fallbackProjectId = projectFromEnv !== void 0 && projectFromEnv.length > 0 ? projectFromEnv : projectFromCache !== void 0 && projectFromCache.length > 0 ? projectFromCache : void 0;
|
|
84341
|
+
const agyTokenRaw = await readTextIfPresent(join24(cliDir, "antigravity-oauth-token"));
|
|
84342
|
+
if (agyTokenRaw !== null) {
|
|
84343
|
+
try {
|
|
84344
|
+
const parsed = agyOAuthTokenFileSchema.safeParse(JSON.parse(agyTokenRaw));
|
|
84345
|
+
if (parsed.success) {
|
|
84346
|
+
const expiryMs = parsed.data.token.expiry === void 0 ? Number.NaN : Date.parse(parsed.data.token.expiry);
|
|
84347
|
+
const email3 = parsed.data.id_token_email?.trim();
|
|
84348
|
+
return {
|
|
84349
|
+
kind: "agy_oauth",
|
|
84350
|
+
authMethod: classifyAuthMethod(parsed.data.auth_method),
|
|
84351
|
+
accessToken: parsed.data.token.access_token,
|
|
84352
|
+
expiresAtMs: Number.isFinite(expiryMs) ? expiryMs : null,
|
|
84353
|
+
...email3 === void 0 || email3.length === 0 ? {} : { email: email3 },
|
|
84354
|
+
...fallbackProjectId === void 0 ? {} : { projectId: fallbackProjectId }
|
|
84355
|
+
};
|
|
84356
|
+
}
|
|
84357
|
+
} catch {
|
|
84358
|
+
}
|
|
84359
|
+
}
|
|
84360
|
+
const acpTokenRaw = await readTextIfPresent(join24(geminiHome, "antigravity-acp", "acp_token.json"));
|
|
84361
|
+
if (acpTokenRaw !== null) {
|
|
84362
|
+
try {
|
|
84363
|
+
const parsed = acpTokenFileSchema.safeParse(JSON.parse(acpTokenRaw));
|
|
84364
|
+
if (parsed.success) {
|
|
84365
|
+
const projectId = parsed.data.project_id?.trim() || fallbackProjectId;
|
|
84366
|
+
return {
|
|
84367
|
+
kind: "acp_token",
|
|
84368
|
+
authMethod: "consumer",
|
|
84369
|
+
clientId: parsed.data.client_id,
|
|
84370
|
+
clientSecret: parsed.data.client_secret,
|
|
84371
|
+
refreshToken: parsed.data.refresh_token,
|
|
84372
|
+
...projectId === void 0 || projectId.length === 0 ? {} : { projectId }
|
|
84373
|
+
};
|
|
84374
|
+
}
|
|
84375
|
+
} catch {
|
|
84376
|
+
}
|
|
84377
|
+
}
|
|
84378
|
+
return { kind: "unauthenticated" };
|
|
84379
|
+
}
|
|
84380
|
+
|
|
84381
|
+
// src/engine/util/network/environment-proxy.ts
|
|
84382
|
+
import { EnvHttpProxyAgent } from "undici";
|
|
84383
|
+
var configuredHttpProxy = process.env["http_proxy"] ?? process.env["HTTP_PROXY"] ?? "";
|
|
84384
|
+
var configuredHttpsProxy = process.env["https_proxy"] ?? process.env["HTTPS_PROXY"] ?? configuredHttpProxy;
|
|
84385
|
+
var environmentProxyDispatcher = new EnvHttpProxyAgent();
|
|
84386
|
+
function bypassesProxy(target) {
|
|
84387
|
+
const noProxy = process.env["no_proxy"] ?? process.env["NO_PROXY"] ?? "";
|
|
84388
|
+
if (noProxy === "*") {
|
|
84389
|
+
return true;
|
|
84390
|
+
}
|
|
84391
|
+
const hostname4 = target.hostname.replace(/^\[|\]$/gu, "").toLowerCase();
|
|
84392
|
+
const defaultPort = target.protocol === "wss:" || target.protocol === "https:" ? 443 : 80;
|
|
84393
|
+
const port = Number.parseInt(target.port, 10) || defaultPort;
|
|
84394
|
+
for (const rawEntry of noProxy.split(/[,\s]/u)) {
|
|
84395
|
+
if (rawEntry.length === 0) {
|
|
84396
|
+
continue;
|
|
84397
|
+
}
|
|
84398
|
+
const parsed = rawEntry.match(/^(.+):(\d+)$/u);
|
|
84399
|
+
const entryHostname = (parsed?.[1] ?? rawEntry).replace(/^\*?\./u, "").toLowerCase();
|
|
84400
|
+
const entryPort = parsed?.[2] === void 0 ? 0 : Number.parseInt(parsed[2], 10);
|
|
84401
|
+
if (entryPort !== 0 && entryPort !== port) {
|
|
84402
|
+
continue;
|
|
84403
|
+
}
|
|
84404
|
+
if (hostname4 === entryHostname || hostname4.endsWith(`.${entryHostname}`)) {
|
|
84405
|
+
return true;
|
|
84406
|
+
}
|
|
84407
|
+
}
|
|
84408
|
+
return false;
|
|
84409
|
+
}
|
|
84410
|
+
function sanitizedProxyOrigin(proxyUrl) {
|
|
84411
|
+
try {
|
|
84412
|
+
return new URL(proxyUrl).origin;
|
|
84413
|
+
} catch {
|
|
84414
|
+
return "configured-invalid-url";
|
|
84415
|
+
}
|
|
84416
|
+
}
|
|
84417
|
+
function describeEnvironmentProxyRoute(target) {
|
|
84418
|
+
if (bypassesProxy(target)) {
|
|
84419
|
+
return { proxyRoute: "direct" };
|
|
84420
|
+
}
|
|
84421
|
+
const proxyUrl = target.protocol === "wss:" || target.protocol === "https:" ? configuredHttpsProxy : configuredHttpProxy;
|
|
84422
|
+
if (proxyUrl.length === 0) {
|
|
84423
|
+
return { proxyRoute: "direct" };
|
|
84424
|
+
}
|
|
84425
|
+
return {
|
|
84426
|
+
proxyOrigin: sanitizedProxyOrigin(proxyUrl),
|
|
84427
|
+
proxyRoute: "proxy"
|
|
84428
|
+
};
|
|
84429
|
+
}
|
|
84430
|
+
|
|
84431
|
+
// src/engine/acp/harness/antigravity/usage-quota.ts
|
|
84432
|
+
var DAILY_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
|
|
84433
|
+
var PROD_ENDPOINT = "https://cloudcode-pa.googleapis.com";
|
|
84434
|
+
var OAUTH_TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
84435
|
+
var HTTP_TIMEOUT_MILLISECONDS = 1e4;
|
|
84436
|
+
var TOKEN_REFRESH_CLI_TIMEOUT_MILLISECONDS = 15e3;
|
|
84437
|
+
var TOKEN_EXPIRY_MARGIN_MILLISECONDS = 6e4;
|
|
84438
|
+
var SESSION_WINDOW_MINUTES3 = 5 * 60;
|
|
84439
|
+
var WEEKLY_WINDOW_MINUTES3 = 7 * 24 * 60;
|
|
84440
|
+
var UNTOUCHED_RESET_TOLERANCE_MILLISECONDS = 6e4;
|
|
84441
|
+
var tokenResponseSchema = external_exports.object({
|
|
84442
|
+
access_token: external_exports.string().min(1),
|
|
84443
|
+
expires_in: external_exports.number().positive()
|
|
84444
|
+
});
|
|
84445
|
+
var quotaSchema = external_exports.object({
|
|
84446
|
+
remainingFraction: external_exports.number().optional(),
|
|
84447
|
+
resetTime: external_exports.string().optional()
|
|
84448
|
+
});
|
|
84449
|
+
var bucketSchema = quotaSchema.extend({
|
|
84450
|
+
bucketId: external_exports.string().min(1),
|
|
84451
|
+
window: external_exports.string().optional(),
|
|
84452
|
+
displayName: external_exports.string().optional(),
|
|
84453
|
+
description: external_exports.string().optional(),
|
|
84454
|
+
disabled: external_exports.boolean().optional()
|
|
84455
|
+
});
|
|
84456
|
+
var summarySchema = external_exports.object({
|
|
84457
|
+
groups: external_exports.array(
|
|
84458
|
+
external_exports.object({
|
|
84459
|
+
displayName: external_exports.string().optional(),
|
|
84460
|
+
buckets: external_exports.array(bucketSchema).optional()
|
|
84461
|
+
})
|
|
84462
|
+
).optional(),
|
|
84463
|
+
buckets: external_exports.array(bucketSchema).optional()
|
|
84464
|
+
});
|
|
84465
|
+
var availableModelsSchema = external_exports.object({
|
|
84466
|
+
models: external_exports.record(
|
|
84467
|
+
external_exports.string(),
|
|
84468
|
+
external_exports.object({
|
|
84469
|
+
modelProvider: external_exports.string().optional(),
|
|
84470
|
+
quotaInfo: quotaSchema.optional(),
|
|
84471
|
+
weeklyQuotaInfo: quotaSchema.optional()
|
|
84472
|
+
})
|
|
84473
|
+
)
|
|
84474
|
+
});
|
|
84475
|
+
function antigravityUserAgent() {
|
|
84476
|
+
return `antigravity/hub/2.24.0 (aidev_client; os_type=${process.platform}; arch=${process.arch}; cl=963137146)`;
|
|
84477
|
+
}
|
|
84478
|
+
function clampPercent3(value) {
|
|
84479
|
+
if (!Number.isFinite(value)) {
|
|
84480
|
+
return 0;
|
|
84481
|
+
}
|
|
84482
|
+
const clamped = Math.max(0, Math.min(100, value));
|
|
84483
|
+
return Math.round(clamped * 100) / 100;
|
|
84484
|
+
}
|
|
84485
|
+
function normalizeIsoTimestamp2(value) {
|
|
84486
|
+
if (value === void 0 || value.trim().length === 0) {
|
|
84487
|
+
return void 0;
|
|
84488
|
+
}
|
|
84489
|
+
const parsed = Date.parse(value);
|
|
84490
|
+
return Number.isFinite(parsed) ? new Date(parsed).toISOString() : void 0;
|
|
84491
|
+
}
|
|
84492
|
+
function summaryWindowMinutes(windowName) {
|
|
84493
|
+
const normalized = windowName?.trim().toLowerCase();
|
|
84494
|
+
if (normalized === "5h") {
|
|
84495
|
+
return SESSION_WINDOW_MINUTES3;
|
|
84496
|
+
}
|
|
84497
|
+
if (normalized === "weekly") {
|
|
84498
|
+
return WEEKLY_WINDOW_MINUTES3;
|
|
84499
|
+
}
|
|
84500
|
+
return void 0;
|
|
84501
|
+
}
|
|
84502
|
+
function summaryResetTime(bucket, windowDurationMins, requestedAtMs) {
|
|
84503
|
+
const parsedReset = bucket.resetTime === void 0 ? Number.NaN : Date.parse(bucket.resetTime);
|
|
84504
|
+
const untouched = bucket.remainingFraction === 1 && bucket.description === void 0 && windowDurationMins !== void 0 && Number.isFinite(parsedReset) && Math.abs(parsedReset - requestedAtMs - windowDurationMins * 6e4) <= UNTOUCHED_RESET_TOLERANCE_MILLISECONDS;
|
|
84505
|
+
return untouched ? void 0 : normalizeIsoTimestamp2(bucket.resetTime);
|
|
84506
|
+
}
|
|
84507
|
+
function quotaToWindow(params) {
|
|
84508
|
+
const parsedReset = normalizeIsoTimestamp2(params.quota.resetTime);
|
|
84509
|
+
const remainingFraction = params.quota.remainingFraction ?? (parsedReset !== void 0 ? 0 : void 0);
|
|
84510
|
+
if (remainingFraction === void 0 || !Number.isFinite(remainingFraction)) {
|
|
84511
|
+
return void 0;
|
|
84512
|
+
}
|
|
84513
|
+
const clampedRemaining = Math.max(0, Math.min(1, remainingFraction));
|
|
84514
|
+
const remainingPercent = clampPercent3(clampedRemaining * 100);
|
|
84515
|
+
const usedPercent = clampPercent3(100 - remainingPercent);
|
|
84516
|
+
const resetsAt = "resetsAtOverride" in params ? params.resetsAtOverride : parsedReset;
|
|
84517
|
+
return {
|
|
84518
|
+
id: params.id,
|
|
84519
|
+
kind: params.kind,
|
|
84520
|
+
label: params.label,
|
|
84521
|
+
...params.group === void 0 ? {} : { group: params.group },
|
|
84522
|
+
usedPercent,
|
|
84523
|
+
remainingPercent,
|
|
84524
|
+
...resetsAt === void 0 ? {} : { resetsAt },
|
|
84525
|
+
...params.windowDurationMins === void 0 ? {} : { windowDurationMins: params.windowDurationMins }
|
|
84526
|
+
};
|
|
84527
|
+
}
|
|
84528
|
+
function parseSummaryWindows(raw, requestedAtMs) {
|
|
84529
|
+
const parsed = summarySchema.safeParse(raw);
|
|
84530
|
+
if (!parsed.success) {
|
|
84531
|
+
return [];
|
|
84532
|
+
}
|
|
84533
|
+
const summary = parsed.data;
|
|
84534
|
+
const groups = summary.groups?.some((group) => (group.buckets?.length ?? 0) > 0) ? summary.groups : [{ displayName: void 0, buckets: summary.buckets }];
|
|
84535
|
+
const windows = /* @__PURE__ */ new Map();
|
|
84536
|
+
for (const group of groups) {
|
|
84537
|
+
for (const bucket of group.buckets ?? []) {
|
|
84538
|
+
if (bucket.disabled === true) {
|
|
84539
|
+
continue;
|
|
84540
|
+
}
|
|
84541
|
+
const family = bucket.bucketId.startsWith("gemini-argon-") ? group.displayName?.trim() || "Gemini Argon" : bucket.bucketId.startsWith("gemini-carbon-") ? group.displayName?.trim() || "Gemini Carbon" : bucket.bucketId.startsWith("gemini-") ? "Gemini" : bucket.bucketId.startsWith("3p-") ? "Claude & GPT (shared)" : group.displayName?.trim() || bucket.bucketId;
|
|
84542
|
+
const normalizedWindow = bucket.window?.trim().toLowerCase();
|
|
84543
|
+
const isWeekly = normalizedWindow === "weekly";
|
|
84544
|
+
const isSession = normalizedWindow === "5h";
|
|
84545
|
+
const windowDurationMins = summaryWindowMinutes(bucket.window);
|
|
84546
|
+
const suffix = isWeekly ? "Weekly" : isSession ? "5-hour" : bucket.displayName?.trim() || "Quota";
|
|
84547
|
+
const window2 = quotaToWindow({
|
|
84548
|
+
id: bucket.bucketId,
|
|
84549
|
+
label: `${family} \xB7 ${suffix}`,
|
|
84550
|
+
group: family,
|
|
84551
|
+
quota: bucket,
|
|
84552
|
+
kind: isWeekly ? "weekly" : isSession ? "session" : "other",
|
|
84553
|
+
...windowDurationMins === void 0 ? {} : { windowDurationMins },
|
|
84554
|
+
resetsAtOverride: summaryResetTime(bucket, windowDurationMins, requestedAtMs)
|
|
84555
|
+
});
|
|
84556
|
+
if (window2 !== void 0) {
|
|
84557
|
+
windows.set(window2.id, window2);
|
|
84558
|
+
}
|
|
84559
|
+
}
|
|
84560
|
+
}
|
|
84561
|
+
return [...windows.values()];
|
|
84562
|
+
}
|
|
84563
|
+
function parseModelWindows(raw) {
|
|
84564
|
+
const parsed = availableModelsSchema.safeParse(raw);
|
|
84565
|
+
if (!parsed.success) {
|
|
84566
|
+
return [];
|
|
84567
|
+
}
|
|
84568
|
+
const windows = /* @__PURE__ */ new Map();
|
|
84569
|
+
for (const [modelId, model] of Object.entries(parsed.data.models)) {
|
|
84570
|
+
const family = model.modelProvider === "MODEL_PROVIDER_GOOGLE" || modelId.startsWith("gemini-") ? "Gemini" : model.modelProvider === "MODEL_PROVIDER_ANTHROPIC" || modelId.startsWith("claude-") ? "Claude" : model.modelProvider === "MODEL_PROVIDER_OPENAI" || modelId.startsWith("gpt-") ? "GPT" : void 0;
|
|
84571
|
+
if (family === void 0) {
|
|
84572
|
+
continue;
|
|
84573
|
+
}
|
|
84574
|
+
const pairs = [
|
|
84575
|
+
["quota", model.quotaInfo],
|
|
84576
|
+
["weekly", model.weeklyQuotaInfo]
|
|
84577
|
+
];
|
|
84578
|
+
for (const [suffix, quota] of pairs) {
|
|
84579
|
+
if (quota === void 0) {
|
|
84580
|
+
continue;
|
|
84581
|
+
}
|
|
84582
|
+
const window2 = quotaToWindow({
|
|
84583
|
+
id: `${family.toLowerCase()}-${suffix}`,
|
|
84584
|
+
label: `${family} \xB7 ${suffix === "weekly" ? "Weekly" : "Reported quota"}`,
|
|
84585
|
+
group: family,
|
|
84586
|
+
quota,
|
|
84587
|
+
kind: suffix === "weekly" ? "weekly" : "other",
|
|
84588
|
+
...suffix === "weekly" ? { windowDurationMins: WEEKLY_WINDOW_MINUTES3 } : {}
|
|
84589
|
+
});
|
|
84590
|
+
if (window2 === void 0) {
|
|
84591
|
+
continue;
|
|
84592
|
+
}
|
|
84593
|
+
const previous = windows.get(window2.id);
|
|
84594
|
+
if (previous === void 0 || window2.usedPercent > previous.usedPercent) {
|
|
84595
|
+
windows.set(window2.id, window2);
|
|
84596
|
+
}
|
|
84597
|
+
}
|
|
84598
|
+
}
|
|
84599
|
+
return [...windows.values()];
|
|
84600
|
+
}
|
|
84601
|
+
function isLoopbackUrl(url2) {
|
|
84602
|
+
try {
|
|
84603
|
+
const hostname4 = new URL(url2).hostname.replace(/^\[|\]$/gu, "").toLowerCase();
|
|
84604
|
+
return hostname4 === "127.0.0.1" || hostname4 === "localhost" || hostname4 === "::1";
|
|
84605
|
+
} catch {
|
|
84606
|
+
return false;
|
|
84607
|
+
}
|
|
84608
|
+
}
|
|
84609
|
+
async function fetchJsonPost(params) {
|
|
84610
|
+
const requestSignal = AbortSignal.any([params.signal, AbortSignal.timeout(HTTP_TIMEOUT_MILLISECONDS)]);
|
|
84611
|
+
const response = await fetch2(params.url, {
|
|
84612
|
+
method: "POST",
|
|
84613
|
+
headers: params.headers,
|
|
84614
|
+
body: params.body,
|
|
84615
|
+
redirect: "manual",
|
|
84616
|
+
...isLoopbackUrl(params.url) ? {} : { dispatcher: environmentProxyDispatcher },
|
|
84617
|
+
signal: requestSignal
|
|
84618
|
+
});
|
|
84619
|
+
if (!response.ok) {
|
|
84620
|
+
return { status: response.status, json: null };
|
|
84621
|
+
}
|
|
84622
|
+
return { status: response.status, json: await response.json() };
|
|
84623
|
+
}
|
|
84624
|
+
async function refreshAgyOAuthViaCli(options) {
|
|
84625
|
+
options.signal.throwIfAborted();
|
|
84626
|
+
const launch = executableLaunch2(options.command, ["models"]);
|
|
84627
|
+
const child = spawn8(launch.command, [...launch.arguments], {
|
|
84628
|
+
cwd: options.cwd,
|
|
84629
|
+
...platformSpawnOptions,
|
|
84630
|
+
env: { ...process.env, ...options.environment },
|
|
84631
|
+
shell: false,
|
|
84632
|
+
stdio: ["ignore", "ignore", "ignore"]
|
|
84633
|
+
});
|
|
84634
|
+
const processTreePromise = captureProcessTree(child).catch(() => []);
|
|
84635
|
+
const timeoutSignal = AbortSignal.any([
|
|
84636
|
+
options.signal,
|
|
84637
|
+
AbortSignal.timeout(TOKEN_REFRESH_CLI_TIMEOUT_MILLISECONDS)
|
|
84638
|
+
]);
|
|
84639
|
+
await new Promise((resolve21, reject2) => {
|
|
84640
|
+
let settled = false;
|
|
84641
|
+
const finish = (outcome) => {
|
|
84642
|
+
if (settled) {
|
|
84643
|
+
return;
|
|
84644
|
+
}
|
|
84645
|
+
settled = true;
|
|
84646
|
+
timeoutSignal.removeEventListener("abort", onAbort);
|
|
84647
|
+
outcome();
|
|
84648
|
+
};
|
|
84649
|
+
const onAbort = () => {
|
|
84650
|
+
void processTreePromise.then(async (tree) => await stopProcessTree(child, tree)).catch(() => void 0).finally(() => finish(() => reject2(timeoutSignal.reason ?? new Error("Antigravity refresh aborted"))));
|
|
84651
|
+
};
|
|
84652
|
+
timeoutSignal.addEventListener("abort", onAbort, { once: true });
|
|
84653
|
+
child.once("error", () => finish(() => resolve21()));
|
|
84654
|
+
child.once("close", () => finish(() => resolve21()));
|
|
84655
|
+
});
|
|
84656
|
+
}
|
|
84657
|
+
async function refreshAcpToken(credentials, tokenUrl, signal) {
|
|
84658
|
+
const form = new URLSearchParams({
|
|
84659
|
+
client_id: credentials.clientId,
|
|
84660
|
+
client_secret: credentials.clientSecret,
|
|
84661
|
+
refresh_token: credentials.refreshToken,
|
|
84662
|
+
grant_type: "refresh_token"
|
|
84663
|
+
});
|
|
84664
|
+
const response = await fetchJsonPost({
|
|
84665
|
+
url: tokenUrl,
|
|
84666
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
84667
|
+
body: form.toString(),
|
|
84668
|
+
signal
|
|
84669
|
+
});
|
|
84670
|
+
if (response.status < 200 || response.status >= 300) {
|
|
84671
|
+
return null;
|
|
84672
|
+
}
|
|
84673
|
+
const parsed = tokenResponseSchema.safeParse(response.json);
|
|
84674
|
+
return parsed.success ? parsed.data.access_token : null;
|
|
84675
|
+
}
|
|
84676
|
+
function resolveQuotaEndpoints(authMethod, environment) {
|
|
84677
|
+
const override = environment["MOBIUS_ANTIGRAVITY_QUOTA_BASE_URL"]?.trim();
|
|
84678
|
+
if (override !== void 0 && override.length > 0) {
|
|
84679
|
+
return [override.replace(/\/+$/u, "")];
|
|
84680
|
+
}
|
|
84681
|
+
return authMethod === "business" ? [PROD_ENDPOINT, DAILY_ENDPOINT] : [DAILY_ENDPOINT, PROD_ENDPOINT];
|
|
84682
|
+
}
|
|
84683
|
+
async function fetchMergedWindows(params) {
|
|
84684
|
+
const body = JSON.stringify(params.projectId === void 0 ? {} : { project: params.projectId });
|
|
84685
|
+
const headers = {
|
|
84686
|
+
authorization: `Bearer ${params.accessToken}`,
|
|
84687
|
+
"content-type": "application/json",
|
|
84688
|
+
"user-agent": antigravityUserAgent()
|
|
84689
|
+
};
|
|
84690
|
+
const results = await Promise.all(
|
|
84691
|
+
params.endpoints.map(
|
|
84692
|
+
async (endpoint) => {
|
|
84693
|
+
const requestedAtMs = Date.now();
|
|
84694
|
+
try {
|
|
84695
|
+
const response = await fetchJsonPost({
|
|
84696
|
+
url: `${endpoint}/v1internal:${params.operation}`,
|
|
84697
|
+
headers,
|
|
84698
|
+
body,
|
|
84699
|
+
signal: params.signal
|
|
84700
|
+
});
|
|
84701
|
+
if (response.status === 401) {
|
|
84702
|
+
return { windows: [], unauthorized: true };
|
|
84703
|
+
}
|
|
84704
|
+
if (response.status < 200 || response.status >= 300) {
|
|
84705
|
+
return { windows: [], unauthorized: false };
|
|
84706
|
+
}
|
|
84707
|
+
return { windows: params.parse(response.json, requestedAtMs), unauthorized: false };
|
|
84708
|
+
} catch (error62) {
|
|
84709
|
+
if (params.signal.aborted) {
|
|
84710
|
+
throw params.signal.reason ?? error62;
|
|
84711
|
+
}
|
|
84712
|
+
return { windows: [], unauthorized: false };
|
|
84713
|
+
}
|
|
84714
|
+
}
|
|
84715
|
+
)
|
|
84716
|
+
);
|
|
84717
|
+
const merged = /* @__PURE__ */ new Map();
|
|
84718
|
+
let unauthorized = false;
|
|
84719
|
+
for (const result of results) {
|
|
84720
|
+
if (result.unauthorized) {
|
|
84721
|
+
unauthorized = true;
|
|
84722
|
+
}
|
|
84723
|
+
for (const window2 of result.windows) {
|
|
84724
|
+
if (!merged.has(window2.id)) {
|
|
84725
|
+
merged.set(window2.id, window2);
|
|
84726
|
+
}
|
|
84727
|
+
}
|
|
84728
|
+
}
|
|
84729
|
+
return { windows: [...merged.values()], unauthorized: unauthorized && merged.size === 0 };
|
|
84730
|
+
}
|
|
84731
|
+
async function readAntigravityUsageQuota(options) {
|
|
84732
|
+
options.signal.throwIfAborted();
|
|
84733
|
+
const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
84734
|
+
let credentials = await readAntigravityStoredCredentials(options.environment);
|
|
84735
|
+
if (credentials.kind === "api_key_or_gateway") {
|
|
84736
|
+
return {
|
|
84737
|
+
agentId: "antigravity",
|
|
84738
|
+
status: "unsupported",
|
|
84739
|
+
checkedAt,
|
|
84740
|
+
reason: "api_key",
|
|
84741
|
+
message: credentials.message
|
|
84742
|
+
};
|
|
84743
|
+
}
|
|
84744
|
+
if (credentials.kind === "unauthenticated") {
|
|
84745
|
+
return {
|
|
84746
|
+
agentId: "antigravity",
|
|
84747
|
+
status: "unauthenticated",
|
|
84748
|
+
checkedAt,
|
|
84749
|
+
message: "Sign in to Antigravity on this computer to view subscription quotas."
|
|
84750
|
+
};
|
|
84751
|
+
}
|
|
84752
|
+
let accessToken = null;
|
|
84753
|
+
let accountLabel;
|
|
84754
|
+
let projectId;
|
|
84755
|
+
let authMethod = credentials.authMethod;
|
|
84756
|
+
try {
|
|
84757
|
+
if (credentials.kind === "agy_oauth") {
|
|
84758
|
+
const nowMs = Date.now();
|
|
84759
|
+
if (credentials.expiresAtMs !== null && credentials.expiresAtMs <= nowMs + TOKEN_EXPIRY_MARGIN_MILLISECONDS) {
|
|
84760
|
+
await refreshAgyOAuthViaCli(options);
|
|
84761
|
+
const refreshed = await readAntigravityStoredCredentials(options.environment);
|
|
84762
|
+
if (refreshed.kind === "agy_oauth") {
|
|
84763
|
+
credentials = refreshed;
|
|
84764
|
+
}
|
|
84765
|
+
}
|
|
84766
|
+
if (credentials.kind === "agy_oauth") {
|
|
84767
|
+
accessToken = credentials.accessToken;
|
|
84768
|
+
accountLabel = credentials.email;
|
|
84769
|
+
projectId = credentials.projectId;
|
|
84770
|
+
authMethod = credentials.authMethod;
|
|
84771
|
+
}
|
|
84772
|
+
} else {
|
|
84773
|
+
const tokenUrl = options.environment["MOBIUS_ANTIGRAVITY_OAUTH_TOKEN_URL"]?.trim() || OAUTH_TOKEN_URL;
|
|
84774
|
+
accessToken = await refreshAcpToken(credentials, tokenUrl, options.signal);
|
|
84775
|
+
projectId = credentials.projectId;
|
|
84776
|
+
authMethod = credentials.authMethod;
|
|
84777
|
+
}
|
|
84778
|
+
if (accessToken === null) {
|
|
84779
|
+
return {
|
|
84780
|
+
agentId: "antigravity",
|
|
84781
|
+
status: "unavailable",
|
|
84782
|
+
checkedAt,
|
|
84783
|
+
errorCode: "antigravity_token_refresh_failed",
|
|
84784
|
+
errorMessage: "Could not refresh the Antigravity OAuth token."
|
|
84785
|
+
};
|
|
84786
|
+
}
|
|
84787
|
+
const endpoints = resolveQuotaEndpoints(authMethod, options.environment);
|
|
84788
|
+
const queryQuotas = async (token) => {
|
|
84789
|
+
const summary = await fetchMergedWindows({
|
|
84790
|
+
endpoints,
|
|
84791
|
+
operation: "retrieveUserQuotaSummary",
|
|
84792
|
+
accessToken: token,
|
|
84793
|
+
...projectId === void 0 ? {} : { projectId },
|
|
84794
|
+
parse: parseSummaryWindows,
|
|
84795
|
+
signal: options.signal
|
|
84796
|
+
});
|
|
84797
|
+
if (summary.windows.length > 0 || summary.unauthorized) {
|
|
84798
|
+
return summary;
|
|
84799
|
+
}
|
|
84800
|
+
return await fetchMergedWindows({
|
|
84801
|
+
endpoints,
|
|
84802
|
+
operation: "fetchAvailableModels",
|
|
84803
|
+
accessToken: token,
|
|
84804
|
+
...projectId === void 0 ? {} : { projectId },
|
|
84805
|
+
parse: (raw) => parseModelWindows(raw),
|
|
84806
|
+
signal: options.signal
|
|
84807
|
+
});
|
|
84808
|
+
};
|
|
84809
|
+
let result = await queryQuotas(accessToken);
|
|
84810
|
+
if (result.unauthorized && credentials.kind === "agy_oauth") {
|
|
84811
|
+
await refreshAgyOAuthViaCli(options);
|
|
84812
|
+
const refreshed = await readAntigravityStoredCredentials(options.environment);
|
|
84813
|
+
if (refreshed.kind === "agy_oauth" && refreshed.accessToken !== accessToken) {
|
|
84814
|
+
result = await queryQuotas(refreshed.accessToken);
|
|
84815
|
+
}
|
|
84816
|
+
}
|
|
84817
|
+
if (result.unauthorized) {
|
|
84818
|
+
return {
|
|
84819
|
+
agentId: "antigravity",
|
|
84820
|
+
status: "unauthenticated",
|
|
84821
|
+
checkedAt,
|
|
84822
|
+
message: "Antigravity sign-in expired. Run `agy acp --login` on this computer."
|
|
84823
|
+
};
|
|
84824
|
+
}
|
|
84825
|
+
if (result.windows.length === 0) {
|
|
84826
|
+
return {
|
|
84827
|
+
agentId: "antigravity",
|
|
84828
|
+
status: "unavailable",
|
|
84829
|
+
checkedAt,
|
|
84830
|
+
errorCode: "antigravity_usage_empty",
|
|
84831
|
+
errorMessage: "Antigravity did not return usable quota information."
|
|
84832
|
+
};
|
|
84833
|
+
}
|
|
84834
|
+
return {
|
|
84835
|
+
agentId: "antigravity",
|
|
84836
|
+
status: "available",
|
|
84837
|
+
checkedAt,
|
|
84838
|
+
...accountLabel === void 0 ? {} : { accountLabel: accountLabel.slice(0, 128) },
|
|
84839
|
+
windows: result.windows
|
|
84840
|
+
};
|
|
84841
|
+
} catch (error62) {
|
|
84842
|
+
if (options.signal.aborted) {
|
|
84843
|
+
throw options.signal.reason ?? error62;
|
|
84844
|
+
}
|
|
84845
|
+
return {
|
|
84846
|
+
agentId: "antigravity",
|
|
84847
|
+
status: "unavailable",
|
|
84848
|
+
checkedAt,
|
|
84849
|
+
errorCode: "antigravity_usage_probe_failed",
|
|
84850
|
+
errorMessage: "Could not read Antigravity usage quotas."
|
|
84851
|
+
};
|
|
84852
|
+
}
|
|
84853
|
+
}
|
|
84854
|
+
|
|
82922
84855
|
// src/engine/acp/protocol/native-session.ts
|
|
82923
84856
|
var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
|
|
82924
84857
|
|
|
82925
84858
|
// src/engine/acp/adapter/execution-connections.ts
|
|
82926
|
-
import { isAbsolute as isAbsolute15, resolve as
|
|
84859
|
+
import { isAbsolute as isAbsolute15, resolve as resolve15 } from "node:path";
|
|
82927
84860
|
|
|
82928
84861
|
// src/engine/acp/client/prompt-content.ts
|
|
82929
84862
|
function validatePromptContent(options, capabilities) {
|
|
@@ -83585,6 +85518,11 @@ var AdapterSessionConnection = class {
|
|
|
83585
85518
|
if (!this.#lifetime.signal.aborted) {
|
|
83586
85519
|
options.onPromptSuggestion?.(report);
|
|
83587
85520
|
}
|
|
85521
|
+
},
|
|
85522
|
+
onUsageQuota: (report) => {
|
|
85523
|
+
if (!this.#lifetime.signal.aborted) {
|
|
85524
|
+
options.onUsageQuota?.(report);
|
|
85525
|
+
}
|
|
83588
85526
|
}
|
|
83589
85527
|
});
|
|
83590
85528
|
}
|
|
@@ -83744,9 +85682,13 @@ var AcpExecutionConnections = class {
|
|
|
83744
85682
|
#closing = /* @__PURE__ */ new WeakSet();
|
|
83745
85683
|
#externalizer;
|
|
83746
85684
|
#normalizeEvent;
|
|
83747
|
-
|
|
85685
|
+
#onUsageQuota;
|
|
85686
|
+
constructor(externalizer, normalizeEvent = (event) => event, onUsageQuota) {
|
|
83748
85687
|
this.#externalizer = externalizer;
|
|
83749
85688
|
this.#normalizeEvent = normalizeEvent;
|
|
85689
|
+
if (onUsageQuota !== void 0) {
|
|
85690
|
+
this.#onUsageQuota = onUsageQuota;
|
|
85691
|
+
}
|
|
83750
85692
|
}
|
|
83751
85693
|
acquire = (params) => {
|
|
83752
85694
|
params.signal.throwIfAborted();
|
|
@@ -83772,6 +85714,7 @@ var AcpExecutionConnections = class {
|
|
|
83772
85714
|
...params.onBackgroundActivity === void 0 ? {} : { onBackgroundActivity: params.onBackgroundActivity },
|
|
83773
85715
|
...params.onPromptDelegation === void 0 ? {} : { onPromptDelegation: params.onPromptDelegation },
|
|
83774
85716
|
...params.onPromptSuggestion === void 0 ? {} : { onPromptSuggestion: params.onPromptSuggestion },
|
|
85717
|
+
...this.#onUsageQuota === void 0 ? {} : { onUsageQuota: this.#onUsageQuota },
|
|
83775
85718
|
...params.onAgentTurn === void 0 ? {} : { onAgentTurn: params.onAgentTurn },
|
|
83776
85719
|
...params.onBackgroundTasks === void 0 ? {} : { onBackgroundTasks: params.onBackgroundTasks },
|
|
83777
85720
|
interactions: params.interactions
|
|
@@ -83829,9 +85772,9 @@ var AcpExecutionConnections = class {
|
|
|
83829
85772
|
);
|
|
83830
85773
|
}
|
|
83831
85774
|
const matches = [...this.#sessions].filter(
|
|
83832
|
-
({ connection, scope }) => connection.events.sessionId() === decoded.data.nativeSessionId && scope.cwd === decoded.data.cwd && scope.cwd ===
|
|
85775
|
+
({ connection, scope }) => connection.events.sessionId() === decoded.data.nativeSessionId && scope.cwd === decoded.data.cwd && scope.cwd === resolve15(decoded.data.cwd) && arraysEqual(scope.additionalDirectories, decoded.data.additionalDirectories) && arraysEqual(
|
|
83833
85776
|
scope.additionalDirectories,
|
|
83834
|
-
decoded.data.additionalDirectories.map((path6) =>
|
|
85777
|
+
decoded.data.additionalDirectories.map((path6) => resolve15(path6))
|
|
83835
85778
|
)
|
|
83836
85779
|
);
|
|
83837
85780
|
if (matches.length > 1) {
|
|
@@ -84438,7 +86381,7 @@ var AgentQueryProcesses = class {
|
|
|
84438
86381
|
};
|
|
84439
86382
|
|
|
84440
86383
|
// src/engine/acp/adapter/antigravity/conversation-handoff.ts
|
|
84441
|
-
import { join as
|
|
86384
|
+
import { join as join25 } from "node:path";
|
|
84442
86385
|
var TRANSCRIPT_TAIL_BYTES2 = 1048576;
|
|
84443
86386
|
var MAXIMUM_HANDOFF_CHARACTERS = 32e3;
|
|
84444
86387
|
var MAXIMUM_MESSAGE_CHARACTERS = 4e3;
|
|
@@ -84473,7 +86416,7 @@ async function readConversationMessages(launchEnvironment, nativeSessionId) {
|
|
|
84473
86416
|
}
|
|
84474
86417
|
const tail = await readScopedFileTail(
|
|
84475
86418
|
geminiHome,
|
|
84476
|
-
|
|
86419
|
+
join25("antigravity-cli", "brain", nativeSessionId, ".system_generated", "logs", "transcript.jsonl"),
|
|
84477
86420
|
TRANSCRIPT_TAIL_BYTES2
|
|
84478
86421
|
);
|
|
84479
86422
|
if (tail === null) {
|
|
@@ -84655,6 +86598,12 @@ var AntigravityAdapter = class {
|
|
|
84655
86598
|
signal.throwIfAborted();
|
|
84656
86599
|
return { kind: "unsupported" };
|
|
84657
86600
|
};
|
|
86601
|
+
readUsageQuota = async (params) => await readAntigravityUsageQuota({
|
|
86602
|
+
command: params.agent.command,
|
|
86603
|
+
cwd: params.cwd,
|
|
86604
|
+
environment: params.agent.environment,
|
|
86605
|
+
signal: params.signal
|
|
86606
|
+
});
|
|
84658
86607
|
close = async () => await runCleanup(
|
|
84659
86608
|
() => this.#queryProcesses.close(),
|
|
84660
86609
|
() => this.#executionConnections.close()
|
|
@@ -84677,7 +86626,11 @@ var ClaudeAdapter = class {
|
|
|
84677
86626
|
#executionConnections;
|
|
84678
86627
|
constructor(agent2, dependencies) {
|
|
84679
86628
|
this.#connector = new AcpSessionConnector(dependencies.contentExternalizer);
|
|
84680
|
-
this.#executionConnections = new AcpExecutionConnections(
|
|
86629
|
+
this.#executionConnections = new AcpExecutionConnections(
|
|
86630
|
+
dependencies.contentExternalizer,
|
|
86631
|
+
void 0,
|
|
86632
|
+
dependencies.onUsageQuota
|
|
86633
|
+
);
|
|
84681
86634
|
this.#queryProcesses = new AgentQueryProcesses(agent2, dependencies.processes, this.#connector);
|
|
84682
86635
|
}
|
|
84683
86636
|
refreshAgent = (agent2) => this.#queryProcesses.refreshAgent(agent2);
|
|
@@ -84735,6 +86688,12 @@ var ClaudeAdapter = class {
|
|
|
84735
86688
|
renameSession = (...args) => this.#executionConnections.renameSession(...args);
|
|
84736
86689
|
configureSession = (...args) => this.#executionConnections.configureSession(...args);
|
|
84737
86690
|
readModelSettings = (params) => this.#executionConnections.readModelSettings(params);
|
|
86691
|
+
readUsageQuota = async (params) => await readClaudeUsageQuota({
|
|
86692
|
+
command: params.agent.command,
|
|
86693
|
+
cwd: params.cwd,
|
|
86694
|
+
environment: params.agent.environment,
|
|
86695
|
+
signal: params.signal
|
|
86696
|
+
});
|
|
84738
86697
|
close = async () => await runCleanup(
|
|
84739
86698
|
() => this.#queryProcesses.close(),
|
|
84740
86699
|
() => this.#executionConnections.close()
|
|
@@ -84823,7 +86782,11 @@ var CodexAdapter = class {
|
|
|
84823
86782
|
}
|
|
84824
86783
|
};
|
|
84825
86784
|
this.#connector = new AcpSessionConnector(contentExternalizer, fitCodexToolEvent);
|
|
84826
|
-
this.#executionConnections = new AcpExecutionConnections(
|
|
86785
|
+
this.#executionConnections = new AcpExecutionConnections(
|
|
86786
|
+
contentExternalizer,
|
|
86787
|
+
fitCodexToolEvent,
|
|
86788
|
+
dependencies.onUsageQuota
|
|
86789
|
+
);
|
|
84827
86790
|
this.#queryProcesses = new AgentQueryProcesses(agent2, dependencies.processes, this.#connector);
|
|
84828
86791
|
}
|
|
84829
86792
|
refreshAgent = (agent2) => {
|
|
@@ -84917,6 +86880,12 @@ var CodexAdapter = class {
|
|
|
84917
86880
|
signal.throwIfAborted();
|
|
84918
86881
|
return { kind: "unsupported" };
|
|
84919
86882
|
};
|
|
86883
|
+
readUsageQuota = async (params) => await readCodexUsageQuota({
|
|
86884
|
+
command: params.agent.command,
|
|
86885
|
+
cwd: params.cwd,
|
|
86886
|
+
environment: params.agent.environment,
|
|
86887
|
+
signal: params.signal
|
|
86888
|
+
});
|
|
84920
86889
|
close = async () => {
|
|
84921
86890
|
await runCleanup(
|
|
84922
86891
|
() => this.#queryProcesses.close(),
|
|
@@ -84994,6 +86963,15 @@ var PiAdapter = class {
|
|
|
84994
86963
|
signal.throwIfAborted();
|
|
84995
86964
|
return { kind: "unsupported" };
|
|
84996
86965
|
};
|
|
86966
|
+
readUsageQuota = async (params) => {
|
|
86967
|
+
params.signal.throwIfAborted();
|
|
86968
|
+
return {
|
|
86969
|
+
agentId: params.agent.id,
|
|
86970
|
+
status: "unsupported",
|
|
86971
|
+
checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
86972
|
+
reason: "no_subscription_quota"
|
|
86973
|
+
};
|
|
86974
|
+
};
|
|
84997
86975
|
close = async () => await runCleanup(
|
|
84998
86976
|
() => this.#queryProcesses.close(),
|
|
84999
86977
|
() => this.#executionConnections.close()
|
|
@@ -85295,11 +87273,15 @@ var AcpContentExternalizer = class {
|
|
|
85295
87273
|
};
|
|
85296
87274
|
|
|
85297
87275
|
// src/engine/agent/runtime-agents.ts
|
|
85298
|
-
function createRuntimeAdapterRegistry(adapters, processes, externalize, linkedResources) {
|
|
87276
|
+
function createRuntimeAdapterRegistry(adapters, processes, externalize, linkedResources, onUsageQuota) {
|
|
85299
87277
|
const contentExternalizer = new AcpContentExternalizer(externalize, linkedResources);
|
|
85300
87278
|
const externalizeSessionUpdate = (sessionId, update, signal) => contentExternalizer.update(sessionId, update, signal);
|
|
85301
87279
|
return {
|
|
85302
|
-
adapters: new AdapterRegistry(adapters, {
|
|
87280
|
+
adapters: new AdapterRegistry(adapters, {
|
|
87281
|
+
processes,
|
|
87282
|
+
contentExternalizer,
|
|
87283
|
+
...onUsageQuota === void 0 ? {} : { onUsageQuota }
|
|
87284
|
+
}),
|
|
85303
87285
|
externalizeSessionUpdate
|
|
85304
87286
|
};
|
|
85305
87287
|
}
|
|
@@ -85312,62 +87294,12 @@ var RuntimeAgentDependencies = class {
|
|
|
85312
87294
|
}
|
|
85313
87295
|
};
|
|
85314
87296
|
|
|
85315
|
-
// src/engine/util/network/environment-proxy.ts
|
|
85316
|
-
import { EnvHttpProxyAgent } from "undici";
|
|
85317
|
-
var configuredHttpProxy = process.env["http_proxy"] ?? process.env["HTTP_PROXY"] ?? "";
|
|
85318
|
-
var configuredHttpsProxy = process.env["https_proxy"] ?? process.env["HTTPS_PROXY"] ?? configuredHttpProxy;
|
|
85319
|
-
var environmentProxyDispatcher = new EnvHttpProxyAgent();
|
|
85320
|
-
function bypassesProxy(target) {
|
|
85321
|
-
const noProxy = process.env["no_proxy"] ?? process.env["NO_PROXY"] ?? "";
|
|
85322
|
-
if (noProxy === "*") {
|
|
85323
|
-
return true;
|
|
85324
|
-
}
|
|
85325
|
-
const hostname4 = target.hostname.replace(/^\[|\]$/gu, "").toLowerCase();
|
|
85326
|
-
const defaultPort = target.protocol === "wss:" || target.protocol === "https:" ? 443 : 80;
|
|
85327
|
-
const port = Number.parseInt(target.port, 10) || defaultPort;
|
|
85328
|
-
for (const rawEntry of noProxy.split(/[,\s]/u)) {
|
|
85329
|
-
if (rawEntry.length === 0) {
|
|
85330
|
-
continue;
|
|
85331
|
-
}
|
|
85332
|
-
const parsed = rawEntry.match(/^(.+):(\d+)$/u);
|
|
85333
|
-
const entryHostname = (parsed?.[1] ?? rawEntry).replace(/^\*?\./u, "").toLowerCase();
|
|
85334
|
-
const entryPort = parsed?.[2] === void 0 ? 0 : Number.parseInt(parsed[2], 10);
|
|
85335
|
-
if (entryPort !== 0 && entryPort !== port) {
|
|
85336
|
-
continue;
|
|
85337
|
-
}
|
|
85338
|
-
if (hostname4 === entryHostname || hostname4.endsWith(`.${entryHostname}`)) {
|
|
85339
|
-
return true;
|
|
85340
|
-
}
|
|
85341
|
-
}
|
|
85342
|
-
return false;
|
|
85343
|
-
}
|
|
85344
|
-
function sanitizedProxyOrigin(proxyUrl) {
|
|
85345
|
-
try {
|
|
85346
|
-
return new URL(proxyUrl).origin;
|
|
85347
|
-
} catch {
|
|
85348
|
-
return "configured-invalid-url";
|
|
85349
|
-
}
|
|
85350
|
-
}
|
|
85351
|
-
function describeEnvironmentProxyRoute(target) {
|
|
85352
|
-
if (bypassesProxy(target)) {
|
|
85353
|
-
return { proxyRoute: "direct" };
|
|
85354
|
-
}
|
|
85355
|
-
const proxyUrl = target.protocol === "wss:" || target.protocol === "https:" ? configuredHttpsProxy : configuredHttpProxy;
|
|
85356
|
-
if (proxyUrl.length === 0) {
|
|
85357
|
-
return { proxyRoute: "direct" };
|
|
85358
|
-
}
|
|
85359
|
-
return {
|
|
85360
|
-
proxyOrigin: sanitizedProxyOrigin(proxyUrl),
|
|
85361
|
-
proxyRoute: "proxy"
|
|
85362
|
-
};
|
|
85363
|
-
}
|
|
85364
|
-
|
|
85365
87297
|
// src/engine/runtime/observability/diagnostic-log.ts
|
|
85366
|
-
import { join as
|
|
87298
|
+
import { join as join28 } from "node:path";
|
|
85367
87299
|
|
|
85368
87300
|
// src/engine/storage/logs/bounded-log.ts
|
|
85369
87301
|
import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync10, renameSync as renameSync2, statSync as statSync5, writeFileSync as writeFileSync2 } from "node:fs";
|
|
85370
|
-
import { join as
|
|
87302
|
+
import { join as join26 } from "node:path";
|
|
85371
87303
|
var BoundedLineLog = class {
|
|
85372
87304
|
#path;
|
|
85373
87305
|
#maximumBytes;
|
|
@@ -85376,7 +87308,7 @@ var BoundedLineLog = class {
|
|
|
85376
87308
|
#onWriteFailure;
|
|
85377
87309
|
constructor(directory, filename, maximumBytes, onWriteFailure = () => void 0) {
|
|
85378
87310
|
this.#directory = directory;
|
|
85379
|
-
this.#path =
|
|
87311
|
+
this.#path = join26(directory, filename);
|
|
85380
87312
|
this.#maximumBytes = maximumBytes;
|
|
85381
87313
|
this.#onWriteFailure = onWriteFailure;
|
|
85382
87314
|
}
|
|
@@ -85427,21 +87359,21 @@ var BoundedLineLog = class {
|
|
|
85427
87359
|
|
|
85428
87360
|
// src/engine/storage/logs/log-files.ts
|
|
85429
87361
|
import { readFileSync as readFileSync11 } from "node:fs";
|
|
85430
|
-
import { join as
|
|
87362
|
+
import { join as join27 } from "node:path";
|
|
85431
87363
|
var DAEMON_LOG_FILENAME = "daemon.log";
|
|
85432
87364
|
var WORKER_LIFECYCLE_LOG_FILENAME = "worker-lifecycle.log";
|
|
85433
87365
|
function unhandledRejectionLogFilename(role) {
|
|
85434
87366
|
return `unhandled-rejections-${role}.log`;
|
|
85435
87367
|
}
|
|
85436
87368
|
function logDirectory(dataDirectory) {
|
|
85437
|
-
return
|
|
87369
|
+
return join27(dataDirectory, "logs");
|
|
85438
87370
|
}
|
|
85439
87371
|
function processLogPaths(dataDirectory) {
|
|
85440
87372
|
return [
|
|
85441
87373
|
WORKER_LIFECYCLE_LOG_FILENAME,
|
|
85442
87374
|
unhandledRejectionLogFilename("manager"),
|
|
85443
87375
|
unhandledRejectionLogFilename("worker")
|
|
85444
|
-
].map((filename) =>
|
|
87376
|
+
].map((filename) => join27(logDirectory(dataDirectory), filename));
|
|
85445
87377
|
}
|
|
85446
87378
|
function readLogText(path6) {
|
|
85447
87379
|
try {
|
|
@@ -85516,7 +87448,7 @@ var RuntimeDiagnosticLog = class {
|
|
|
85516
87448
|
this.#maximumBytes = maximumBytes;
|
|
85517
87449
|
const processLogsDirectory = options.processLogsDirectory;
|
|
85518
87450
|
this.#sources = [
|
|
85519
|
-
{ maximumBytes, path:
|
|
87451
|
+
{ maximumBytes, path: join28(directory, DAEMON_LOG_FILENAME) },
|
|
85520
87452
|
// The process logs a Runtime does not own, but must read to explain its own deaths.
|
|
85521
87453
|
...processLogsDirectory === void 0 ? [] : processLogPaths(processLogsDirectory).map((path6) => ({ maximumBytes: null, path: path6 }))
|
|
85522
87454
|
];
|
|
@@ -85637,7 +87569,7 @@ async function discoverRuntimeAgentInventory(options, channelId) {
|
|
|
85637
87569
|
}
|
|
85638
87570
|
|
|
85639
87571
|
// src/engine/runtime/catalog/publish-agent-catalog.ts
|
|
85640
|
-
import { fetch as
|
|
87572
|
+
import { fetch as fetch3 } from "undici";
|
|
85641
87573
|
|
|
85642
87574
|
// src/engine/runtime/relay/relay-authentication.ts
|
|
85643
87575
|
function runtimeCredential(relayUrl) {
|
|
@@ -85714,7 +87646,7 @@ async function publishAgentCatalog(config2, signal) {
|
|
|
85714
87646
|
let response;
|
|
85715
87647
|
const catalog = config2.catalog.read();
|
|
85716
87648
|
try {
|
|
85717
|
-
response = await
|
|
87649
|
+
response = await fetch3(catalogEndpoint(config2), {
|
|
85718
87650
|
body: JSON.stringify({
|
|
85719
87651
|
agents: catalog.agents.map((agent2) => ({
|
|
85720
87652
|
agentPath: agent2.agentIdentity.requestedPath,
|
|
@@ -85745,7 +87677,7 @@ async function publishAgentCatalog(config2, signal) {
|
|
|
85745
87677
|
}
|
|
85746
87678
|
|
|
85747
87679
|
// src/engine/runtime/config.ts
|
|
85748
|
-
import { resolve as
|
|
87680
|
+
import { resolve as resolve16 } from "node:path";
|
|
85749
87681
|
|
|
85750
87682
|
// src/engine/agent/catalog.ts
|
|
85751
87683
|
var LocalAgentCatalogSnapshot = class {
|
|
@@ -85808,7 +87740,7 @@ var RuntimeLocalContext = class {
|
|
|
85808
87740
|
stateDirectory;
|
|
85809
87741
|
maxAcpProcesses;
|
|
85810
87742
|
constructor(stateDirectory, agentLaunchEnvironment, maxAcpProcesses = 1e3) {
|
|
85811
|
-
this.stateDirectory =
|
|
87743
|
+
this.stateDirectory = resolve16(stateDirectory);
|
|
85812
87744
|
this.agentLaunchEnvironment = Object.freeze({ ...agentLaunchEnvironment });
|
|
85813
87745
|
this.maxAcpProcesses = maxAcpProcesses;
|
|
85814
87746
|
}
|
|
@@ -85963,7 +87895,7 @@ function validatePairingId(value) {
|
|
|
85963
87895
|
return value;
|
|
85964
87896
|
}
|
|
85965
87897
|
async function resolveDefaultWorkspace(path6) {
|
|
85966
|
-
const requestedWorkspace =
|
|
87898
|
+
const requestedWorkspace = resolve17(path6);
|
|
85967
87899
|
let defaultWorkspace;
|
|
85968
87900
|
try {
|
|
85969
87901
|
defaultWorkspace = await ensureCanonicalDirectory(requestedWorkspace);
|
|
@@ -86028,7 +87960,7 @@ async function claimPairing(options, defaultWorkspace, localAgents, signal) {
|
|
|
86028
87960
|
const endpoint = options.pairingId.length > 0 ? mobiusApiUrl(options.relayOrigin, `/v1/runtime-pairings/${encodeURIComponent(options.pairingId)}/redeem`) : mobiusApiUrl(options.relayOrigin, "/pairings/claim");
|
|
86029
87961
|
let response;
|
|
86030
87962
|
try {
|
|
86031
|
-
response = await
|
|
87963
|
+
response = await fetch4(endpoint, {
|
|
86032
87964
|
body: JSON.stringify({
|
|
86033
87965
|
agents,
|
|
86034
87966
|
machineName: hostname3(),
|
|
@@ -86141,7 +88073,7 @@ async function prepareRuntimeConnection(installation, connection, signal, enviro
|
|
|
86141
88073
|
}
|
|
86142
88074
|
|
|
86143
88075
|
// src/engine/runtime/runtime-loop.ts
|
|
86144
|
-
import { resolve as
|
|
88076
|
+
import { resolve as resolve19 } from "node:path";
|
|
86145
88077
|
|
|
86146
88078
|
// src/engine/runtime/run.ts
|
|
86147
88079
|
import { styleText } from "node:util";
|
|
@@ -86651,7 +88583,7 @@ function sql(strings, ...params) {
|
|
|
86651
88583
|
return new SQL([new StringChunk(str)]);
|
|
86652
88584
|
}
|
|
86653
88585
|
_sql.raw = raw;
|
|
86654
|
-
function
|
|
88586
|
+
function join35(chunks, separator) {
|
|
86655
88587
|
const result = [];
|
|
86656
88588
|
for (const [i, chunk] of chunks.entries()) {
|
|
86657
88589
|
if (i > 0 && separator !== void 0) result.push(separator);
|
|
@@ -86659,7 +88591,7 @@ function sql(strings, ...params) {
|
|
|
86659
88591
|
}
|
|
86660
88592
|
return new SQL(result);
|
|
86661
88593
|
}
|
|
86662
|
-
_sql.join =
|
|
88594
|
+
_sql.join = join35;
|
|
86663
88595
|
function identifier2(value) {
|
|
86664
88596
|
return new Name(value);
|
|
86665
88597
|
}
|
|
@@ -88804,7 +90736,7 @@ var SQLiteSelectBase = class extends TypedQueryBuilder {
|
|
|
88804
90736
|
const baseTableName = this.tableName;
|
|
88805
90737
|
const tableName = getTableLikeName(table);
|
|
88806
90738
|
for (const item of extractUsedTable(table)) this.usedTables.add(item);
|
|
88807
|
-
if (typeof tableName === "string" && this.config.joins?.some((
|
|
90739
|
+
if (typeof tableName === "string" && this.config.joins?.some((join35) => join35.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
|
|
88808
90740
|
if (!this.isPartialSelect) {
|
|
88809
90741
|
if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") this.config.fields = { [baseTableName]: this.config.fields };
|
|
88810
90742
|
if (typeof tableName === "string" && !is(table, SQL)) {
|
|
@@ -89643,7 +91575,7 @@ var SQLiteDialect = class {
|
|
|
89643
91575
|
if (!joins2) return;
|
|
89644
91576
|
const withEntries = Object.entries(joins2).filter(([_, v]) => v);
|
|
89645
91577
|
if (!withEntries.length) return;
|
|
89646
|
-
return sql.join(withEntries.map(([k2,
|
|
91578
|
+
return sql.join(withEntries.map(([k2, join35]) => {
|
|
89647
91579
|
const relation = tableConfig.relations[k2];
|
|
89648
91580
|
const isSingle2 = is(relation, One2);
|
|
89649
91581
|
const targetTable = aliasedTable(relation.targetTable, `d${currentDepth + 1}`);
|
|
@@ -89654,7 +91586,7 @@ var SQLiteDialect = class {
|
|
|
89654
91586
|
table: targetTable,
|
|
89655
91587
|
mode: isSingle2 ? "first" : "many",
|
|
89656
91588
|
schema,
|
|
89657
|
-
queryConfig:
|
|
91589
|
+
queryConfig: join35,
|
|
89658
91590
|
tableConfig: schema[relation.targetTableName],
|
|
89659
91591
|
relationWhere: filter,
|
|
89660
91592
|
isNested: true,
|
|
@@ -89668,7 +91600,7 @@ var SQLiteDialect = class {
|
|
|
89668
91600
|
key: k2,
|
|
89669
91601
|
selection: innerQuery.selection,
|
|
89670
91602
|
isArray: !isSingle2,
|
|
89671
|
-
isOptional: (relation.optional ?? false) ||
|
|
91603
|
+
isOptional: (relation.optional ?? false) || join35 !== true && !!join35.where
|
|
89672
91604
|
});
|
|
89673
91605
|
const jsonColumns = sql.join(innerQuery.selection.map((s) => {
|
|
89674
91606
|
return sql`${sql.raw(this.escapeString(s.key))}, ${s.selection ? sql`${jsonb}(${sql.identifier(s.key)})` : sql.identifier(s.key)}`;
|
|
@@ -90284,7 +92216,7 @@ var SQLiteUpdateBase = class {
|
|
|
90284
92216
|
createJoin(joinType) {
|
|
90285
92217
|
return ((table, on2) => {
|
|
90286
92218
|
const tableName = getTableLikeName(table);
|
|
90287
|
-
if (typeof tableName === "string" && this.config.joins.some((
|
|
92219
|
+
if (typeof tableName === "string" && this.config.joins.some((join35) => join35.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
|
|
90288
92220
|
if (typeof on2 === "function") {
|
|
90289
92221
|
const from = this.config.from ? is(table, SQLiteTable) ? table[Table.Symbol.Columns] : is(table, Subquery) ? table._.selectedFields : is(table, SQLiteViewBase) ? table[ViewBaseConfig].selectedFields : void 0 : void 0;
|
|
90290
92222
|
on2 = on2(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
|
|
@@ -91238,7 +93170,7 @@ var SessionEventCacheTable = class {
|
|
|
91238
93170
|
// src/engine/storage/sqlite/local-databases.ts
|
|
91239
93171
|
import { createHash as createHash4 } from "node:crypto";
|
|
91240
93172
|
import { existsSync as existsSync9 } from "node:fs";
|
|
91241
|
-
import { join as
|
|
93173
|
+
import { join as join29 } from "node:path";
|
|
91242
93174
|
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
91243
93175
|
|
|
91244
93176
|
// src/engine/generated/acp-session-store-migrations.ts
|
|
@@ -91491,9 +93423,9 @@ var LocalSqliteDatabase = class {
|
|
|
91491
93423
|
function channelSessionDatabasePaths(stateDirectory, channelId) {
|
|
91492
93424
|
const channelHash = createHash4("sha256").update(channelId).digest("hex");
|
|
91493
93425
|
return {
|
|
91494
|
-
cancellations:
|
|
91495
|
-
events:
|
|
91496
|
-
sessions:
|
|
93426
|
+
cancellations: join29(stateDirectory, "sessions", `${channelHash}.cancellations.sqlite`),
|
|
93427
|
+
events: join29(stateDirectory, "sessions", `${channelHash}.events.sqlite`),
|
|
93428
|
+
sessions: join29(stateDirectory, "sessions", `${channelHash}.sqlite`)
|
|
91497
93429
|
};
|
|
91498
93430
|
}
|
|
91499
93431
|
function recordAppliedAdmissionOrder(path6) {
|
|
@@ -91650,14 +93582,14 @@ function mergeTextChunk(previous, incoming) {
|
|
|
91650
93582
|
var SessionEventHistoryProjection = class {
|
|
91651
93583
|
#toolCallEventIds = /* @__PURE__ */ new Map();
|
|
91652
93584
|
#latestEvent = null;
|
|
91653
|
-
apply = (liveEvent2,
|
|
93585
|
+
apply = (liveEvent2, resolve21) => {
|
|
91654
93586
|
if (liveEvent2.type === "lifecycle-metadata") {
|
|
91655
93587
|
this.#latestEvent = null;
|
|
91656
93588
|
return { kind: "skip" };
|
|
91657
93589
|
}
|
|
91658
93590
|
if (liveEvent2.type === "acp" && liveEvent2.payload.sessionUpdate === "tool_call_update") {
|
|
91659
93591
|
const targetEventId = this.#toolCallEventIds.get(liveEvent2.payload.toolCallId);
|
|
91660
|
-
const current = targetEventId === void 0 ? void 0 :
|
|
93592
|
+
const current = targetEventId === void 0 ? void 0 : resolve21([targetEventId]).get(targetEventId);
|
|
91661
93593
|
if (current?.type === "acp" && (current.payload.sessionUpdate === "tool_call" || current.payload.sessionUpdate === "tool_call_update")) {
|
|
91662
93594
|
return this.#replace(
|
|
91663
93595
|
current,
|
|
@@ -91681,12 +93613,12 @@ var SessionEventHistoryProjection = class {
|
|
|
91681
93613
|
* The projected tool call announced with this identifier, in its current
|
|
91682
93614
|
* merged form, or `undefined` when the projection has not recorded one.
|
|
91683
93615
|
*/
|
|
91684
|
-
getToolCall = (toolCallId,
|
|
93616
|
+
getToolCall = (toolCallId, resolve21) => {
|
|
91685
93617
|
const eventId = this.#toolCallEventIds.get(toolCallId);
|
|
91686
93618
|
if (eventId === void 0) {
|
|
91687
93619
|
return void 0;
|
|
91688
93620
|
}
|
|
91689
|
-
const event =
|
|
93621
|
+
const event = resolve21([eventId]).get(eventId);
|
|
91690
93622
|
if (event?.type === "acp" && (event.payload.sessionUpdate === "tool_call" || event.payload.sessionUpdate === "tool_call_update")) {
|
|
91691
93623
|
return event.payload;
|
|
91692
93624
|
}
|
|
@@ -91746,8 +93678,8 @@ var SessionEvents = class {
|
|
|
91746
93678
|
this.sessionGenerationId = sessionGenerationId;
|
|
91747
93679
|
this.#projection = new SessionEventHistoryProjection();
|
|
91748
93680
|
}
|
|
91749
|
-
apply = (event,
|
|
91750
|
-
const projected = this.#projection.apply(event,
|
|
93681
|
+
apply = (event, resolve21) => {
|
|
93682
|
+
const projected = this.#projection.apply(event, resolve21);
|
|
91751
93683
|
this.#throughPosition = event.position;
|
|
91752
93684
|
if (projected.kind === "skip") {
|
|
91753
93685
|
return;
|
|
@@ -91774,7 +93706,7 @@ var SessionEvents = class {
|
|
|
91774
93706
|
return this.#cachedItemsByEventId.size;
|
|
91775
93707
|
}
|
|
91776
93708
|
/** The projected tool call for this identifier, materializing it if needed. */
|
|
91777
|
-
toolCall = (toolCallId,
|
|
93709
|
+
toolCall = (toolCallId, resolve21) => this.#projection.getToolCall(toolCallId, resolve21);
|
|
91778
93710
|
item = (eventId) => this.#cachedItemsByEventId.get(eventId)?.event;
|
|
91779
93711
|
/**
|
|
91780
93712
|
* Materializes an event that was previously dropped to the cache database.
|
|
@@ -96192,8 +98124,8 @@ var RuntimeTurnActivity = class {
|
|
|
96192
98124
|
#changed() {
|
|
96193
98125
|
this.#changedAt = Date.now();
|
|
96194
98126
|
if (this.count() === 0) {
|
|
96195
|
-
for (const
|
|
96196
|
-
|
|
98127
|
+
for (const resolve21 of this.#idleWaiters) {
|
|
98128
|
+
resolve21();
|
|
96197
98129
|
}
|
|
96198
98130
|
this.#idleWaiters.clear();
|
|
96199
98131
|
}
|
|
@@ -96203,14 +98135,14 @@ var RuntimeTurnActivity = class {
|
|
|
96203
98135
|
if (this.count() === 0) {
|
|
96204
98136
|
return Promise.resolve();
|
|
96205
98137
|
}
|
|
96206
|
-
return new Promise((
|
|
98138
|
+
return new Promise((resolve21, reject2) => {
|
|
96207
98139
|
const abort = () => {
|
|
96208
98140
|
this.#idleWaiters.delete(idle);
|
|
96209
98141
|
reject2(signal.reason);
|
|
96210
98142
|
};
|
|
96211
98143
|
const idle = () => {
|
|
96212
98144
|
signal.removeEventListener("abort", abort);
|
|
96213
|
-
|
|
98145
|
+
resolve21();
|
|
96214
98146
|
};
|
|
96215
98147
|
this.#idleWaiters.add(idle);
|
|
96216
98148
|
signal.addEventListener("abort", abort, { once: true });
|
|
@@ -96374,7 +98306,7 @@ var ActiveRuntimeTurn = class {
|
|
|
96374
98306
|
// src/engine/session/turn/session-execution.ts
|
|
96375
98307
|
var waitForTurnCompletion = (turn, waitSignal) => {
|
|
96376
98308
|
waitSignal.throwIfAborted();
|
|
96377
|
-
return new Promise((
|
|
98309
|
+
return new Promise((resolve21, reject2) => {
|
|
96378
98310
|
let settled = false;
|
|
96379
98311
|
const finish = (result) => {
|
|
96380
98312
|
if (settled) {
|
|
@@ -96383,7 +98315,7 @@ var waitForTurnCompletion = (turn, waitSignal) => {
|
|
|
96383
98315
|
settled = true;
|
|
96384
98316
|
waitSignal.removeEventListener("abort", onAbort);
|
|
96385
98317
|
if (result.kind === "completed") {
|
|
96386
|
-
|
|
98318
|
+
resolve21();
|
|
96387
98319
|
} else {
|
|
96388
98320
|
reject2(result.error);
|
|
96389
98321
|
}
|
|
@@ -96597,8 +98529,8 @@ var SessionTurns = class {
|
|
|
96597
98529
|
};
|
|
96598
98530
|
|
|
96599
98531
|
// src/engine/session/workspace/workspace-directory.ts
|
|
96600
|
-
import { homedir as
|
|
96601
|
-
import { basename as basename8, dirname as dirname10, isAbsolute as isAbsolute16, join as
|
|
98532
|
+
import { homedir as homedir5 } from "node:os";
|
|
98533
|
+
import { basename as basename8, dirname as dirname10, isAbsolute as isAbsolute16, join as join30, normalize as normalize2, relative as relative3 } from "node:path";
|
|
96602
98534
|
|
|
96603
98535
|
// src/engine/session/workspace/local-authorization-error.ts
|
|
96604
98536
|
var LocalAuthorizationError = class extends OperationError {
|
|
@@ -96629,7 +98561,7 @@ function encodePath(path6) {
|
|
|
96629
98561
|
return `path-${encoded}`;
|
|
96630
98562
|
}
|
|
96631
98563
|
function expandCurrentUserHome(path6) {
|
|
96632
|
-
return path6.replace(/^~(?=$|\/|\\)/,
|
|
98564
|
+
return path6.replace(/^~(?=$|\/|\\)/, homedir5());
|
|
96633
98565
|
}
|
|
96634
98566
|
function decodePath(value, prefix) {
|
|
96635
98567
|
const encoded = value.slice(prefix.length);
|
|
@@ -96660,7 +98592,7 @@ var WorkspaceDirectoryService = class {
|
|
|
96660
98592
|
return this.#defaultWorkspace;
|
|
96661
98593
|
}
|
|
96662
98594
|
if (id === "home") {
|
|
96663
|
-
return
|
|
98595
|
+
return homedir5();
|
|
96664
98596
|
}
|
|
96665
98597
|
if (id.startsWith("path-")) {
|
|
96666
98598
|
const path6 = expandCurrentUserHome(decodePath(id, "path-"));
|
|
@@ -96695,7 +98627,7 @@ var WorkspaceDirectoryService = class {
|
|
|
96695
98627
|
}
|
|
96696
98628
|
};
|
|
96697
98629
|
label = (path6) => {
|
|
96698
|
-
const suffix = relative3(
|
|
98630
|
+
const suffix = relative3(homedir5(), path6);
|
|
96699
98631
|
return suffix === "" ? "~" : !isAbsolute16(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path6;
|
|
96700
98632
|
};
|
|
96701
98633
|
identify = async (bindingId, requestedPath2, signal) => {
|
|
@@ -96744,7 +98676,7 @@ var WorkspaceDirectoryService = class {
|
|
|
96744
98676
|
continue;
|
|
96745
98677
|
}
|
|
96746
98678
|
try {
|
|
96747
|
-
const path6 = await this.resolvePath(
|
|
98679
|
+
const path6 = await this.resolvePath(join30(target, child.name), signal);
|
|
96748
98680
|
entries.push({ directoryId: encodePath(path6), name: child.name });
|
|
96749
98681
|
} catch (cause) {
|
|
96750
98682
|
signal.throwIfAborted();
|
|
@@ -96929,13 +98861,13 @@ function buildSessionLayer(options) {
|
|
|
96929
98861
|
|
|
96930
98862
|
// src/engine/session/content/external-content-store.ts
|
|
96931
98863
|
import { createHash as createHash8 } from "node:crypto";
|
|
96932
|
-
import { extname as extname2, join as
|
|
98864
|
+
import { extname as extname2, join as join32 } from "node:path";
|
|
96933
98865
|
import { pathToFileURL as pathToFileURL3 } from "node:url";
|
|
96934
98866
|
|
|
96935
98867
|
// src/engine/storage/files/scratch-directory.ts
|
|
96936
98868
|
import { randomUUID as randomUUID18 } from "node:crypto";
|
|
96937
|
-
import { lstat as lstat4, mkdir as mkdir5, readdir as readdir6, readFile as
|
|
96938
|
-
import { dirname as dirname11, join as
|
|
98869
|
+
import { lstat as lstat4, mkdir as mkdir5, readdir as readdir6, readFile as readFile8, realpath as realpath7, rename as rename4, rm as rm5, stat as stat6, utimes, writeFile as writeFile2 } from "node:fs/promises";
|
|
98870
|
+
import { dirname as dirname11, join as join31 } from "node:path";
|
|
96939
98871
|
async function atomicWrite(path6, bytes, signal) {
|
|
96940
98872
|
const temporary = `${path6}.${randomUUID18()}.tmp`;
|
|
96941
98873
|
try {
|
|
@@ -96949,7 +98881,7 @@ async function atomicWrite(path6, bytes, signal) {
|
|
|
96949
98881
|
var ScratchDirectory = class {
|
|
96950
98882
|
#root;
|
|
96951
98883
|
constructor(parent) {
|
|
96952
|
-
this.#root =
|
|
98884
|
+
this.#root = join31(parent, randomUUID18());
|
|
96953
98885
|
}
|
|
96954
98886
|
/** Refreshes this directory's lease and removes sibling directories whose lease is older than `leaseMilliseconds`. */
|
|
96955
98887
|
refreshLease = async (leaseMilliseconds) => {
|
|
@@ -96960,7 +98892,7 @@ var ScratchDirectory = class {
|
|
|
96960
98892
|
if (!directory.isDirectory() || !/^[a-f0-9-]{36}$/u.test(directory.name)) {
|
|
96961
98893
|
continue;
|
|
96962
98894
|
}
|
|
96963
|
-
const path6 =
|
|
98895
|
+
const path6 = join31(dirname11(this.#root), directory.name);
|
|
96964
98896
|
if (path6 === this.#root) {
|
|
96965
98897
|
continue;
|
|
96966
98898
|
}
|
|
@@ -96975,10 +98907,10 @@ var ScratchDirectory = class {
|
|
|
96975
98907
|
};
|
|
96976
98908
|
/** Writes `bytes` atomically to `<group>/<name>` with owner-only permissions and returns the path. */
|
|
96977
98909
|
write = async (group, name2, bytes, signal) => {
|
|
96978
|
-
const directory =
|
|
98910
|
+
const directory = join31(this.#root, group);
|
|
96979
98911
|
await mkdir5(directory, { mode: 448, recursive: true });
|
|
96980
98912
|
signal.throwIfAborted();
|
|
96981
|
-
const path6 =
|
|
98913
|
+
const path6 = join31(directory, name2);
|
|
96982
98914
|
await atomicWrite(path6, bytes, signal);
|
|
96983
98915
|
return path6;
|
|
96984
98916
|
};
|
|
@@ -97002,7 +98934,7 @@ var ScratchDirectory = class {
|
|
|
97002
98934
|
read = async (path6, signal) => {
|
|
97003
98935
|
const resolved = await this.resolveFile(path6);
|
|
97004
98936
|
signal.throwIfAborted();
|
|
97005
|
-
return resolved === null ? null : new Uint8Array(await
|
|
98937
|
+
return resolved === null ? null : new Uint8Array(await readFile8(resolved, { signal }));
|
|
97006
98938
|
};
|
|
97007
98939
|
removeAll = async () => {
|
|
97008
98940
|
await rm5(this.#root, { force: true, recursive: true });
|
|
@@ -97029,7 +98961,7 @@ var LocalExternalContentStore = class {
|
|
|
97029
98961
|
#expirationTimer;
|
|
97030
98962
|
#cleanup = Promise.resolve();
|
|
97031
98963
|
constructor(stateDirectory) {
|
|
97032
|
-
this.#scratch = new ScratchDirectory(
|
|
98964
|
+
this.#scratch = new ScratchDirectory(join32(stateDirectory, "tmp", "session-content"));
|
|
97033
98965
|
this.#expirationTimer = setInterval(() => {
|
|
97034
98966
|
void this.#expire().catch(() => void 0);
|
|
97035
98967
|
}, 6e4);
|
|
@@ -97437,7 +99369,7 @@ var AgentProcessPool = class {
|
|
|
97437
99369
|
|
|
97438
99370
|
// src/engine/session/settings/agent-settings-cache.ts
|
|
97439
99371
|
import { createHash as createHash9, randomUUID as randomUUID19 } from "node:crypto";
|
|
97440
|
-
import { join as
|
|
99372
|
+
import { join as join33 } from "node:path";
|
|
97441
99373
|
var CACHE_FILE_LIMIT = 32 * 1024 * 1024;
|
|
97442
99374
|
var CACHE_FORMAT = 1;
|
|
97443
99375
|
var generationSchema = external_exports.union([external_exports.literal("initial"), external_exports.uuid()]);
|
|
@@ -97502,8 +99434,8 @@ var AgentSettingsCache = class {
|
|
|
97502
99434
|
#generationPath;
|
|
97503
99435
|
#generation = 0;
|
|
97504
99436
|
constructor(stateDirectory) {
|
|
97505
|
-
this.#directory =
|
|
97506
|
-
this.#generationPath =
|
|
99437
|
+
this.#directory = join33(stateDirectory, "agent-settings");
|
|
99438
|
+
this.#generationPath = join33(this.#directory, "generation");
|
|
97507
99439
|
}
|
|
97508
99440
|
get generation() {
|
|
97509
99441
|
return this.#generation;
|
|
@@ -97514,7 +99446,7 @@ var AgentSettingsCache = class {
|
|
|
97514
99446
|
};
|
|
97515
99447
|
open = async (agent2, signal) => {
|
|
97516
99448
|
const inspections = /* @__PURE__ */ new Map();
|
|
97517
|
-
const path6 =
|
|
99449
|
+
const path6 = join33(this.#directory, `${hash2(agent2.id)}.json`);
|
|
97518
99450
|
const fingerprint = hash2([
|
|
97519
99451
|
agent2.agentVersion,
|
|
97520
99452
|
agent2.adapterVersion,
|
|
@@ -97605,6 +99537,243 @@ var AgentSettingsCache = class {
|
|
|
97605
99537
|
};
|
|
97606
99538
|
};
|
|
97607
99539
|
|
|
99540
|
+
// src/engine/session/usage/runtime-usage-service.ts
|
|
99541
|
+
var MANUAL_REFRESH_COOLDOWN_MILLISECONDS = 3e4;
|
|
99542
|
+
var DEFAULT_CACHE_TTL_MILLISECONDS = 6e4;
|
|
99543
|
+
var RATE_LIMITED_PROVIDER_CACHE_TTL_MILLISECONDS = 5 * 6e4;
|
|
99544
|
+
var AGENT_PROBE_TIMEOUT_MILLISECONDS = 25e3;
|
|
99545
|
+
function cacheTtlForAgent(agentId) {
|
|
99546
|
+
return agentId === "claude" || agentId === "antigravity" ? RATE_LIMITED_PROVIDER_CACHE_TTL_MILLISECONDS : DEFAULT_CACHE_TTL_MILLISECONDS;
|
|
99547
|
+
}
|
|
99548
|
+
function applyElapsedWindows(reading, nowMs) {
|
|
99549
|
+
if (reading.status !== "available") {
|
|
99550
|
+
return reading;
|
|
99551
|
+
}
|
|
99552
|
+
let changed = false;
|
|
99553
|
+
const windows = reading.windows.map((window2) => {
|
|
99554
|
+
if (window2.resetsAt === void 0) {
|
|
99555
|
+
return window2;
|
|
99556
|
+
}
|
|
99557
|
+
const resetMs = Date.parse(window2.resetsAt);
|
|
99558
|
+
if (!Number.isFinite(resetMs) || resetMs > nowMs) {
|
|
99559
|
+
return window2;
|
|
99560
|
+
}
|
|
99561
|
+
changed = true;
|
|
99562
|
+
const { resetsAt: _expired, ...rest } = window2;
|
|
99563
|
+
return {
|
|
99564
|
+
...rest,
|
|
99565
|
+
usedPercent: 0,
|
|
99566
|
+
remainingPercent: 100
|
|
99567
|
+
};
|
|
99568
|
+
});
|
|
99569
|
+
return changed ? { ...reading, windows } : reading;
|
|
99570
|
+
}
|
|
99571
|
+
function mergeWindows(existing, incoming) {
|
|
99572
|
+
if (incoming.length === 0) {
|
|
99573
|
+
return existing;
|
|
99574
|
+
}
|
|
99575
|
+
const merged = [...existing];
|
|
99576
|
+
for (const update of incoming) {
|
|
99577
|
+
if (update.id === "seven_day_overage_included") {
|
|
99578
|
+
const scopedIndex = merged.findIndex(
|
|
99579
|
+
(candidate) => candidate.group === "Models" && candidate.id.startsWith("seven_day_")
|
|
99580
|
+
);
|
|
99581
|
+
if (scopedIndex >= 0) {
|
|
99582
|
+
const target = merged[scopedIndex];
|
|
99583
|
+
if (target !== void 0) {
|
|
99584
|
+
merged[scopedIndex] = {
|
|
99585
|
+
...target,
|
|
99586
|
+
usedPercent: update.usedPercent,
|
|
99587
|
+
remainingPercent: update.remainingPercent,
|
|
99588
|
+
...update.resetsAt === void 0 ? {} : { resetsAt: update.resetsAt }
|
|
99589
|
+
};
|
|
99590
|
+
}
|
|
99591
|
+
}
|
|
99592
|
+
continue;
|
|
99593
|
+
}
|
|
99594
|
+
const index2 = merged.findIndex((candidate) => candidate.id === update.id);
|
|
99595
|
+
if (index2 >= 0) {
|
|
99596
|
+
merged[index2] = update;
|
|
99597
|
+
} else {
|
|
99598
|
+
merged.push(update);
|
|
99599
|
+
}
|
|
99600
|
+
}
|
|
99601
|
+
return merged;
|
|
99602
|
+
}
|
|
99603
|
+
function raceWithCallerSignal(promise2, signal) {
|
|
99604
|
+
if (signal.aborted) {
|
|
99605
|
+
return Promise.reject(signal.reason ?? new Error("Usage read aborted"));
|
|
99606
|
+
}
|
|
99607
|
+
return new Promise((resolve21, reject2) => {
|
|
99608
|
+
const onAbort = () => {
|
|
99609
|
+
reject2(signal.reason ?? new Error("Usage read aborted"));
|
|
99610
|
+
};
|
|
99611
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
99612
|
+
promise2.then(
|
|
99613
|
+
(value) => {
|
|
99614
|
+
signal.removeEventListener("abort", onAbort);
|
|
99615
|
+
resolve21(value);
|
|
99616
|
+
},
|
|
99617
|
+
(error62) => {
|
|
99618
|
+
signal.removeEventListener("abort", onAbort);
|
|
99619
|
+
reject2(error62);
|
|
99620
|
+
}
|
|
99621
|
+
);
|
|
99622
|
+
});
|
|
99623
|
+
}
|
|
99624
|
+
var RuntimeUsageService = class {
|
|
99625
|
+
#listAgents;
|
|
99626
|
+
#resolveAgent;
|
|
99627
|
+
#defaultWorkspace;
|
|
99628
|
+
#now;
|
|
99629
|
+
#cache = /* @__PURE__ */ new Map();
|
|
99630
|
+
constructor(dependencies) {
|
|
99631
|
+
this.#listAgents = dependencies.listAgents;
|
|
99632
|
+
this.#resolveAgent = dependencies.resolveAgent;
|
|
99633
|
+
this.#defaultWorkspace = dependencies.defaultWorkspace;
|
|
99634
|
+
this.#now = dependencies.now ?? (() => Date.now());
|
|
99635
|
+
}
|
|
99636
|
+
#entry = (agentId) => {
|
|
99637
|
+
const existing = this.#cache.get(agentId);
|
|
99638
|
+
if (existing !== void 0) {
|
|
99639
|
+
return existing;
|
|
99640
|
+
}
|
|
99641
|
+
const created = {
|
|
99642
|
+
lastGood: null,
|
|
99643
|
+
lastResult: null,
|
|
99644
|
+
lastAttemptAtMs: null,
|
|
99645
|
+
lastPassiveAtMs: null,
|
|
99646
|
+
inFlight: null
|
|
99647
|
+
};
|
|
99648
|
+
this.#cache.set(agentId, created);
|
|
99649
|
+
return created;
|
|
99650
|
+
};
|
|
99651
|
+
/** Merges a passive quota update observed during a live session without triggering a probe. */
|
|
99652
|
+
recordPassiveUpdate = (report) => {
|
|
99653
|
+
const entry = this.#entry(report.agentId);
|
|
99654
|
+
const nowMs = this.#now();
|
|
99655
|
+
entry.lastPassiveAtMs = nowMs;
|
|
99656
|
+
const previous = entry.lastGood;
|
|
99657
|
+
const windows = mergeWindows(previous?.windows ?? [], report.windows);
|
|
99658
|
+
const plan = report.plan ?? previous?.plan;
|
|
99659
|
+
const accountLabel = report.accountLabel ?? previous?.accountLabel;
|
|
99660
|
+
const credits = report.credits ?? previous?.credits;
|
|
99661
|
+
const resetCredits = previous?.resetCredits;
|
|
99662
|
+
const updated = {
|
|
99663
|
+
agentId: report.agentId,
|
|
99664
|
+
status: "available",
|
|
99665
|
+
checkedAt: report.observedAt,
|
|
99666
|
+
...plan === void 0 ? {} : { plan },
|
|
99667
|
+
...accountLabel === void 0 ? {} : { accountLabel },
|
|
99668
|
+
windows,
|
|
99669
|
+
...credits === void 0 ? {} : { credits },
|
|
99670
|
+
...resetCredits === void 0 ? {} : { resetCredits }
|
|
99671
|
+
};
|
|
99672
|
+
entry.lastGood = updated;
|
|
99673
|
+
entry.lastResult = updated;
|
|
99674
|
+
};
|
|
99675
|
+
readUsage = async (options) => {
|
|
99676
|
+
options.signal.throwIfAborted();
|
|
99677
|
+
const installed = this.#listAgents().map((agent2) => agent2.id);
|
|
99678
|
+
const installedSet = new Set(installed);
|
|
99679
|
+
const targetIds = options.agentIds === void 0 ? installed : [...new Set(options.agentIds)].filter((agentId) => installedSet.has(agentId));
|
|
99680
|
+
return await Promise.all(
|
|
99681
|
+
targetIds.map(async (agentId) => await this.#readAgent(agentId, options.forceRefresh, options.signal))
|
|
99682
|
+
);
|
|
99683
|
+
};
|
|
99684
|
+
#readAgent = async (agentId, forceRefresh, signal) => {
|
|
99685
|
+
signal.throwIfAborted();
|
|
99686
|
+
const entry = this.#entry(agentId);
|
|
99687
|
+
const nowMs = this.#now();
|
|
99688
|
+
if (entry.inFlight !== null) {
|
|
99689
|
+
const result = await raceWithCallerSignal(entry.inFlight, signal);
|
|
99690
|
+
return applyElapsedWindows(result, this.#now());
|
|
99691
|
+
}
|
|
99692
|
+
if (entry.lastResult !== null && entry.lastAttemptAtMs !== null) {
|
|
99693
|
+
const elapsedSinceAttempt = nowMs - entry.lastAttemptAtMs;
|
|
99694
|
+
if (forceRefresh && elapsedSinceAttempt < MANUAL_REFRESH_COOLDOWN_MILLISECONDS) {
|
|
99695
|
+
return applyElapsedWindows(entry.lastResult, nowMs);
|
|
99696
|
+
}
|
|
99697
|
+
if (!forceRefresh && elapsedSinceAttempt < cacheTtlForAgent(agentId)) {
|
|
99698
|
+
return applyElapsedWindows(entry.lastResult, nowMs);
|
|
99699
|
+
}
|
|
99700
|
+
}
|
|
99701
|
+
const probeSignal = AbortSignal.timeout(AGENT_PROBE_TIMEOUT_MILLISECONDS);
|
|
99702
|
+
const probe = this.#probeAgent(agentId, entry, probeSignal);
|
|
99703
|
+
entry.inFlight = probe;
|
|
99704
|
+
try {
|
|
99705
|
+
const result = await raceWithCallerSignal(probe, signal);
|
|
99706
|
+
return applyElapsedWindows(result, this.#now());
|
|
99707
|
+
} finally {
|
|
99708
|
+
if (entry.inFlight === probe) {
|
|
99709
|
+
entry.inFlight = null;
|
|
99710
|
+
}
|
|
99711
|
+
}
|
|
99712
|
+
};
|
|
99713
|
+
#probeAgent = async (agentId, entry, signal) => {
|
|
99714
|
+
const startedAtMs = this.#now();
|
|
99715
|
+
entry.lastAttemptAtMs = startedAtMs;
|
|
99716
|
+
let fresh;
|
|
99717
|
+
try {
|
|
99718
|
+
const resolved = await this.#resolveAgent(agentId, signal);
|
|
99719
|
+
if (resolved.adapter.readUsageQuota === void 0) {
|
|
99720
|
+
fresh = {
|
|
99721
|
+
agentId,
|
|
99722
|
+
status: "unsupported",
|
|
99723
|
+
checkedAt: new Date(this.#now()).toISOString(),
|
|
99724
|
+
reason: "agent_unsupported"
|
|
99725
|
+
};
|
|
99726
|
+
} else {
|
|
99727
|
+
fresh = await resolved.adapter.readUsageQuota({
|
|
99728
|
+
agent: resolved.agent,
|
|
99729
|
+
cwd: this.#defaultWorkspace,
|
|
99730
|
+
signal
|
|
99731
|
+
});
|
|
99732
|
+
}
|
|
99733
|
+
} catch (error62) {
|
|
99734
|
+
const checkedAt = new Date(this.#now()).toISOString();
|
|
99735
|
+
const message = error62 instanceof Error && error62.message.trim().length > 0 ? error62.message.trim().slice(0, 256) : "The agent usage probe failed.";
|
|
99736
|
+
fresh = {
|
|
99737
|
+
agentId,
|
|
99738
|
+
status: "unavailable",
|
|
99739
|
+
checkedAt,
|
|
99740
|
+
errorCode: signal.aborted ? "usage_probe_timeout" : "usage_probe_failed",
|
|
99741
|
+
errorMessage: message
|
|
99742
|
+
};
|
|
99743
|
+
}
|
|
99744
|
+
if (fresh.status === "available") {
|
|
99745
|
+
const existingGood = entry.lastGood;
|
|
99746
|
+
const merged = existingGood !== null && entry.lastPassiveAtMs !== null && entry.lastPassiveAtMs > startedAtMs ? {
|
|
99747
|
+
...fresh,
|
|
99748
|
+
windows: mergeWindows(fresh.windows, existingGood.windows),
|
|
99749
|
+
checkedAt: existingGood.checkedAt
|
|
99750
|
+
} : fresh;
|
|
99751
|
+
entry.lastGood = merged;
|
|
99752
|
+
entry.lastResult = merged;
|
|
99753
|
+
return merged;
|
|
99754
|
+
}
|
|
99755
|
+
if (fresh.status === "unauthenticated" || fresh.status === "unsupported") {
|
|
99756
|
+
entry.lastGood = null;
|
|
99757
|
+
entry.lastResult = fresh;
|
|
99758
|
+
return fresh;
|
|
99759
|
+
}
|
|
99760
|
+
if (entry.lastGood !== null) {
|
|
99761
|
+
const retained = {
|
|
99762
|
+
...entry.lastGood,
|
|
99763
|
+
stale: {
|
|
99764
|
+
errorCode: fresh.errorCode,
|
|
99765
|
+
errorMessage: fresh.errorMessage,
|
|
99766
|
+
failedAt: fresh.checkedAt
|
|
99767
|
+
}
|
|
99768
|
+
};
|
|
99769
|
+
entry.lastResult = retained;
|
|
99770
|
+
return retained;
|
|
99771
|
+
}
|
|
99772
|
+
entry.lastResult = fresh;
|
|
99773
|
+
return fresh;
|
|
99774
|
+
};
|
|
99775
|
+
};
|
|
99776
|
+
|
|
97608
99777
|
// src/engine/runtime/relay/diagnostics.ts
|
|
97609
99778
|
var MAX_DIAGNOSTIC_TEXT_LENGTH = 256;
|
|
97610
99779
|
function sanitizeDiagnosticText(value) {
|
|
@@ -97788,7 +99957,7 @@ var RelayConnectionDiagnostics = class {
|
|
|
97788
99957
|
};
|
|
97789
99958
|
|
|
97790
99959
|
// src/engine/runtime/relay/run-relay-connection.ts
|
|
97791
|
-
import { WebSocket as
|
|
99960
|
+
import { WebSocket as WebSocket9 } from "undici";
|
|
97792
99961
|
|
|
97793
99962
|
// src/engine/runtime/catalog/handle-agent-catalog-discovery.ts
|
|
97794
99963
|
import { WebSocket as WebSocket3 } from "undici";
|
|
@@ -98539,7 +100708,7 @@ function createContentWriteCommands(context) {
|
|
|
98539
100708
|
import { WebSocket as WebSocket5 } from "undici";
|
|
98540
100709
|
|
|
98541
100710
|
// src/engine/session/content/session-files.ts
|
|
98542
|
-
import { basename as basename9, extname as extname3, isAbsolute as isAbsolute17, join as
|
|
100711
|
+
import { basename as basename9, extname as extname3, isAbsolute as isAbsolute17, join as join34, normalize as normalize3, resolve as resolve18 } from "node:path";
|
|
98543
100712
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
98544
100713
|
function requestedPath(value) {
|
|
98545
100714
|
if (value.includes("\0")) {
|
|
@@ -98563,7 +100732,7 @@ async function resolveFile(value, workingDirectory, signal) {
|
|
|
98563
100732
|
if (isAbsolute17(requested.path) && normalize3(requested.path) !== requested.path) {
|
|
98564
100733
|
return null;
|
|
98565
100734
|
}
|
|
98566
|
-
const candidates = requested.explicitUrl || workingDirectory === null ? [requested.path] : isAbsolute17(requested.path) ? [
|
|
100735
|
+
const candidates = requested.explicitUrl || workingDirectory === null ? [requested.path] : isAbsolute17(requested.path) ? [join34(workingDirectory, requested.path), requested.path] : [resolve18(workingDirectory, requested.path)];
|
|
98567
100736
|
for (const candidate of candidates) {
|
|
98568
100737
|
if (!isAbsolute17(candidate) || normalize3(candidate) !== candidate) {
|
|
98569
100738
|
continue;
|
|
@@ -99458,6 +101627,9 @@ var sessionPromptSuggestionReadCommand = {
|
|
|
99458
101627
|
}
|
|
99459
101628
|
};
|
|
99460
101629
|
|
|
101630
|
+
// src/engine/runtime/command/registry/runtime.ts
|
|
101631
|
+
import { WebSocket as WebSocket7 } from "undici";
|
|
101632
|
+
|
|
99461
101633
|
// src/engine/runtime/observability/environment-diagnostics.ts
|
|
99462
101634
|
import { release } from "node:os";
|
|
99463
101635
|
function version2(value) {
|
|
@@ -99565,10 +101737,59 @@ var runtimePingCommand = {
|
|
|
99565
101737
|
promptSuggestions: true,
|
|
99566
101738
|
sessionTitleGeneration: true,
|
|
99567
101739
|
requestId: message.requestId,
|
|
99568
|
-
scopedFileRead: supportsScopedLocalFileRead()
|
|
101740
|
+
scopedFileRead: supportsScopedLocalFileRead(),
|
|
101741
|
+
usageQuota: true
|
|
99569
101742
|
});
|
|
99570
101743
|
}
|
|
99571
101744
|
};
|
|
101745
|
+
function createRuntimeUsageReadCommand() {
|
|
101746
|
+
const active = /* @__PURE__ */ new Set();
|
|
101747
|
+
return {
|
|
101748
|
+
kind: RUNTIME_USAGE_READ_KIND,
|
|
101749
|
+
handle: ({ diagnostics, signal, socket, usageService }, message) => {
|
|
101750
|
+
if (message.kind !== RUNTIME_USAGE_READ_KIND) {
|
|
101751
|
+
throw new Error("Command kind mismatch");
|
|
101752
|
+
}
|
|
101753
|
+
const task = (async () => {
|
|
101754
|
+
try {
|
|
101755
|
+
const agents = await usageService.readUsage({
|
|
101756
|
+
...message.agentIds === void 0 ? {} : { agentIds: message.agentIds },
|
|
101757
|
+
forceRefresh: message.forceRefresh ?? false,
|
|
101758
|
+
signal
|
|
101759
|
+
});
|
|
101760
|
+
if (socket.readyState === WebSocket7.OPEN) {
|
|
101761
|
+
send(socket, {
|
|
101762
|
+
kind: RUNTIME_USAGE_RESULT_KIND,
|
|
101763
|
+
requestId: message.requestId,
|
|
101764
|
+
state: "supported",
|
|
101765
|
+
collectedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
101766
|
+
agents
|
|
101767
|
+
});
|
|
101768
|
+
}
|
|
101769
|
+
} catch (error62) {
|
|
101770
|
+
if (signal.aborted) {
|
|
101771
|
+
return;
|
|
101772
|
+
}
|
|
101773
|
+
diagnostics.daemonDiagnostic("runtime_usage_read_failed", message.requestId, {}, error62);
|
|
101774
|
+
if (socket.readyState === WebSocket7.OPEN) {
|
|
101775
|
+
send(socket, {
|
|
101776
|
+
kind: SESSION_OPERATION_FAILED_KIND,
|
|
101777
|
+
requestId: message.requestId,
|
|
101778
|
+
sessionId: "runtime",
|
|
101779
|
+
code: "runtime_usage_unavailable",
|
|
101780
|
+
message: "Runtime usage quotas are unavailable."
|
|
101781
|
+
});
|
|
101782
|
+
}
|
|
101783
|
+
}
|
|
101784
|
+
})();
|
|
101785
|
+
active.add(task);
|
|
101786
|
+
void task.finally(() => active.delete(task));
|
|
101787
|
+
},
|
|
101788
|
+
settle: async () => {
|
|
101789
|
+
await Promise.allSettled([...active]);
|
|
101790
|
+
}
|
|
101791
|
+
};
|
|
101792
|
+
}
|
|
99572
101793
|
|
|
99573
101794
|
// src/engine/runtime/command/registry/session.ts
|
|
99574
101795
|
async function prepareSession(command, recovery, closed, config2, resolveAgent, directories, sessions, metrics, signal) {
|
|
@@ -99961,6 +102182,7 @@ function createCommandRegistry(context) {
|
|
|
99961
102182
|
const commands = [
|
|
99962
102183
|
runtimeDiagnosticsCommand,
|
|
99963
102184
|
runtimePingCommand,
|
|
102185
|
+
createRuntimeUsageReadCommand(),
|
|
99964
102186
|
sessionHistoryPageLoadCommand,
|
|
99965
102187
|
previewHistoryPageLoadCommand,
|
|
99966
102188
|
...createNativeSessionCommands(context),
|
|
@@ -100022,7 +102244,7 @@ function createRuntimeCommandDispatcher(options) {
|
|
|
100022
102244
|
}
|
|
100023
102245
|
|
|
100024
102246
|
// src/engine/runtime/relay/connect.ts
|
|
100025
|
-
import { WebSocket as
|
|
102247
|
+
import { WebSocket as WebSocket8 } from "undici";
|
|
100026
102248
|
var CONNECTION_TIMEOUT_MILLISECONDS = 6e4;
|
|
100027
102249
|
var RelayConnectionError = class extends Error {
|
|
100028
102250
|
code;
|
|
@@ -100036,7 +102258,7 @@ var RelayConnectionError = class extends Error {
|
|
|
100036
102258
|
};
|
|
100037
102259
|
function connectRelay(url2, signal, transportFailed = () => void 0) {
|
|
100038
102260
|
signal.throwIfAborted();
|
|
100039
|
-
return new Promise((
|
|
102261
|
+
return new Promise((resolve21, reject2) => {
|
|
100040
102262
|
let releaseTransport = () => void 0;
|
|
100041
102263
|
let removeTransportObserver = () => void 0;
|
|
100042
102264
|
let released = false;
|
|
@@ -100087,7 +102309,7 @@ function connectRelay(url2, signal, transportFailed = () => void 0) {
|
|
|
100087
102309
|
const endpoint = new URL(url2);
|
|
100088
102310
|
const headers = relayAuthorization(endpoint);
|
|
100089
102311
|
endpoint.searchParams.delete("token");
|
|
100090
|
-
const socket = new
|
|
102312
|
+
const socket = new WebSocket8(endpoint, {
|
|
100091
102313
|
dispatcher,
|
|
100092
102314
|
headers
|
|
100093
102315
|
});
|
|
@@ -100160,7 +102382,7 @@ function connectRelay(url2, signal, transportFailed = () => void 0) {
|
|
|
100160
102382
|
}
|
|
100161
102383
|
finished = true;
|
|
100162
102384
|
cleanup();
|
|
100163
|
-
|
|
102385
|
+
resolve21({ release: release2, socket });
|
|
100164
102386
|
};
|
|
100165
102387
|
function onTimeout() {
|
|
100166
102388
|
fail(
|
|
@@ -100293,6 +102515,7 @@ async function runRelayConnection({
|
|
|
100293
102515
|
reportUpgradeAvailability,
|
|
100294
102516
|
directories,
|
|
100295
102517
|
sessionTurns,
|
|
102518
|
+
usageService,
|
|
100296
102519
|
nativeSessions,
|
|
100297
102520
|
operations,
|
|
100298
102521
|
publisher,
|
|
@@ -100324,13 +102547,14 @@ async function runRelayConnection({
|
|
|
100324
102547
|
eventProjection,
|
|
100325
102548
|
externalContent,
|
|
100326
102549
|
sessionTurns,
|
|
102550
|
+
usageService,
|
|
100327
102551
|
diagnostics,
|
|
100328
102552
|
socket,
|
|
100329
102553
|
signal: connectionController.signal,
|
|
100330
102554
|
timer
|
|
100331
102555
|
});
|
|
100332
102556
|
void reportUpgradeAvailability((result) => {
|
|
100333
|
-
if (socket.readyState ===
|
|
102557
|
+
if (socket.readyState === WebSocket9.OPEN) {
|
|
100334
102558
|
send(socket, result);
|
|
100335
102559
|
}
|
|
100336
102560
|
}, signal).catch((cause) => {
|
|
@@ -100339,7 +102563,7 @@ async function runRelayConnection({
|
|
|
100339
102563
|
}
|
|
100340
102564
|
});
|
|
100341
102565
|
try {
|
|
100342
|
-
await new Promise((
|
|
102566
|
+
await new Promise((resolve21, reject2) => {
|
|
100343
102567
|
let finished = false;
|
|
100344
102568
|
let ready = false;
|
|
100345
102569
|
const cleanup = () => {
|
|
@@ -100357,7 +102581,7 @@ async function runRelayConnection({
|
|
|
100357
102581
|
}
|
|
100358
102582
|
finished = true;
|
|
100359
102583
|
cleanup();
|
|
100360
|
-
|
|
102584
|
+
resolve21();
|
|
100361
102585
|
};
|
|
100362
102586
|
const rejectConnection = (failure2) => {
|
|
100363
102587
|
if (finished) {
|
|
@@ -100381,14 +102605,14 @@ async function runRelayConnection({
|
|
|
100381
102605
|
};
|
|
100382
102606
|
const connectionLiveness = new RelayConnectionLiveness(timer, {
|
|
100383
102607
|
send: (message) => {
|
|
100384
|
-
if (socket.readyState !==
|
|
102608
|
+
if (socket.readyState !== WebSocket9.OPEN) {
|
|
100385
102609
|
return false;
|
|
100386
102610
|
}
|
|
100387
102611
|
try {
|
|
100388
102612
|
send(socket, message);
|
|
100389
102613
|
return true;
|
|
100390
102614
|
} catch (error62) {
|
|
100391
|
-
if (socket.readyState !==
|
|
102615
|
+
if (socket.readyState !== WebSocket9.OPEN) {
|
|
100392
102616
|
return false;
|
|
100393
102617
|
}
|
|
100394
102618
|
throw error62;
|
|
@@ -100490,7 +102714,7 @@ async function runRelayConnection({
|
|
|
100490
102714
|
}
|
|
100491
102715
|
|
|
100492
102716
|
// src/engine/runtime/relay/session-event-publisher.ts
|
|
100493
|
-
import { WebSocket as
|
|
102717
|
+
import { WebSocket as WebSocket10 } from "undici";
|
|
100494
102718
|
var MAX_BUFFERED_BYTES = 32 * 1024 * 1024;
|
|
100495
102719
|
var MAX_PENDING_BYTES2 = 32 * 1024 * 1024;
|
|
100496
102720
|
var MAX_EVENT_BATCH_BYTES = 1024 * 1024;
|
|
@@ -100545,7 +102769,7 @@ var RuntimeSessionEventPublisher = class {
|
|
|
100545
102769
|
};
|
|
100546
102770
|
#send = (message) => {
|
|
100547
102771
|
const connection = this.#connection;
|
|
100548
|
-
if (connection.kind !== "connected" || connection.socket.readyState !==
|
|
102772
|
+
if (connection.kind !== "connected" || connection.socket.readyState !== WebSocket10.OPEN) {
|
|
100549
102773
|
return;
|
|
100550
102774
|
}
|
|
100551
102775
|
const socket = connection.socket;
|
|
@@ -100607,7 +102831,7 @@ var RuntimeSessionEventPublisher = class {
|
|
|
100607
102831
|
});
|
|
100608
102832
|
}
|
|
100609
102833
|
const connection = this.#connection;
|
|
100610
|
-
if (connection.kind !== "connected" || connection.socket.readyState !==
|
|
102834
|
+
if (connection.kind !== "connected" || connection.socket.readyState !== WebSocket10.OPEN) {
|
|
100611
102835
|
return;
|
|
100612
102836
|
}
|
|
100613
102837
|
const socket = connection.socket;
|
|
@@ -100646,7 +102870,7 @@ var RuntimeSessionEventPublisher = class {
|
|
|
100646
102870
|
flushEvents = (socket) => {
|
|
100647
102871
|
this.cancelFlush();
|
|
100648
102872
|
const connection = this.#connection;
|
|
100649
|
-
if (connection.kind !== "connected" || connection.socket !== socket || socket.readyState !==
|
|
102873
|
+
if (connection.kind !== "connected" || connection.socket !== socket || socket.readyState !== WebSocket10.OPEN) {
|
|
100650
102874
|
return;
|
|
100651
102875
|
}
|
|
100652
102876
|
let sent = 0;
|
|
@@ -100693,12 +102917,12 @@ function waitForRelayRetry(signal, timer) {
|
|
|
100693
102917
|
if (signal.aborted) {
|
|
100694
102918
|
return Promise.resolve();
|
|
100695
102919
|
}
|
|
100696
|
-
return new Promise((
|
|
102920
|
+
return new Promise((resolve21) => {
|
|
100697
102921
|
const retry = timer.schedule(finish, RELAY_RECONNECT_DELAY_MILLISECONDS);
|
|
100698
102922
|
function finish() {
|
|
100699
102923
|
retry.cancel();
|
|
100700
102924
|
signal.removeEventListener("abort", finish);
|
|
100701
|
-
|
|
102925
|
+
resolve21();
|
|
100702
102926
|
}
|
|
100703
102927
|
signal.addEventListener("abort", finish, { once: true });
|
|
100704
102928
|
});
|
|
@@ -100743,11 +102967,13 @@ async function runRuntime(config2, parentSignal, timer = systemTimer, options =
|
|
|
100743
102967
|
const publisher = new RuntimeSessionEventPublisher(timer);
|
|
100744
102968
|
const externalContent = __using(_stack, new LocalExternalContentStore(stateDirectory), true);
|
|
100745
102969
|
const processes = new AgentProcessPool(config2.localContext.maxAcpProcesses, timer);
|
|
102970
|
+
let usageService = null;
|
|
100746
102971
|
const { adapters, externalizeSessionUpdate } = createRuntimeAdapterRegistry(
|
|
100747
102972
|
config2.adapters,
|
|
100748
102973
|
processes,
|
|
100749
102974
|
(sessionId, content, contentSignal) => externalContent.put({ ...content, sessionId, signal: contentSignal }),
|
|
100750
|
-
externalContent.linkedResources
|
|
102975
|
+
externalContent.linkedResources,
|
|
102976
|
+
(report) => usageService?.recordPassiveUpdate(report)
|
|
100751
102977
|
);
|
|
100752
102978
|
const resolveAgent = async (agentId, resolveSignal, sessionId) => {
|
|
100753
102979
|
const catalogAgent = await resolveCatalogAgent(config2, agentId, resolveSignal);
|
|
@@ -100759,6 +102985,11 @@ async function runRuntime(config2, parentSignal, timer = systemTimer, options =
|
|
|
100759
102985
|
externalizeSessionUpdate
|
|
100760
102986
|
};
|
|
100761
102987
|
};
|
|
102988
|
+
usageService = new RuntimeUsageService({
|
|
102989
|
+
listAgents: () => config2.catalog.read().agents,
|
|
102990
|
+
resolveAgent,
|
|
102991
|
+
defaultWorkspace: config2.defaultWorkspace
|
|
102992
|
+
});
|
|
100762
102993
|
const layer = buildSessionLayer({
|
|
100763
102994
|
processes,
|
|
100764
102995
|
...options.turnActivity === void 0 ? {} : { turnActivity: options.turnActivity },
|
|
@@ -100837,6 +103068,7 @@ async function runRuntime(config2, parentSignal, timer = systemTimer, options =
|
|
|
100837
103068
|
eventProjection,
|
|
100838
103069
|
externalContent,
|
|
100839
103070
|
sessionTurns: activeSessions,
|
|
103071
|
+
usageService,
|
|
100840
103072
|
connectionEpoch,
|
|
100841
103073
|
reportUpgradeAvailability,
|
|
100842
103074
|
diagnostics,
|
|
@@ -100920,7 +103152,7 @@ function relayUrlFromConnection(connection) {
|
|
|
100920
103152
|
return relayUrl;
|
|
100921
103153
|
}
|
|
100922
103154
|
async function resolveWorkspace(path6) {
|
|
100923
|
-
const requested =
|
|
103155
|
+
const requested = resolve19(path6);
|
|
100924
103156
|
let resolved;
|
|
100925
103157
|
try {
|
|
100926
103158
|
resolved = await ensureCanonicalDirectory(requested);
|
|
@@ -101019,7 +103251,7 @@ var MobiusRuntimeEngine = class {
|
|
|
101019
103251
|
#connections;
|
|
101020
103252
|
#installation = { kind: "uninitialized" };
|
|
101021
103253
|
constructor(params) {
|
|
101022
|
-
this.#engineDataDir =
|
|
103254
|
+
this.#engineDataDir = resolve20(params.engineDataDir);
|
|
101023
103255
|
this.#agentLaunchEnvironment = Object.freeze({ ...params.agentLaunchEnvironment });
|
|
101024
103256
|
this.#maxAcpProcesses = params.maxAcpProcesses ?? 1e3;
|
|
101025
103257
|
this.#connections = new ConnectionManager(this.#ensureInstallation);
|
|
@@ -101140,4 +103372,4 @@ export {
|
|
|
101140
103372
|
* MIT Licensed
|
|
101141
103373
|
*)
|
|
101142
103374
|
*/
|
|
101143
|
-
//# sourceMappingURL=chunk-
|
|
103375
|
+
//# sourceMappingURL=chunk-GUE7ZQI6.js.map
|