@moxt-ai/mobius 0.0.454 → 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-7VYQEJW7.js → chunk-GUE7ZQI6.js} +2676 -200
- package/dist/{chunk-7VYQEJW7.js.map → chunk-GUE7ZQI6.js.map} +4 -4
- package/dist/{chunk-TOQQNYQU.js → chunk-H3JQ3BX5.js} +2 -2
- package/dist/{chunk-TOQQNYQU.js.map → chunk-H3JQ3BX5.js.map} +1 -1
- package/dist/{cli-CCIMF4WB.js → cli-E4GLG6NB.js} +3 -3
- package/dist/cli.js +2 -2
- package/dist/engine/acp/acp-error.d.ts +5 -0
- package/dist/engine/acp/acp-error.d.ts.map +1 -1
- package/dist/engine/acp/acp-error.js +5 -0
- package/dist/engine/acp/acp-error.js.map +1 -1
- package/dist/engine/acp/adapter/antigravity/adapter.d.ts +54 -0
- package/dist/engine/acp/adapter/antigravity/adapter.d.ts.map +1 -1
- package/dist/engine/acp/adapter/antigravity/adapter.js +35 -2
- package/dist/engine/acp/adapter/antigravity/adapter.js.map +1 -1
- package/dist/engine/acp/adapter/antigravity/agent-connection.d.ts +6 -0
- package/dist/engine/acp/adapter/antigravity/agent-connection.d.ts.map +1 -1
- package/dist/engine/acp/adapter/antigravity/agent-connection.js +20 -1
- package/dist/engine/acp/adapter/antigravity/agent-connection.js.map +1 -1
- package/dist/engine/acp/adapter/antigravity/background-wakeup.d.ts +2 -0
- package/dist/engine/acp/adapter/antigravity/background-wakeup.d.ts.map +1 -1
- package/dist/engine/acp/adapter/antigravity/background-wakeup.js +2 -2
- package/dist/engine/acp/adapter/antigravity/background-wakeup.js.map +1 -1
- package/dist/engine/acp/adapter/antigravity/conversation-handoff.d.ts +7 -0
- package/dist/engine/acp/adapter/antigravity/conversation-handoff.d.ts.map +1 -0
- package/dist/engine/acp/adapter/antigravity/conversation-handoff.js +110 -0
- package/dist/engine/acp/adapter/antigravity/conversation-handoff.js.map +1 -0
- 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 +16 -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/live/agent-session-restore.d.ts +1 -0
- package/dist/engine/session/live/agent-session-restore.d.ts.map +1 -1
- package/dist/engine/session/live/agent-session.d.ts +7 -1
- package/dist/engine/session/live/agent-session.d.ts.map +1 -1
- package/dist/engine/session/live/agent-session.js +14 -1
- package/dist/engine/session/live/agent-session.js.map +1 -1
- package/dist/engine/session/live/session-restore.d.ts +6 -0
- package/dist/engine/session/live/session-restore.d.ts.map +1 -1
- package/dist/engine/session/live/session-restore.js +26 -0
- package/dist/engine/session/live/session-restore.js.map +1 -1
- package/dist/engine/session/manager/session-manager.d.ts.map +1 -1
- package/dist/engine/session/manager/session-manager.js +26 -1
- package/dist/engine/session/manager/session-manager.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-CCIMF4WB.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
|
};
|
|
@@ -26978,6 +27080,7 @@ function operationErrorMessage(error62) {
|
|
|
26978
27080
|
}
|
|
26979
27081
|
|
|
26980
27082
|
// src/engine/acp/acp-error.ts
|
|
27083
|
+
var NATIVE_SESSION_UNUSABLE_ERROR_CODE = "native_session_unusable";
|
|
26981
27084
|
var AcpExecutionError = class extends OperationError {
|
|
26982
27085
|
constructor(message, options = {}, code = "acp_execution_failed") {
|
|
26983
27086
|
super(code, message, options);
|
|
@@ -27965,7 +28068,7 @@ function createWritableAcpStream(output2) {
|
|
|
27965
28068
|
if (outputFailure !== void 0) {
|
|
27966
28069
|
return Promise.reject(outputFailure);
|
|
27967
28070
|
}
|
|
27968
|
-
return new Promise((
|
|
28071
|
+
return new Promise((resolve21, reject2) => {
|
|
27969
28072
|
pendingWriteFailures.add(reject2);
|
|
27970
28073
|
output2.write(chunk, (error62) => {
|
|
27971
28074
|
pendingWriteFailures.delete(reject2);
|
|
@@ -27978,7 +28081,7 @@ function createWritableAcpStream(output2) {
|
|
|
27978
28081
|
reject2(outputFailure);
|
|
27979
28082
|
return;
|
|
27980
28083
|
}
|
|
27981
|
-
|
|
28084
|
+
resolve21();
|
|
27982
28085
|
});
|
|
27983
28086
|
});
|
|
27984
28087
|
},
|
|
@@ -29253,6 +29356,7 @@ var FULL_ACCESS_MODE_DESCRIPTION = "Never asks the user: approves file edits and
|
|
|
29253
29356
|
var MAXIMUM_STDERR_TAIL_CHARACTERS = 2048;
|
|
29254
29357
|
var MAXIMUM_PENDING_CONFIG_ECHOES = 16;
|
|
29255
29358
|
var CANCEL_REQUEST_METHOD2 = "$/cancel_request";
|
|
29359
|
+
var INVALID_THINKING_SIGNATURE_PATTERN = /\bmessages\.\d+\.content\.\d+(?:\.thinking\.signature: Field required|: Invalid `signature` in `thinking` block)/u;
|
|
29256
29360
|
function readStringProperty(record2, key) {
|
|
29257
29361
|
const value = record2[key];
|
|
29258
29362
|
return typeof value === "string" ? value : void 0;
|
|
@@ -29376,6 +29480,9 @@ async function prepareAntigravitySessionCancel(clientConnection2, sessionId) {
|
|
|
29376
29480
|
}
|
|
29377
29481
|
return await owner.prepareSessionCancel(sessionId);
|
|
29378
29482
|
}
|
|
29483
|
+
function takeAntigravityUnusableNativeSession(clientConnection2, sessionId) {
|
|
29484
|
+
return activeConnectionsByClient.get(clientConnection2)?.takeUnusableNativeSession(sessionId) ?? false;
|
|
29485
|
+
}
|
|
29379
29486
|
var AntigravityAgentConnection = class {
|
|
29380
29487
|
connection;
|
|
29381
29488
|
termination;
|
|
@@ -29389,6 +29496,8 @@ var AntigravityAgentConnection = class {
|
|
|
29389
29496
|
#messageStreams = /* @__PURE__ */ new Map();
|
|
29390
29497
|
#pendingRequests = /* @__PURE__ */ new Map();
|
|
29391
29498
|
#pendingConfigEchoes = [];
|
|
29499
|
+
/** Native sessions whose current prompt reported an unusable conversation. */
|
|
29500
|
+
#unusableSessions = /* @__PURE__ */ new Set();
|
|
29392
29501
|
#latestPermissionMode = { kind: "native" };
|
|
29393
29502
|
#sessionEstablished = false;
|
|
29394
29503
|
#closePromise = null;
|
|
@@ -29562,6 +29671,7 @@ var AntigravityAgentConnection = class {
|
|
|
29562
29671
|
await this.#flushDeliveries();
|
|
29563
29672
|
return disposition;
|
|
29564
29673
|
};
|
|
29674
|
+
takeUnusableNativeSession = (sessionId) => this.#unusableSessions.delete(sessionId);
|
|
29565
29675
|
initialize = async (signal) => {
|
|
29566
29676
|
signal.throwIfAborted();
|
|
29567
29677
|
};
|
|
@@ -29672,6 +29782,7 @@ var AntigravityAgentConnection = class {
|
|
|
29672
29782
|
case methods.agent.session.prompt: {
|
|
29673
29783
|
if (sessionId !== void 0) {
|
|
29674
29784
|
this.#messageStreams.set(sessionId, { kind: "none" });
|
|
29785
|
+
this.#unusableSessions.delete(sessionId);
|
|
29675
29786
|
}
|
|
29676
29787
|
return message;
|
|
29677
29788
|
}
|
|
@@ -29795,6 +29906,10 @@ var AntigravityAgentConnection = class {
|
|
|
29795
29906
|
}
|
|
29796
29907
|
const modeState = this.#permissionModes.get(sessionId) ?? { kind: "native" };
|
|
29797
29908
|
const updateKind = readStringProperty(update, "sessionUpdate");
|
|
29909
|
+
const executorError = updateKind === void 0 ? void 0 : extractExecutorError(updateKind, update);
|
|
29910
|
+
if (executorError !== void 0 && INVALID_THINKING_SIGNATURE_PATTERN.test(executorError)) {
|
|
29911
|
+
this.#unusableSessions.add(sessionId);
|
|
29912
|
+
}
|
|
29798
29913
|
if (updateKind === "config_option_update") {
|
|
29799
29914
|
if (this.#consumeConfigEcho(sessionId, update["configOptions"])) {
|
|
29800
29915
|
return void 0;
|
|
@@ -66755,11 +66870,11 @@ var Pushable = class {
|
|
|
66755
66870
|
done = false;
|
|
66756
66871
|
push(item) {
|
|
66757
66872
|
if (this.resolvers.length > 0) {
|
|
66758
|
-
const
|
|
66759
|
-
if (
|
|
66873
|
+
const resolve21 = this.resolvers.shift();
|
|
66874
|
+
if (resolve21 === void 0) {
|
|
66760
66875
|
return;
|
|
66761
66876
|
}
|
|
66762
|
-
|
|
66877
|
+
resolve21({ value: item, done: false });
|
|
66763
66878
|
} else {
|
|
66764
66879
|
this.queue.push(item);
|
|
66765
66880
|
}
|
|
@@ -66767,8 +66882,8 @@ var Pushable = class {
|
|
|
66767
66882
|
end() {
|
|
66768
66883
|
this.done = true;
|
|
66769
66884
|
while (this.resolvers.length > 0) {
|
|
66770
|
-
const
|
|
66771
|
-
|
|
66885
|
+
const resolve21 = this.resolvers.shift();
|
|
66886
|
+
resolve21?.({ done: true, value: void 0 });
|
|
66772
66887
|
}
|
|
66773
66888
|
}
|
|
66774
66889
|
[Symbol.asyncIterator]() {
|
|
@@ -66784,8 +66899,8 @@ var Pushable = class {
|
|
|
66784
66899
|
if (this.done) {
|
|
66785
66900
|
return Promise.resolve({ done: true, value: void 0 });
|
|
66786
66901
|
}
|
|
66787
|
-
return new Promise((
|
|
66788
|
-
this.resolvers.push(
|
|
66902
|
+
return new Promise((resolve21) => {
|
|
66903
|
+
this.resolvers.push(resolve21);
|
|
66789
66904
|
});
|
|
66790
66905
|
}
|
|
66791
66906
|
};
|
|
@@ -66803,14 +66918,14 @@ function unreachable(value, logger = console) {
|
|
|
66803
66918
|
async function withDeadline(signal, timeoutMilliseconds, operation) {
|
|
66804
66919
|
const deadline = AbortSignal.any([signal, AbortSignal.timeout(timeoutMilliseconds)]);
|
|
66805
66920
|
deadline.throwIfAborted();
|
|
66806
|
-
return await new Promise((
|
|
66921
|
+
return await new Promise((resolve21, reject2) => {
|
|
66807
66922
|
const settle2 = (callback) => {
|
|
66808
66923
|
deadline.removeEventListener("abort", onAbort);
|
|
66809
66924
|
callback();
|
|
66810
66925
|
};
|
|
66811
66926
|
const onAbort = () => settle2(() => reject2(deadline.reason));
|
|
66812
66927
|
deadline.addEventListener("abort", onAbort, { once: true });
|
|
66813
|
-
operation().then((value) => settle2(() =>
|
|
66928
|
+
operation().then((value) => settle2(() => resolve21(value)), (error62) => settle2(() => reject2(error62)));
|
|
66814
66929
|
});
|
|
66815
66930
|
}
|
|
66816
66931
|
var environmentChain = Promise.resolve();
|
|
@@ -69715,14 +69830,14 @@ function waitUnlessAborted(milliseconds, signal) {
|
|
|
69715
69830
|
if (signal.aborted) {
|
|
69716
69831
|
return Promise.resolve(false);
|
|
69717
69832
|
}
|
|
69718
|
-
return new Promise((
|
|
69833
|
+
return new Promise((resolve21) => {
|
|
69719
69834
|
const timer = setTimeout(() => {
|
|
69720
69835
|
signal.removeEventListener("abort", onAbort);
|
|
69721
|
-
|
|
69836
|
+
resolve21(true);
|
|
69722
69837
|
}, milliseconds);
|
|
69723
69838
|
const onAbort = () => {
|
|
69724
69839
|
clearTimeout(timer);
|
|
69725
|
-
|
|
69840
|
+
resolve21(false);
|
|
69726
69841
|
};
|
|
69727
69842
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
69728
69843
|
});
|
|
@@ -69983,7 +70098,7 @@ var ClientConnection = class {
|
|
|
69983
70098
|
}
|
|
69984
70099
|
};
|
|
69985
70100
|
function raceWithAbort(operation, signal) {
|
|
69986
|
-
return new Promise((
|
|
70101
|
+
return new Promise((resolve21, reject2) => {
|
|
69987
70102
|
const cleanup = () => signal.removeEventListener("abort", onAbort);
|
|
69988
70103
|
const onAbort = () => {
|
|
69989
70104
|
cleanup();
|
|
@@ -69995,7 +70110,7 @@ function raceWithAbort(operation, signal) {
|
|
|
69995
70110
|
}
|
|
69996
70111
|
void operation.then((value) => {
|
|
69997
70112
|
cleanup();
|
|
69998
|
-
|
|
70113
|
+
resolve21(value);
|
|
69999
70114
|
}, (error62) => {
|
|
70000
70115
|
cleanup();
|
|
70001
70116
|
reject2(error62);
|
|
@@ -70117,6 +70232,7 @@ var ClaudeAcpAgent = class {
|
|
|
70117
70232
|
spawnClaudeCodeProcess;
|
|
70118
70233
|
onBackgroundActivity;
|
|
70119
70234
|
onPromptSuggestion;
|
|
70235
|
+
onRateLimitEvent;
|
|
70120
70236
|
pendingSubmissions = /* @__PURE__ */ new Map();
|
|
70121
70237
|
sessions;
|
|
70122
70238
|
client;
|
|
@@ -70144,10 +70260,11 @@ var ClaudeAcpAgent = class {
|
|
|
70144
70260
|
* return "cancelled". See {@link DEFAULT_FORCE_CANCEL_GRACE_MS}. Mutable so
|
|
70145
70261
|
* tests can shrink it. */
|
|
70146
70262
|
forceCancelGraceMs = DEFAULT_FORCE_CANCEL_GRACE_MS;
|
|
70147
|
-
constructor(client2, logger, environment = process.env, spawnClaudeCodeProcess, onBackgroundActivity, onPromptSuggestion) {
|
|
70263
|
+
constructor(client2, logger, environment = process.env, spawnClaudeCodeProcess, onBackgroundActivity, onPromptSuggestion, onRateLimitEvent) {
|
|
70148
70264
|
this.spawnClaudeCodeProcess = spawnClaudeCodeProcess;
|
|
70149
70265
|
this.onBackgroundActivity = onBackgroundActivity;
|
|
70150
70266
|
this.onPromptSuggestion = onPromptSuggestion;
|
|
70267
|
+
this.onRateLimitEvent = onRateLimitEvent;
|
|
70151
70268
|
this.sessions = {};
|
|
70152
70269
|
this.client = client2;
|
|
70153
70270
|
this.logger = logger ?? console;
|
|
@@ -70610,12 +70727,12 @@ var ClaudeAcpAgent = class {
|
|
|
70610
70727
|
}
|
|
70611
70728
|
};
|
|
70612
70729
|
let completeTurn;
|
|
70613
|
-
turn.completion = new Promise((
|
|
70614
|
-
completeTurn =
|
|
70730
|
+
turn.completion = new Promise((resolve21) => {
|
|
70731
|
+
completeTurn = resolve21;
|
|
70615
70732
|
});
|
|
70616
|
-
const response = new Promise((
|
|
70733
|
+
const response = new Promise((resolve21, reject2) => {
|
|
70617
70734
|
turn.resolve = (result) => {
|
|
70618
|
-
|
|
70735
|
+
resolve21(result);
|
|
70619
70736
|
completeTurn();
|
|
70620
70737
|
};
|
|
70621
70738
|
turn.reject = (error62) => {
|
|
@@ -71192,8 +71309,8 @@ var ClaudeAcpAgent = class {
|
|
|
71192
71309
|
pendingNext ??= session.query.next().then((result) => ({ kind: "message", result }));
|
|
71193
71310
|
const nextMessage = pendingNext;
|
|
71194
71311
|
let onAbort;
|
|
71195
|
-
const abortRace = new Promise((
|
|
71196
|
-
onAbort = () =>
|
|
71312
|
+
const abortRace = new Promise((resolve21) => {
|
|
71313
|
+
onAbort = () => resolve21("abort");
|
|
71197
71314
|
cancelController.signal.addEventListener("abort", onAbort, { once: true });
|
|
71198
71315
|
});
|
|
71199
71316
|
const raced = await Promise.race([nextMessage, abortRace]);
|
|
@@ -72148,6 +72265,7 @@ ${message.api_refusal_explanation}` : "";
|
|
|
72148
72265
|
break;
|
|
72149
72266
|
}
|
|
72150
72267
|
case "rate_limit_event": {
|
|
72268
|
+
this.onRateLimitEvent?.(message.rate_limit_info);
|
|
72151
72269
|
if (lastAssistantTotalUsage !== null) {
|
|
72152
72270
|
await sendUpdate({
|
|
72153
72271
|
sessionId: message.session_id,
|
|
@@ -74689,7 +74807,7 @@ var AGENT_TURN_META2 = "mobius.agentTurn";
|
|
|
74689
74807
|
function createClaudeAcpApp(options = {}) {
|
|
74690
74808
|
let agent2 = null;
|
|
74691
74809
|
const app = agent({ name: "claude-code-acp" }).onConnect((connection) => {
|
|
74692
|
-
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);
|
|
74693
74811
|
options.onConnect?.(connection);
|
|
74694
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));
|
|
74695
74813
|
return { agent: () => agent2, app };
|
|
@@ -74801,6 +74919,881 @@ function getMatchingModelUsage(modelUsage, currentModel) {
|
|
|
74801
74919
|
}
|
|
74802
74920
|
}
|
|
74803
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
|
+
|
|
74804
75797
|
// src/engine/acp/harness/claude/endpoint.ts
|
|
74805
75798
|
var ClaudeAcpEndpoint = class {
|
|
74806
75799
|
#agent;
|
|
@@ -74826,6 +75819,14 @@ var ClaudeAcpEndpoint = class {
|
|
|
74826
75819
|
onSessionUpdate: options.onSessionUpdate,
|
|
74827
75820
|
onBackgroundActivity: (activity) => options.onBackgroundActivity?.(activity),
|
|
74828
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
|
+
},
|
|
74829
75830
|
onConnect: (connection) => {
|
|
74830
75831
|
this.#connection = connection;
|
|
74831
75832
|
}
|
|
@@ -74863,7 +75864,8 @@ var ClaudeAgentConnection = class extends EndpointAgentConnection {
|
|
|
74863
75864
|
await options.client.onUpdate(notification);
|
|
74864
75865
|
},
|
|
74865
75866
|
onBackgroundActivity: (activity) => options.onBackgroundActivity?.(activity),
|
|
74866
|
-
onPromptSuggestion: (report) => options.onPromptSuggestion?.(report)
|
|
75867
|
+
onPromptSuggestion: (report) => options.onPromptSuggestion?.(report),
|
|
75868
|
+
onUsageQuota: (report) => options.onUsageQuota?.(report)
|
|
74867
75869
|
});
|
|
74868
75870
|
super(endpoint, options.client);
|
|
74869
75871
|
}
|
|
@@ -74897,7 +75899,7 @@ var ClaudeCodeAgentSpecification = class extends InProcessAcpAgentSpecification
|
|
|
74897
75899
|
};
|
|
74898
75900
|
|
|
74899
75901
|
// src/engine/acp/harness/codex/app-server-client.ts
|
|
74900
|
-
import { spawn as
|
|
75902
|
+
import { spawn as spawn6 } from "node:child_process";
|
|
74901
75903
|
|
|
74902
75904
|
// src/engine/acp/harness/codex/app-server-protocol.ts
|
|
74903
75905
|
import { isAbsolute as isAbsolute9 } from "node:path";
|
|
@@ -75239,7 +76241,7 @@ var CodexAppServerClient = class {
|
|
|
75239
76241
|
constructor(options) {
|
|
75240
76242
|
this.#handlers = options.handlers;
|
|
75241
76243
|
const launch = executableLaunch2(options.command, ["app-server"]);
|
|
75242
|
-
this.#child =
|
|
76244
|
+
this.#child = spawn6(launch.command, [...launch.arguments], {
|
|
75243
76245
|
cwd: options.cwd,
|
|
75244
76246
|
...platformSpawnOptions,
|
|
75245
76247
|
env: { ...process.env, ...options.environment },
|
|
@@ -75629,12 +76631,12 @@ function presentToolItem(item) {
|
|
|
75629
76631
|
};
|
|
75630
76632
|
}
|
|
75631
76633
|
if (item.type === "collabAgentToolCall") {
|
|
75632
|
-
const
|
|
76634
|
+
const spawn9 = item.tool === "spawnAgent";
|
|
75633
76635
|
return {
|
|
75634
76636
|
content: [],
|
|
75635
76637
|
kind: "other",
|
|
75636
76638
|
locations: [],
|
|
75637
|
-
rawInput:
|
|
76639
|
+
rawInput: spawn9 ? {
|
|
75638
76640
|
model: item.model,
|
|
75639
76641
|
prompt: item.prompt,
|
|
75640
76642
|
reasoningEffort: item.reasoningEffort,
|
|
@@ -75642,10 +76644,10 @@ function presentToolItem(item) {
|
|
|
75642
76644
|
} : { receiverThreadIds: item.receiverThreadIds, senderThreadId: item.senderThreadId },
|
|
75643
76645
|
rawOutput: {
|
|
75644
76646
|
agentsStates: item.agentsStates,
|
|
75645
|
-
...
|
|
76647
|
+
...spawn9 ? { receiverThreadIds: item.receiverThreadIds } : {}
|
|
75646
76648
|
},
|
|
75647
76649
|
status: collaborationStatus(item.status),
|
|
75648
|
-
title:
|
|
76650
|
+
title: spawn9 ? "Dispatch subagent" : "Wait for subagent"
|
|
75649
76651
|
};
|
|
75650
76652
|
}
|
|
75651
76653
|
if (item.type === "subAgentActivity" && item.kind === "started") {
|
|
@@ -76621,10 +77623,10 @@ function turnRunning(turn) {
|
|
|
76621
77623
|
}
|
|
76622
77624
|
function waitForNextPoll(timer, signal) {
|
|
76623
77625
|
signal.throwIfAborted();
|
|
76624
|
-
return new Promise((
|
|
77626
|
+
return new Promise((resolve21, reject2) => {
|
|
76625
77627
|
const poll = timer.schedule(() => {
|
|
76626
77628
|
signal.removeEventListener("abort", abort);
|
|
76627
|
-
|
|
77629
|
+
resolve21();
|
|
76628
77630
|
}, POLL_INTERVAL);
|
|
76629
77631
|
const abort = () => {
|
|
76630
77632
|
poll.cancel();
|
|
@@ -77689,6 +78691,337 @@ var CodexSettings = class {
|
|
|
77689
78691
|
};
|
|
77690
78692
|
};
|
|
77691
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
|
+
|
|
77692
79025
|
// src/engine/acp/harness/codex/agent.ts
|
|
77693
79026
|
import { randomUUID as randomUUID10 } from "node:crypto";
|
|
77694
79027
|
var APPROVAL_TIMEOUT_MILLISECONDS3 = 36e5;
|
|
@@ -77740,6 +79073,7 @@ var CodexAcpAgent = class {
|
|
|
77740
79073
|
#onBackgroundActivity;
|
|
77741
79074
|
#onPromptDelegation;
|
|
77742
79075
|
#onPromptSuggestion;
|
|
79076
|
+
#onUsageQuota;
|
|
77743
79077
|
/** Whether this app-server serves `thread/sample`, which predicts the member's next prompt. */
|
|
77744
79078
|
#promptSampling = false;
|
|
77745
79079
|
#nativeSessionId = "";
|
|
@@ -77750,12 +79084,19 @@ var CodexAcpAgent = class {
|
|
|
77750
79084
|
this.#onBackgroundActivity = options.onBackgroundActivity;
|
|
77751
79085
|
this.#onPromptDelegation = options.onPromptDelegation;
|
|
77752
79086
|
this.#onPromptSuggestion = options.onPromptSuggestion;
|
|
79087
|
+
this.#onUsageQuota = options.onUsageQuota;
|
|
77753
79088
|
this.#appServer = new CodexAppServerClient({
|
|
77754
79089
|
command: options.command,
|
|
77755
79090
|
cwd: options.cwd,
|
|
77756
79091
|
environment: options.environment,
|
|
77757
79092
|
handlers: {
|
|
77758
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
|
+
}
|
|
77759
79100
|
await this.#sessionAgent.onNotification(method, params);
|
|
77760
79101
|
},
|
|
77761
79102
|
onServerRequest: async (request) => {
|
|
@@ -78063,7 +79404,8 @@ var CodexAgentConnection = class extends EndpointAgentConnection {
|
|
|
78063
79404
|
onSessionUpdate: options.client.onUpdate,
|
|
78064
79405
|
onBackgroundActivity: (activity) => options.onBackgroundActivity?.(activity),
|
|
78065
79406
|
onPromptDelegation: async (stage) => await options.onPromptDelegation?.(stage),
|
|
78066
|
-
onPromptSuggestion: (report) => options.onPromptSuggestion?.(report)
|
|
79407
|
+
onPromptSuggestion: (report) => options.onPromptSuggestion?.(report),
|
|
79408
|
+
onUsageQuota: (report) => options.onUsageQuota?.(report)
|
|
78067
79409
|
});
|
|
78068
79410
|
super(endpoint, options.client);
|
|
78069
79411
|
}
|
|
@@ -78094,7 +79436,7 @@ import { existsSync as existsSync8, readdirSync as readdirSync6, readFileSync as
|
|
|
78094
79436
|
import { basename as basename6, dirname as dirname8, isAbsolute as isAbsolute13, join as join22 } from "node:path";
|
|
78095
79437
|
|
|
78096
79438
|
// src/engine/acp/harness/pi/upstream/dist/pi-rpc/process.js
|
|
78097
|
-
import { spawn as
|
|
79439
|
+
import { spawn as spawn7 } from "node:child_process";
|
|
78098
79440
|
import * as readline from "node:readline";
|
|
78099
79441
|
|
|
78100
79442
|
// src/engine/acp/harness/pi/upstream/dist/pi-rpc/command.js
|
|
@@ -78211,17 +79553,17 @@ var PiRpcProcess = class _PiRpcProcess {
|
|
|
78211
79553
|
args.push("--fork", params.origin.sessionPath);
|
|
78212
79554
|
break;
|
|
78213
79555
|
}
|
|
78214
|
-
const child =
|
|
79556
|
+
const child = spawn7(cmd, args, {
|
|
78215
79557
|
cwd: params.cwd,
|
|
78216
79558
|
stdio: "pipe",
|
|
78217
79559
|
env: params.environment,
|
|
78218
79560
|
shell: shouldUseShellForPiCommand(cmd)
|
|
78219
79561
|
});
|
|
78220
79562
|
try {
|
|
78221
|
-
await new Promise((
|
|
79563
|
+
await new Promise((resolve21, reject2) => {
|
|
78222
79564
|
const onSpawn = () => {
|
|
78223
79565
|
cleanup();
|
|
78224
|
-
|
|
79566
|
+
resolve21();
|
|
78225
79567
|
};
|
|
78226
79568
|
const onError = (err) => {
|
|
78227
79569
|
cleanup();
|
|
@@ -78423,7 +79765,7 @@ var PiRpcProcess = class _PiRpcProcess {
|
|
|
78423
79765
|
const timeoutMs = opts?.timeoutMs;
|
|
78424
79766
|
const line = `${JSON.stringify(withId)}
|
|
78425
79767
|
`;
|
|
78426
|
-
return new Promise((
|
|
79768
|
+
return new Promise((resolve21, reject2) => {
|
|
78427
79769
|
const signal = opts?.signal;
|
|
78428
79770
|
if (signal?.aborted === true) {
|
|
78429
79771
|
reject2(signal.reason);
|
|
@@ -78445,7 +79787,7 @@ var PiRpcProcess = class _PiRpcProcess {
|
|
|
78445
79787
|
this.pending.set(id, {
|
|
78446
79788
|
resolve: (res) => {
|
|
78447
79789
|
drop();
|
|
78448
|
-
|
|
79790
|
+
resolve21(res);
|
|
78449
79791
|
},
|
|
78450
79792
|
reject: (error62) => {
|
|
78451
79793
|
drop();
|
|
@@ -78478,14 +79820,14 @@ var PiRpcProcess = class _PiRpcProcess {
|
|
|
78478
79820
|
});
|
|
78479
79821
|
}
|
|
78480
79822
|
writeLine(line) {
|
|
78481
|
-
return new Promise((
|
|
79823
|
+
return new Promise((resolve21, reject2) => {
|
|
78482
79824
|
try {
|
|
78483
79825
|
this.child.stdin.write(line, (error62) => {
|
|
78484
79826
|
if (error62) {
|
|
78485
79827
|
reject2(error62);
|
|
78486
79828
|
return;
|
|
78487
79829
|
}
|
|
78488
|
-
|
|
79830
|
+
resolve21();
|
|
78489
79831
|
});
|
|
78490
79832
|
} catch (error62) {
|
|
78491
79833
|
reject2(error62);
|
|
@@ -79840,8 +81182,8 @@ var PiAcpSession = class {
|
|
|
79840
81182
|
}
|
|
79841
81183
|
async prompt(message, images = []) {
|
|
79842
81184
|
const expandedMessage = expandSlashCommand(message, this.fileCommands);
|
|
79843
|
-
const turnPromise = new Promise((
|
|
79844
|
-
const queued = { message: expandedMessage, images, resolve:
|
|
81185
|
+
const turnPromise = new Promise((resolve21, reject2) => {
|
|
81186
|
+
const queued = { message: expandedMessage, images, resolve: resolve21, reject: reject2 };
|
|
79845
81187
|
if (this.pendingTurn) {
|
|
79846
81188
|
this.turnQueue.push(queued);
|
|
79847
81189
|
this.emit({
|
|
@@ -82873,8 +84215,8 @@ var AdapterRegistry = class {
|
|
|
82873
84215
|
#resolve;
|
|
82874
84216
|
#dependencies;
|
|
82875
84217
|
#adapters = /* @__PURE__ */ new Map();
|
|
82876
|
-
constructor(
|
|
82877
|
-
this.#resolve =
|
|
84218
|
+
constructor(resolve21, dependencies) {
|
|
84219
|
+
this.#resolve = resolve21;
|
|
82878
84220
|
this.#dependencies = dependencies;
|
|
82879
84221
|
}
|
|
82880
84222
|
resolve = (agent2) => {
|
|
@@ -82906,11 +84248,615 @@ async function runCleanup(...actions) {
|
|
|
82906
84248
|
}
|
|
82907
84249
|
}
|
|
82908
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
|
+
|
|
82909
84855
|
// src/engine/acp/protocol/native-session.ts
|
|
82910
84856
|
var nativeSessionIdSchema = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,255}$/);
|
|
82911
84857
|
|
|
82912
84858
|
// src/engine/acp/adapter/execution-connections.ts
|
|
82913
|
-
import { isAbsolute as isAbsolute15, resolve as
|
|
84859
|
+
import { isAbsolute as isAbsolute15, resolve as resolve15 } from "node:path";
|
|
82914
84860
|
|
|
82915
84861
|
// src/engine/acp/client/prompt-content.ts
|
|
82916
84862
|
function validatePromptContent(options, capabilities) {
|
|
@@ -83572,6 +85518,11 @@ var AdapterSessionConnection = class {
|
|
|
83572
85518
|
if (!this.#lifetime.signal.aborted) {
|
|
83573
85519
|
options.onPromptSuggestion?.(report);
|
|
83574
85520
|
}
|
|
85521
|
+
},
|
|
85522
|
+
onUsageQuota: (report) => {
|
|
85523
|
+
if (!this.#lifetime.signal.aborted) {
|
|
85524
|
+
options.onUsageQuota?.(report);
|
|
85525
|
+
}
|
|
83575
85526
|
}
|
|
83576
85527
|
});
|
|
83577
85528
|
}
|
|
@@ -83731,9 +85682,13 @@ var AcpExecutionConnections = class {
|
|
|
83731
85682
|
#closing = /* @__PURE__ */ new WeakSet();
|
|
83732
85683
|
#externalizer;
|
|
83733
85684
|
#normalizeEvent;
|
|
83734
|
-
|
|
85685
|
+
#onUsageQuota;
|
|
85686
|
+
constructor(externalizer, normalizeEvent = (event) => event, onUsageQuota) {
|
|
83735
85687
|
this.#externalizer = externalizer;
|
|
83736
85688
|
this.#normalizeEvent = normalizeEvent;
|
|
85689
|
+
if (onUsageQuota !== void 0) {
|
|
85690
|
+
this.#onUsageQuota = onUsageQuota;
|
|
85691
|
+
}
|
|
83737
85692
|
}
|
|
83738
85693
|
acquire = (params) => {
|
|
83739
85694
|
params.signal.throwIfAborted();
|
|
@@ -83759,6 +85714,7 @@ var AcpExecutionConnections = class {
|
|
|
83759
85714
|
...params.onBackgroundActivity === void 0 ? {} : { onBackgroundActivity: params.onBackgroundActivity },
|
|
83760
85715
|
...params.onPromptDelegation === void 0 ? {} : { onPromptDelegation: params.onPromptDelegation },
|
|
83761
85716
|
...params.onPromptSuggestion === void 0 ? {} : { onPromptSuggestion: params.onPromptSuggestion },
|
|
85717
|
+
...this.#onUsageQuota === void 0 ? {} : { onUsageQuota: this.#onUsageQuota },
|
|
83762
85718
|
...params.onAgentTurn === void 0 ? {} : { onAgentTurn: params.onAgentTurn },
|
|
83763
85719
|
...params.onBackgroundTasks === void 0 ? {} : { onBackgroundTasks: params.onBackgroundTasks },
|
|
83764
85720
|
interactions: params.interactions
|
|
@@ -83816,9 +85772,9 @@ var AcpExecutionConnections = class {
|
|
|
83816
85772
|
);
|
|
83817
85773
|
}
|
|
83818
85774
|
const matches = [...this.#sessions].filter(
|
|
83819
|
-
({ 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(
|
|
83820
85776
|
scope.additionalDirectories,
|
|
83821
|
-
decoded.data.additionalDirectories.map((path6) =>
|
|
85777
|
+
decoded.data.additionalDirectories.map((path6) => resolve15(path6))
|
|
83822
85778
|
)
|
|
83823
85779
|
);
|
|
83824
85780
|
if (matches.length > 1) {
|
|
@@ -84424,7 +86380,115 @@ var AgentQueryProcesses = class {
|
|
|
84424
86380
|
};
|
|
84425
86381
|
};
|
|
84426
86382
|
|
|
86383
|
+
// src/engine/acp/adapter/antigravity/conversation-handoff.ts
|
|
86384
|
+
import { join as join25 } from "node:path";
|
|
86385
|
+
var TRANSCRIPT_TAIL_BYTES2 = 1048576;
|
|
86386
|
+
var MAXIMUM_HANDOFF_CHARACTERS = 32e3;
|
|
86387
|
+
var MAXIMUM_MESSAGE_CHARACTERS = 4e3;
|
|
86388
|
+
var SESSION_UUID_PATTERN2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
|
|
86389
|
+
var USER_REQUEST_PATTERN = /<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/u;
|
|
86390
|
+
var HANDOFF_TAG = "previous_conversation";
|
|
86391
|
+
var transcriptStepSchema2 = external_exports.object({
|
|
86392
|
+
content: external_exports.string().optional(),
|
|
86393
|
+
step_index: external_exports.number().int().nonnegative(),
|
|
86394
|
+
type: external_exports.string()
|
|
86395
|
+
});
|
|
86396
|
+
function messageFromStep(step) {
|
|
86397
|
+
const content = step.content?.trim();
|
|
86398
|
+
if (content === void 0 || content.length === 0) {
|
|
86399
|
+
return void 0;
|
|
86400
|
+
}
|
|
86401
|
+
switch (step.type) {
|
|
86402
|
+
case "USER_INPUT": {
|
|
86403
|
+
const request = USER_REQUEST_PATTERN.exec(content)?.[1]?.trim();
|
|
86404
|
+
return request === void 0 || request.length === 0 ? void 0 : { role: "user", text: request };
|
|
86405
|
+
}
|
|
86406
|
+
case "PLANNER_RESPONSE":
|
|
86407
|
+
return { role: "assistant", text: content };
|
|
86408
|
+
default:
|
|
86409
|
+
return void 0;
|
|
86410
|
+
}
|
|
86411
|
+
}
|
|
86412
|
+
async function readConversationMessages(launchEnvironment, nativeSessionId) {
|
|
86413
|
+
const geminiHome = resolveGeminiHome(launchEnvironment);
|
|
86414
|
+
if (geminiHome === void 0 || !SESSION_UUID_PATTERN2.test(nativeSessionId)) {
|
|
86415
|
+
return null;
|
|
86416
|
+
}
|
|
86417
|
+
const tail = await readScopedFileTail(
|
|
86418
|
+
geminiHome,
|
|
86419
|
+
join25("antigravity-cli", "brain", nativeSessionId, ".system_generated", "logs", "transcript.jsonl"),
|
|
86420
|
+
TRANSCRIPT_TAIL_BYTES2
|
|
86421
|
+
);
|
|
86422
|
+
if (tail === null) {
|
|
86423
|
+
return null;
|
|
86424
|
+
}
|
|
86425
|
+
const lines = new TextDecoder().decode(tail.bytes).split("\n");
|
|
86426
|
+
const steps = [];
|
|
86427
|
+
for (const line of lines.slice(tail.offset > 0 ? 1 : 0)) {
|
|
86428
|
+
if (line.trim().length === 0) {
|
|
86429
|
+
continue;
|
|
86430
|
+
}
|
|
86431
|
+
let decoded;
|
|
86432
|
+
try {
|
|
86433
|
+
decoded = JSON.parse(line);
|
|
86434
|
+
} catch {
|
|
86435
|
+
continue;
|
|
86436
|
+
}
|
|
86437
|
+
const parsed = transcriptStepSchema2.safeParse(decoded);
|
|
86438
|
+
if (parsed.success) {
|
|
86439
|
+
steps.push(parsed.data);
|
|
86440
|
+
}
|
|
86441
|
+
}
|
|
86442
|
+
steps.sort((left, right) => left.step_index - right.step_index);
|
|
86443
|
+
const messages = steps.flatMap((step) => {
|
|
86444
|
+
const message = messageFromStep(step);
|
|
86445
|
+
return message === void 0 ? [] : [message];
|
|
86446
|
+
});
|
|
86447
|
+
return { messages, complete: tail.offset === 0 };
|
|
86448
|
+
}
|
|
86449
|
+
async function antigravityConversationHandoff(launchEnvironment, unusableNativeSessionId) {
|
|
86450
|
+
const conversation = await readConversationMessages(launchEnvironment, unusableNativeSessionId);
|
|
86451
|
+
const introduction = "This conversation continues an earlier one that could no longer be sent to the model. Treat the earlier messages below as what the user and you have already said; continue from them without repeating finished work unless the user asks.";
|
|
86452
|
+
if (conversation === null || conversation.messages.length === 0) {
|
|
86453
|
+
return `<${HANDOFF_TAG}>
|
|
86454
|
+
${introduction}
|
|
86455
|
+
The earlier messages could not be read.
|
|
86456
|
+
</${HANDOFF_TAG}>`;
|
|
86457
|
+
}
|
|
86458
|
+
const entries = [];
|
|
86459
|
+
let length = 0;
|
|
86460
|
+
let omitted = 0;
|
|
86461
|
+
for (let index2 = conversation.messages.length - 1; index2 >= 0; index2 -= 1) {
|
|
86462
|
+
const message = conversation.messages[index2];
|
|
86463
|
+
if (message === void 0) {
|
|
86464
|
+
continue;
|
|
86465
|
+
}
|
|
86466
|
+
const text2 = truncate(message.text, MAXIMUM_MESSAGE_CHARACTERS).replaceAll(
|
|
86467
|
+
`</${HANDOFF_TAG}>`,
|
|
86468
|
+
`</ ${HANDOFF_TAG}>`
|
|
86469
|
+
);
|
|
86470
|
+
const entry = `[${message.role}]
|
|
86471
|
+
${text2}`;
|
|
86472
|
+
if (length + entry.length > MAXIMUM_HANDOFF_CHARACTERS) {
|
|
86473
|
+
omitted = index2 + 1;
|
|
86474
|
+
break;
|
|
86475
|
+
}
|
|
86476
|
+
entries.unshift(entry);
|
|
86477
|
+
length += entry.length;
|
|
86478
|
+
}
|
|
86479
|
+
const earlierOmitted = omitted > 0 || !conversation.complete;
|
|
86480
|
+
return [
|
|
86481
|
+
`<${HANDOFF_TAG}>`,
|
|
86482
|
+
introduction,
|
|
86483
|
+
...earlierOmitted ? ["Earlier messages are omitted; the ones below are the most recent."] : [],
|
|
86484
|
+
"",
|
|
86485
|
+
entries.join("\n\n"),
|
|
86486
|
+
`</${HANDOFF_TAG}>`
|
|
86487
|
+
].join("\n");
|
|
86488
|
+
}
|
|
86489
|
+
|
|
84427
86490
|
// src/engine/acp/adapter/antigravity/adapter.ts
|
|
86491
|
+
var UNUSABLE_NATIVE_SESSION_MESSAGE = "Antigravity can no longer send this conversation's saved history to the model. Your next message continues in a new Antigravity conversation that carries this conversation's context.";
|
|
84428
86492
|
var AntigravityAdapter = class {
|
|
84429
86493
|
#queryProcesses;
|
|
84430
86494
|
#connector;
|
|
@@ -84449,6 +86513,30 @@ var AntigravityAdapter = class {
|
|
|
84449
86513
|
this.#executionConnections.bind(execution, nativeSessionId);
|
|
84450
86514
|
return normalizeOpenedSession(execution, nativeSessionId, response, signal);
|
|
84451
86515
|
});
|
|
86516
|
+
// `agy acp` adds `systemPrompt.append` to the new conversation's system prompt and keeps it with the conversation.
|
|
86517
|
+
continueInNewSession = (params) => this.#executionConnections.withConnection(params, async (execution, signal) => {
|
|
86518
|
+
const { connection } = execution;
|
|
86519
|
+
const handoff2 = await antigravityConversationHandoff(
|
|
86520
|
+
{ ...process.env, ...params.scope.agent.environment },
|
|
86521
|
+
params.unusableNativeSessionId
|
|
86522
|
+
);
|
|
86523
|
+
signal.throwIfAborted();
|
|
86524
|
+
const response = await connection.race(
|
|
86525
|
+
connection.connection.agent.request(
|
|
86526
|
+
methods.agent.session.new,
|
|
86527
|
+
{
|
|
86528
|
+
...sessionWorkspace(params.scope),
|
|
86529
|
+
_meta: { antigravity: { systemPrompt: { append: handoff2 } } }
|
|
86530
|
+
},
|
|
86531
|
+
{ cancellationSignal: signal }
|
|
86532
|
+
),
|
|
86533
|
+
"ACP agent exited while starting a session",
|
|
86534
|
+
signal
|
|
86535
|
+
);
|
|
86536
|
+
const nativeSessionId = createdNativeSessionId(response);
|
|
86537
|
+
this.#executionConnections.bind(execution, nativeSessionId);
|
|
86538
|
+
return normalizeOpenedSession(execution, nativeSessionId, response, signal);
|
|
86539
|
+
});
|
|
84452
86540
|
openSession = (params) => this.#executionConnections.withConnection(params, async (execution, signal) => {
|
|
84453
86541
|
const { connection } = execution;
|
|
84454
86542
|
const nativeSessionId = nativeSessionIdSchema.parse(params.nativeSessionId);
|
|
@@ -84494,7 +86582,14 @@ var AntigravityAdapter = class {
|
|
|
84494
86582
|
closeSession = (...args) => this.#executionConnections.closeSession(...args);
|
|
84495
86583
|
releaseSession = (params) => this.#executionConnections.releaseSession(params);
|
|
84496
86584
|
readNativeHistoryRevision = (params) => this.#executionConnections.readNativeHistoryRevision(params);
|
|
84497
|
-
prompt = (
|
|
86585
|
+
prompt = async (params) => {
|
|
86586
|
+
const result = await this.#executionConnections.prompt(params);
|
|
86587
|
+
const connection = this.#executionConnections.connection(params);
|
|
86588
|
+
if (connection !== void 0 && takeAntigravityUnusableNativeSession(connection.connection, params.nativeSessionId) && result.stopReason !== "cancelled") {
|
|
86589
|
+
throw new AcpExecutionError(UNUSABLE_NATIVE_SESSION_MESSAGE, {}, NATIVE_SESSION_UNUSABLE_ERROR_CODE);
|
|
86590
|
+
}
|
|
86591
|
+
return result;
|
|
86592
|
+
};
|
|
84498
86593
|
steer = (...args) => this.#executionConnections.steer(...args);
|
|
84499
86594
|
renameSession = (...args) => this.#executionConnections.renameSession(...args);
|
|
84500
86595
|
configureSession = (...args) => this.#executionConnections.configureSession(...args);
|
|
@@ -84503,6 +86598,12 @@ var AntigravityAdapter = class {
|
|
|
84503
86598
|
signal.throwIfAborted();
|
|
84504
86599
|
return { kind: "unsupported" };
|
|
84505
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
|
+
});
|
|
84506
86607
|
close = async () => await runCleanup(
|
|
84507
86608
|
() => this.#queryProcesses.close(),
|
|
84508
86609
|
() => this.#executionConnections.close()
|
|
@@ -84525,7 +86626,11 @@ var ClaudeAdapter = class {
|
|
|
84525
86626
|
#executionConnections;
|
|
84526
86627
|
constructor(agent2, dependencies) {
|
|
84527
86628
|
this.#connector = new AcpSessionConnector(dependencies.contentExternalizer);
|
|
84528
|
-
this.#executionConnections = new AcpExecutionConnections(
|
|
86629
|
+
this.#executionConnections = new AcpExecutionConnections(
|
|
86630
|
+
dependencies.contentExternalizer,
|
|
86631
|
+
void 0,
|
|
86632
|
+
dependencies.onUsageQuota
|
|
86633
|
+
);
|
|
84529
86634
|
this.#queryProcesses = new AgentQueryProcesses(agent2, dependencies.processes, this.#connector);
|
|
84530
86635
|
}
|
|
84531
86636
|
refreshAgent = (agent2) => this.#queryProcesses.refreshAgent(agent2);
|
|
@@ -84583,6 +86688,12 @@ var ClaudeAdapter = class {
|
|
|
84583
86688
|
renameSession = (...args) => this.#executionConnections.renameSession(...args);
|
|
84584
86689
|
configureSession = (...args) => this.#executionConnections.configureSession(...args);
|
|
84585
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
|
+
});
|
|
84586
86697
|
close = async () => await runCleanup(
|
|
84587
86698
|
() => this.#queryProcesses.close(),
|
|
84588
86699
|
() => this.#executionConnections.close()
|
|
@@ -84671,7 +86782,11 @@ var CodexAdapter = class {
|
|
|
84671
86782
|
}
|
|
84672
86783
|
};
|
|
84673
86784
|
this.#connector = new AcpSessionConnector(contentExternalizer, fitCodexToolEvent);
|
|
84674
|
-
this.#executionConnections = new AcpExecutionConnections(
|
|
86785
|
+
this.#executionConnections = new AcpExecutionConnections(
|
|
86786
|
+
contentExternalizer,
|
|
86787
|
+
fitCodexToolEvent,
|
|
86788
|
+
dependencies.onUsageQuota
|
|
86789
|
+
);
|
|
84675
86790
|
this.#queryProcesses = new AgentQueryProcesses(agent2, dependencies.processes, this.#connector);
|
|
84676
86791
|
}
|
|
84677
86792
|
refreshAgent = (agent2) => {
|
|
@@ -84765,6 +86880,12 @@ var CodexAdapter = class {
|
|
|
84765
86880
|
signal.throwIfAborted();
|
|
84766
86881
|
return { kind: "unsupported" };
|
|
84767
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
|
+
});
|
|
84768
86889
|
close = async () => {
|
|
84769
86890
|
await runCleanup(
|
|
84770
86891
|
() => this.#queryProcesses.close(),
|
|
@@ -84842,6 +86963,15 @@ var PiAdapter = class {
|
|
|
84842
86963
|
signal.throwIfAborted();
|
|
84843
86964
|
return { kind: "unsupported" };
|
|
84844
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
|
+
};
|
|
84845
86975
|
close = async () => await runCleanup(
|
|
84846
86976
|
() => this.#queryProcesses.close(),
|
|
84847
86977
|
() => this.#executionConnections.close()
|
|
@@ -85143,11 +87273,15 @@ var AcpContentExternalizer = class {
|
|
|
85143
87273
|
};
|
|
85144
87274
|
|
|
85145
87275
|
// src/engine/agent/runtime-agents.ts
|
|
85146
|
-
function createRuntimeAdapterRegistry(adapters, processes, externalize, linkedResources) {
|
|
87276
|
+
function createRuntimeAdapterRegistry(adapters, processes, externalize, linkedResources, onUsageQuota) {
|
|
85147
87277
|
const contentExternalizer = new AcpContentExternalizer(externalize, linkedResources);
|
|
85148
87278
|
const externalizeSessionUpdate = (sessionId, update, signal) => contentExternalizer.update(sessionId, update, signal);
|
|
85149
87279
|
return {
|
|
85150
|
-
adapters: new AdapterRegistry(adapters, {
|
|
87280
|
+
adapters: new AdapterRegistry(adapters, {
|
|
87281
|
+
processes,
|
|
87282
|
+
contentExternalizer,
|
|
87283
|
+
...onUsageQuota === void 0 ? {} : { onUsageQuota }
|
|
87284
|
+
}),
|
|
85151
87285
|
externalizeSessionUpdate
|
|
85152
87286
|
};
|
|
85153
87287
|
}
|
|
@@ -85160,62 +87294,12 @@ var RuntimeAgentDependencies = class {
|
|
|
85160
87294
|
}
|
|
85161
87295
|
};
|
|
85162
87296
|
|
|
85163
|
-
// src/engine/util/network/environment-proxy.ts
|
|
85164
|
-
import { EnvHttpProxyAgent } from "undici";
|
|
85165
|
-
var configuredHttpProxy = process.env["http_proxy"] ?? process.env["HTTP_PROXY"] ?? "";
|
|
85166
|
-
var configuredHttpsProxy = process.env["https_proxy"] ?? process.env["HTTPS_PROXY"] ?? configuredHttpProxy;
|
|
85167
|
-
var environmentProxyDispatcher = new EnvHttpProxyAgent();
|
|
85168
|
-
function bypassesProxy(target) {
|
|
85169
|
-
const noProxy = process.env["no_proxy"] ?? process.env["NO_PROXY"] ?? "";
|
|
85170
|
-
if (noProxy === "*") {
|
|
85171
|
-
return true;
|
|
85172
|
-
}
|
|
85173
|
-
const hostname4 = target.hostname.replace(/^\[|\]$/gu, "").toLowerCase();
|
|
85174
|
-
const defaultPort = target.protocol === "wss:" || target.protocol === "https:" ? 443 : 80;
|
|
85175
|
-
const port = Number.parseInt(target.port, 10) || defaultPort;
|
|
85176
|
-
for (const rawEntry of noProxy.split(/[,\s]/u)) {
|
|
85177
|
-
if (rawEntry.length === 0) {
|
|
85178
|
-
continue;
|
|
85179
|
-
}
|
|
85180
|
-
const parsed = rawEntry.match(/^(.+):(\d+)$/u);
|
|
85181
|
-
const entryHostname = (parsed?.[1] ?? rawEntry).replace(/^\*?\./u, "").toLowerCase();
|
|
85182
|
-
const entryPort = parsed?.[2] === void 0 ? 0 : Number.parseInt(parsed[2], 10);
|
|
85183
|
-
if (entryPort !== 0 && entryPort !== port) {
|
|
85184
|
-
continue;
|
|
85185
|
-
}
|
|
85186
|
-
if (hostname4 === entryHostname || hostname4.endsWith(`.${entryHostname}`)) {
|
|
85187
|
-
return true;
|
|
85188
|
-
}
|
|
85189
|
-
}
|
|
85190
|
-
return false;
|
|
85191
|
-
}
|
|
85192
|
-
function sanitizedProxyOrigin(proxyUrl) {
|
|
85193
|
-
try {
|
|
85194
|
-
return new URL(proxyUrl).origin;
|
|
85195
|
-
} catch {
|
|
85196
|
-
return "configured-invalid-url";
|
|
85197
|
-
}
|
|
85198
|
-
}
|
|
85199
|
-
function describeEnvironmentProxyRoute(target) {
|
|
85200
|
-
if (bypassesProxy(target)) {
|
|
85201
|
-
return { proxyRoute: "direct" };
|
|
85202
|
-
}
|
|
85203
|
-
const proxyUrl = target.protocol === "wss:" || target.protocol === "https:" ? configuredHttpsProxy : configuredHttpProxy;
|
|
85204
|
-
if (proxyUrl.length === 0) {
|
|
85205
|
-
return { proxyRoute: "direct" };
|
|
85206
|
-
}
|
|
85207
|
-
return {
|
|
85208
|
-
proxyOrigin: sanitizedProxyOrigin(proxyUrl),
|
|
85209
|
-
proxyRoute: "proxy"
|
|
85210
|
-
};
|
|
85211
|
-
}
|
|
85212
|
-
|
|
85213
87297
|
// src/engine/runtime/observability/diagnostic-log.ts
|
|
85214
|
-
import { join as
|
|
87298
|
+
import { join as join28 } from "node:path";
|
|
85215
87299
|
|
|
85216
87300
|
// src/engine/storage/logs/bounded-log.ts
|
|
85217
87301
|
import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync10, renameSync as renameSync2, statSync as statSync5, writeFileSync as writeFileSync2 } from "node:fs";
|
|
85218
|
-
import { join as
|
|
87302
|
+
import { join as join26 } from "node:path";
|
|
85219
87303
|
var BoundedLineLog = class {
|
|
85220
87304
|
#path;
|
|
85221
87305
|
#maximumBytes;
|
|
@@ -85224,7 +87308,7 @@ var BoundedLineLog = class {
|
|
|
85224
87308
|
#onWriteFailure;
|
|
85225
87309
|
constructor(directory, filename, maximumBytes, onWriteFailure = () => void 0) {
|
|
85226
87310
|
this.#directory = directory;
|
|
85227
|
-
this.#path =
|
|
87311
|
+
this.#path = join26(directory, filename);
|
|
85228
87312
|
this.#maximumBytes = maximumBytes;
|
|
85229
87313
|
this.#onWriteFailure = onWriteFailure;
|
|
85230
87314
|
}
|
|
@@ -85275,21 +87359,21 @@ var BoundedLineLog = class {
|
|
|
85275
87359
|
|
|
85276
87360
|
// src/engine/storage/logs/log-files.ts
|
|
85277
87361
|
import { readFileSync as readFileSync11 } from "node:fs";
|
|
85278
|
-
import { join as
|
|
87362
|
+
import { join as join27 } from "node:path";
|
|
85279
87363
|
var DAEMON_LOG_FILENAME = "daemon.log";
|
|
85280
87364
|
var WORKER_LIFECYCLE_LOG_FILENAME = "worker-lifecycle.log";
|
|
85281
87365
|
function unhandledRejectionLogFilename(role) {
|
|
85282
87366
|
return `unhandled-rejections-${role}.log`;
|
|
85283
87367
|
}
|
|
85284
87368
|
function logDirectory(dataDirectory) {
|
|
85285
|
-
return
|
|
87369
|
+
return join27(dataDirectory, "logs");
|
|
85286
87370
|
}
|
|
85287
87371
|
function processLogPaths(dataDirectory) {
|
|
85288
87372
|
return [
|
|
85289
87373
|
WORKER_LIFECYCLE_LOG_FILENAME,
|
|
85290
87374
|
unhandledRejectionLogFilename("manager"),
|
|
85291
87375
|
unhandledRejectionLogFilename("worker")
|
|
85292
|
-
].map((filename) =>
|
|
87376
|
+
].map((filename) => join27(logDirectory(dataDirectory), filename));
|
|
85293
87377
|
}
|
|
85294
87378
|
function readLogText(path6) {
|
|
85295
87379
|
try {
|
|
@@ -85364,7 +87448,7 @@ var RuntimeDiagnosticLog = class {
|
|
|
85364
87448
|
this.#maximumBytes = maximumBytes;
|
|
85365
87449
|
const processLogsDirectory = options.processLogsDirectory;
|
|
85366
87450
|
this.#sources = [
|
|
85367
|
-
{ maximumBytes, path:
|
|
87451
|
+
{ maximumBytes, path: join28(directory, DAEMON_LOG_FILENAME) },
|
|
85368
87452
|
// The process logs a Runtime does not own, but must read to explain its own deaths.
|
|
85369
87453
|
...processLogsDirectory === void 0 ? [] : processLogPaths(processLogsDirectory).map((path6) => ({ maximumBytes: null, path: path6 }))
|
|
85370
87454
|
];
|
|
@@ -85485,7 +87569,7 @@ async function discoverRuntimeAgentInventory(options, channelId) {
|
|
|
85485
87569
|
}
|
|
85486
87570
|
|
|
85487
87571
|
// src/engine/runtime/catalog/publish-agent-catalog.ts
|
|
85488
|
-
import { fetch as
|
|
87572
|
+
import { fetch as fetch3 } from "undici";
|
|
85489
87573
|
|
|
85490
87574
|
// src/engine/runtime/relay/relay-authentication.ts
|
|
85491
87575
|
function runtimeCredential(relayUrl) {
|
|
@@ -85562,7 +87646,7 @@ async function publishAgentCatalog(config2, signal) {
|
|
|
85562
87646
|
let response;
|
|
85563
87647
|
const catalog = config2.catalog.read();
|
|
85564
87648
|
try {
|
|
85565
|
-
response = await
|
|
87649
|
+
response = await fetch3(catalogEndpoint(config2), {
|
|
85566
87650
|
body: JSON.stringify({
|
|
85567
87651
|
agents: catalog.agents.map((agent2) => ({
|
|
85568
87652
|
agentPath: agent2.agentIdentity.requestedPath,
|
|
@@ -85593,7 +87677,7 @@ async function publishAgentCatalog(config2, signal) {
|
|
|
85593
87677
|
}
|
|
85594
87678
|
|
|
85595
87679
|
// src/engine/runtime/config.ts
|
|
85596
|
-
import { resolve as
|
|
87680
|
+
import { resolve as resolve16 } from "node:path";
|
|
85597
87681
|
|
|
85598
87682
|
// src/engine/agent/catalog.ts
|
|
85599
87683
|
var LocalAgentCatalogSnapshot = class {
|
|
@@ -85656,7 +87740,7 @@ var RuntimeLocalContext = class {
|
|
|
85656
87740
|
stateDirectory;
|
|
85657
87741
|
maxAcpProcesses;
|
|
85658
87742
|
constructor(stateDirectory, agentLaunchEnvironment, maxAcpProcesses = 1e3) {
|
|
85659
|
-
this.stateDirectory =
|
|
87743
|
+
this.stateDirectory = resolve16(stateDirectory);
|
|
85660
87744
|
this.agentLaunchEnvironment = Object.freeze({ ...agentLaunchEnvironment });
|
|
85661
87745
|
this.maxAcpProcesses = maxAcpProcesses;
|
|
85662
87746
|
}
|
|
@@ -85811,7 +87895,7 @@ function validatePairingId(value) {
|
|
|
85811
87895
|
return value;
|
|
85812
87896
|
}
|
|
85813
87897
|
async function resolveDefaultWorkspace(path6) {
|
|
85814
|
-
const requestedWorkspace =
|
|
87898
|
+
const requestedWorkspace = resolve17(path6);
|
|
85815
87899
|
let defaultWorkspace;
|
|
85816
87900
|
try {
|
|
85817
87901
|
defaultWorkspace = await ensureCanonicalDirectory(requestedWorkspace);
|
|
@@ -85876,7 +87960,7 @@ async function claimPairing(options, defaultWorkspace, localAgents, signal) {
|
|
|
85876
87960
|
const endpoint = options.pairingId.length > 0 ? mobiusApiUrl(options.relayOrigin, `/v1/runtime-pairings/${encodeURIComponent(options.pairingId)}/redeem`) : mobiusApiUrl(options.relayOrigin, "/pairings/claim");
|
|
85877
87961
|
let response;
|
|
85878
87962
|
try {
|
|
85879
|
-
response = await
|
|
87963
|
+
response = await fetch4(endpoint, {
|
|
85880
87964
|
body: JSON.stringify({
|
|
85881
87965
|
agents,
|
|
85882
87966
|
machineName: hostname3(),
|
|
@@ -85989,7 +88073,7 @@ async function prepareRuntimeConnection(installation, connection, signal, enviro
|
|
|
85989
88073
|
}
|
|
85990
88074
|
|
|
85991
88075
|
// src/engine/runtime/runtime-loop.ts
|
|
85992
|
-
import { resolve as
|
|
88076
|
+
import { resolve as resolve19 } from "node:path";
|
|
85993
88077
|
|
|
85994
88078
|
// src/engine/runtime/run.ts
|
|
85995
88079
|
import { styleText } from "node:util";
|
|
@@ -86499,7 +88583,7 @@ function sql(strings, ...params) {
|
|
|
86499
88583
|
return new SQL([new StringChunk(str)]);
|
|
86500
88584
|
}
|
|
86501
88585
|
_sql.raw = raw;
|
|
86502
|
-
function
|
|
88586
|
+
function join35(chunks, separator) {
|
|
86503
88587
|
const result = [];
|
|
86504
88588
|
for (const [i, chunk] of chunks.entries()) {
|
|
86505
88589
|
if (i > 0 && separator !== void 0) result.push(separator);
|
|
@@ -86507,7 +88591,7 @@ function sql(strings, ...params) {
|
|
|
86507
88591
|
}
|
|
86508
88592
|
return new SQL(result);
|
|
86509
88593
|
}
|
|
86510
|
-
_sql.join =
|
|
88594
|
+
_sql.join = join35;
|
|
86511
88595
|
function identifier2(value) {
|
|
86512
88596
|
return new Name(value);
|
|
86513
88597
|
}
|
|
@@ -88652,7 +90736,7 @@ var SQLiteSelectBase = class extends TypedQueryBuilder {
|
|
|
88652
90736
|
const baseTableName = this.tableName;
|
|
88653
90737
|
const tableName = getTableLikeName(table);
|
|
88654
90738
|
for (const item of extractUsedTable(table)) this.usedTables.add(item);
|
|
88655
|
-
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`);
|
|
88656
90740
|
if (!this.isPartialSelect) {
|
|
88657
90741
|
if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") this.config.fields = { [baseTableName]: this.config.fields };
|
|
88658
90742
|
if (typeof tableName === "string" && !is(table, SQL)) {
|
|
@@ -89491,7 +91575,7 @@ var SQLiteDialect = class {
|
|
|
89491
91575
|
if (!joins2) return;
|
|
89492
91576
|
const withEntries = Object.entries(joins2).filter(([_, v]) => v);
|
|
89493
91577
|
if (!withEntries.length) return;
|
|
89494
|
-
return sql.join(withEntries.map(([k2,
|
|
91578
|
+
return sql.join(withEntries.map(([k2, join35]) => {
|
|
89495
91579
|
const relation = tableConfig.relations[k2];
|
|
89496
91580
|
const isSingle2 = is(relation, One2);
|
|
89497
91581
|
const targetTable = aliasedTable(relation.targetTable, `d${currentDepth + 1}`);
|
|
@@ -89502,7 +91586,7 @@ var SQLiteDialect = class {
|
|
|
89502
91586
|
table: targetTable,
|
|
89503
91587
|
mode: isSingle2 ? "first" : "many",
|
|
89504
91588
|
schema,
|
|
89505
|
-
queryConfig:
|
|
91589
|
+
queryConfig: join35,
|
|
89506
91590
|
tableConfig: schema[relation.targetTableName],
|
|
89507
91591
|
relationWhere: filter,
|
|
89508
91592
|
isNested: true,
|
|
@@ -89516,7 +91600,7 @@ var SQLiteDialect = class {
|
|
|
89516
91600
|
key: k2,
|
|
89517
91601
|
selection: innerQuery.selection,
|
|
89518
91602
|
isArray: !isSingle2,
|
|
89519
|
-
isOptional: (relation.optional ?? false) ||
|
|
91603
|
+
isOptional: (relation.optional ?? false) || join35 !== true && !!join35.where
|
|
89520
91604
|
});
|
|
89521
91605
|
const jsonColumns = sql.join(innerQuery.selection.map((s) => {
|
|
89522
91606
|
return sql`${sql.raw(this.escapeString(s.key))}, ${s.selection ? sql`${jsonb}(${sql.identifier(s.key)})` : sql.identifier(s.key)}`;
|
|
@@ -90132,7 +92216,7 @@ var SQLiteUpdateBase = class {
|
|
|
90132
92216
|
createJoin(joinType) {
|
|
90133
92217
|
return ((table, on2) => {
|
|
90134
92218
|
const tableName = getTableLikeName(table);
|
|
90135
|
-
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`);
|
|
90136
92220
|
if (typeof on2 === "function") {
|
|
90137
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;
|
|
90138
92222
|
on2 = on2(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
|
|
@@ -91086,7 +93170,7 @@ var SessionEventCacheTable = class {
|
|
|
91086
93170
|
// src/engine/storage/sqlite/local-databases.ts
|
|
91087
93171
|
import { createHash as createHash4 } from "node:crypto";
|
|
91088
93172
|
import { existsSync as existsSync9 } from "node:fs";
|
|
91089
|
-
import { join as
|
|
93173
|
+
import { join as join29 } from "node:path";
|
|
91090
93174
|
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
91091
93175
|
|
|
91092
93176
|
// src/engine/generated/acp-session-store-migrations.ts
|
|
@@ -91339,9 +93423,9 @@ var LocalSqliteDatabase = class {
|
|
|
91339
93423
|
function channelSessionDatabasePaths(stateDirectory, channelId) {
|
|
91340
93424
|
const channelHash = createHash4("sha256").update(channelId).digest("hex");
|
|
91341
93425
|
return {
|
|
91342
|
-
cancellations:
|
|
91343
|
-
events:
|
|
91344
|
-
sessions:
|
|
93426
|
+
cancellations: join29(stateDirectory, "sessions", `${channelHash}.cancellations.sqlite`),
|
|
93427
|
+
events: join29(stateDirectory, "sessions", `${channelHash}.events.sqlite`),
|
|
93428
|
+
sessions: join29(stateDirectory, "sessions", `${channelHash}.sqlite`)
|
|
91345
93429
|
};
|
|
91346
93430
|
}
|
|
91347
93431
|
function recordAppliedAdmissionOrder(path6) {
|
|
@@ -91498,14 +93582,14 @@ function mergeTextChunk(previous, incoming) {
|
|
|
91498
93582
|
var SessionEventHistoryProjection = class {
|
|
91499
93583
|
#toolCallEventIds = /* @__PURE__ */ new Map();
|
|
91500
93584
|
#latestEvent = null;
|
|
91501
|
-
apply = (liveEvent2,
|
|
93585
|
+
apply = (liveEvent2, resolve21) => {
|
|
91502
93586
|
if (liveEvent2.type === "lifecycle-metadata") {
|
|
91503
93587
|
this.#latestEvent = null;
|
|
91504
93588
|
return { kind: "skip" };
|
|
91505
93589
|
}
|
|
91506
93590
|
if (liveEvent2.type === "acp" && liveEvent2.payload.sessionUpdate === "tool_call_update") {
|
|
91507
93591
|
const targetEventId = this.#toolCallEventIds.get(liveEvent2.payload.toolCallId);
|
|
91508
|
-
const current = targetEventId === void 0 ? void 0 :
|
|
93592
|
+
const current = targetEventId === void 0 ? void 0 : resolve21([targetEventId]).get(targetEventId);
|
|
91509
93593
|
if (current?.type === "acp" && (current.payload.sessionUpdate === "tool_call" || current.payload.sessionUpdate === "tool_call_update")) {
|
|
91510
93594
|
return this.#replace(
|
|
91511
93595
|
current,
|
|
@@ -91529,12 +93613,12 @@ var SessionEventHistoryProjection = class {
|
|
|
91529
93613
|
* The projected tool call announced with this identifier, in its current
|
|
91530
93614
|
* merged form, or `undefined` when the projection has not recorded one.
|
|
91531
93615
|
*/
|
|
91532
|
-
getToolCall = (toolCallId,
|
|
93616
|
+
getToolCall = (toolCallId, resolve21) => {
|
|
91533
93617
|
const eventId = this.#toolCallEventIds.get(toolCallId);
|
|
91534
93618
|
if (eventId === void 0) {
|
|
91535
93619
|
return void 0;
|
|
91536
93620
|
}
|
|
91537
|
-
const event =
|
|
93621
|
+
const event = resolve21([eventId]).get(eventId);
|
|
91538
93622
|
if (event?.type === "acp" && (event.payload.sessionUpdate === "tool_call" || event.payload.sessionUpdate === "tool_call_update")) {
|
|
91539
93623
|
return event.payload;
|
|
91540
93624
|
}
|
|
@@ -91594,8 +93678,8 @@ var SessionEvents = class {
|
|
|
91594
93678
|
this.sessionGenerationId = sessionGenerationId;
|
|
91595
93679
|
this.#projection = new SessionEventHistoryProjection();
|
|
91596
93680
|
}
|
|
91597
|
-
apply = (event,
|
|
91598
|
-
const projected = this.#projection.apply(event,
|
|
93681
|
+
apply = (event, resolve21) => {
|
|
93682
|
+
const projected = this.#projection.apply(event, resolve21);
|
|
91599
93683
|
this.#throughPosition = event.position;
|
|
91600
93684
|
if (projected.kind === "skip") {
|
|
91601
93685
|
return;
|
|
@@ -91622,7 +93706,7 @@ var SessionEvents = class {
|
|
|
91622
93706
|
return this.#cachedItemsByEventId.size;
|
|
91623
93707
|
}
|
|
91624
93708
|
/** The projected tool call for this identifier, materializing it if needed. */
|
|
91625
|
-
toolCall = (toolCallId,
|
|
93709
|
+
toolCall = (toolCallId, resolve21) => this.#projection.getToolCall(toolCallId, resolve21);
|
|
91626
93710
|
item = (eventId) => this.#cachedItemsByEventId.get(eventId)?.event;
|
|
91627
93711
|
/**
|
|
91628
93712
|
* Materializes an event that was previously dropped to the cache database.
|
|
@@ -93096,6 +95180,30 @@ async function restoreSession(session, signal, recovery) {
|
|
|
93096
95180
|
conversation !== void 0 && session.restored ? conversation.updatedAt : (/* @__PURE__ */ new Date()).toISOString()
|
|
93097
95181
|
);
|
|
93098
95182
|
}
|
|
95183
|
+
async function continueInNewNativeSession(session, signal, unusableNativeSessionId) {
|
|
95184
|
+
const stored = session.metrics.measureSync("session-state-read", () => session.store.read(session.sessionId));
|
|
95185
|
+
const conversation = stored instanceof FoundStoredSession ? stored.session : void 0;
|
|
95186
|
+
if (conversation === void 0 || conversation.nativeSessionId !== unusableNativeSessionId || conversation.agentId !== session.agentId || conversation.cwd !== session.cwd || !arraysEqual(conversation.additionalDirectories, session.additionalDirectories)) {
|
|
95187
|
+
throw new AcpExecutionError(
|
|
95188
|
+
"The Session no longer continues the native conversation that failed",
|
|
95189
|
+
{},
|
|
95190
|
+
"session_identity_mismatch"
|
|
95191
|
+
);
|
|
95192
|
+
}
|
|
95193
|
+
const opened = await session.metrics.measure(
|
|
95194
|
+
"session-new",
|
|
95195
|
+
async () => await session.continueSession(unusableNativeSessionId, signal)
|
|
95196
|
+
);
|
|
95197
|
+
session.selectNativeSession(opened.nativeSessionId);
|
|
95198
|
+
session.setPrompted(true);
|
|
95199
|
+
session.setSessionTitle(conversation.title);
|
|
95200
|
+
session.setRestored(true);
|
|
95201
|
+
session.startExecutionOnlyCapture();
|
|
95202
|
+
session.applySessionOpened(opened);
|
|
95203
|
+
await session.restoreStoredConfigurations(conversation, signal);
|
|
95204
|
+
signal.throwIfAborted();
|
|
95205
|
+
session.writeStoredSession((/* @__PURE__ */ new Date()).toISOString());
|
|
95206
|
+
}
|
|
93099
95207
|
|
|
93100
95208
|
// src/engine/session/live/agent-session.ts
|
|
93101
95209
|
var SESSION_CONTROL_COMMAND_ID = "session-control";
|
|
@@ -93316,6 +95424,23 @@ var AgentSession = class _AgentSession {
|
|
|
93316
95424
|
promptSuggestions,
|
|
93317
95425
|
timer
|
|
93318
95426
|
);
|
|
95427
|
+
/**
|
|
95428
|
+
* Starts a process that continues the Session in a new native conversation, in place of the stored one whose
|
|
95429
|
+
* prompts failed with `native_session_unusable`.
|
|
95430
|
+
*/
|
|
95431
|
+
static continueUnusable = async (options, unusableNativeSessionId, getObserver, agentCommand, store, adapter, promptSuggestions, timer) => await _AgentSession.#start(
|
|
95432
|
+
options,
|
|
95433
|
+
getObserver,
|
|
95434
|
+
agentCommand,
|
|
95435
|
+
store,
|
|
95436
|
+
async (runtime) => await runtime.#writeNativeHistory(
|
|
95437
|
+
async () => await continueInNewNativeSession(runtime, options.signal, unusableNativeSessionId)
|
|
95438
|
+
),
|
|
95439
|
+
unmeasuredOperationMetrics,
|
|
95440
|
+
adapter,
|
|
95441
|
+
promptSuggestions,
|
|
95442
|
+
timer
|
|
95443
|
+
);
|
|
93319
95444
|
belongsTo = (agentId, cwd, additionalDirectories) => this.#agentId === agentId && this.#cwd === cwd && arraysEqual(this.#additionalDirectories, additionalDirectories);
|
|
93320
95445
|
usesEnvironment = (environment) => recordsEqual(this.#environment, environment);
|
|
93321
95446
|
writeStoredSession = (updatedAt) => {
|
|
@@ -94164,6 +96289,17 @@ var AgentSession = class _AgentSession {
|
|
|
94164
96289
|
generateTitle: this.#generateTitle
|
|
94165
96290
|
});
|
|
94166
96291
|
createSession = (signal) => this.#adapter.createSession(this.#sessionParams(signal));
|
|
96292
|
+
continueSession = async (unusableNativeSessionId, signal) => {
|
|
96293
|
+
const continueInNewSession = this.#adapter.continueInNewSession;
|
|
96294
|
+
if (continueInNewSession === void 0) {
|
|
96295
|
+
throw new AcpExecutionError(
|
|
96296
|
+
"This Agent cannot continue a conversation in a new native conversation",
|
|
96297
|
+
{},
|
|
96298
|
+
"session_restore_unsupported"
|
|
96299
|
+
);
|
|
96300
|
+
}
|
|
96301
|
+
return await continueInNewSession({ ...this.#sessionParams(signal), unusableNativeSessionId });
|
|
96302
|
+
};
|
|
94167
96303
|
openSession = (signal) => this.#adapter.openSession({ ...this.#sessionParams(signal), nativeSessionId: this.nativeSessionId() });
|
|
94168
96304
|
openSessionWithReplay = async (signal) => (await this.#loadSession(signal)).opened;
|
|
94169
96305
|
setConfigOptions(options) {
|
|
@@ -94946,6 +97082,7 @@ var SessionManager2 = class {
|
|
|
94946
97082
|
}
|
|
94947
97083
|
} catch (error62) {
|
|
94948
97084
|
const failedRuntime = this.#executionProcesses.get(options2.sessionId);
|
|
97085
|
+
const unusableNativeSessionId = error62 instanceof AcpExecutionError && error62.code === NATIVE_SESSION_UNUSABLE_ERROR_CODE ? failedRuntime?.nativeSessionId() : void 0;
|
|
94949
97086
|
if (failedRuntime !== void 0) {
|
|
94950
97087
|
await this.#retireSessionProcess(
|
|
94951
97088
|
options2.sessionId,
|
|
@@ -94956,6 +97093,9 @@ var SessionManager2 = class {
|
|
|
94956
97093
|
if (cancelled()) {
|
|
94957
97094
|
return { stopReason: "cancelled" };
|
|
94958
97095
|
}
|
|
97096
|
+
if (unusableNativeSessionId !== void 0 && unusableNativeSessionId.length > 0) {
|
|
97097
|
+
await this.#continueInNewNativeSession(options2, unusableNativeSessionId);
|
|
97098
|
+
}
|
|
94959
97099
|
if (error62 instanceof AcpExecutionError) {
|
|
94960
97100
|
throw error62;
|
|
94961
97101
|
}
|
|
@@ -94972,6 +97112,42 @@ var SessionManager2 = class {
|
|
|
94972
97112
|
}
|
|
94973
97113
|
}
|
|
94974
97114
|
});
|
|
97115
|
+
/**
|
|
97116
|
+
* Moves a Session off a native conversation the Agent can no longer continue before its failed prompt settles,
|
|
97117
|
+
* so the member's next prompt reaches a conversation that works. When this fails, the next prompt fails the same
|
|
97118
|
+
* way and tries again.
|
|
97119
|
+
*/
|
|
97120
|
+
async #continueInNewNativeSession(options, unusableNativeSessionId) {
|
|
97121
|
+
if (options.adapter.continueInNewSession === void 0) {
|
|
97122
|
+
return;
|
|
97123
|
+
}
|
|
97124
|
+
try {
|
|
97125
|
+
await this.#executionProcesses.prepare(
|
|
97126
|
+
options.sessionId,
|
|
97127
|
+
async () => this.#startRetainedSessionProcess(
|
|
97128
|
+
options,
|
|
97129
|
+
async () => await AgentSession.continueUnusable(
|
|
97130
|
+
options,
|
|
97131
|
+
unusableNativeSessionId,
|
|
97132
|
+
() => this.#runtimeObserver,
|
|
97133
|
+
this.#executions.agentCommand,
|
|
97134
|
+
this.#store,
|
|
97135
|
+
options.adapter,
|
|
97136
|
+
this.promptSuggestions,
|
|
97137
|
+
this.#timer
|
|
97138
|
+
)
|
|
97139
|
+
)
|
|
97140
|
+
);
|
|
97141
|
+
} catch (error62) {
|
|
97142
|
+
if (options.signal.aborted) {
|
|
97143
|
+
return;
|
|
97144
|
+
}
|
|
97145
|
+
console.warn(
|
|
97146
|
+
`[${options.agent.id}-acp] The Session could not continue in a new native conversation`,
|
|
97147
|
+
error62
|
|
97148
|
+
);
|
|
97149
|
+
}
|
|
97150
|
+
}
|
|
94975
97151
|
respondPermission = async (options) => {
|
|
94976
97152
|
this.#assertOpen(options.sessionId);
|
|
94977
97153
|
const runtime = this.#executionProcesses.get(options.sessionId);
|
|
@@ -95948,8 +98124,8 @@ var RuntimeTurnActivity = class {
|
|
|
95948
98124
|
#changed() {
|
|
95949
98125
|
this.#changedAt = Date.now();
|
|
95950
98126
|
if (this.count() === 0) {
|
|
95951
|
-
for (const
|
|
95952
|
-
|
|
98127
|
+
for (const resolve21 of this.#idleWaiters) {
|
|
98128
|
+
resolve21();
|
|
95953
98129
|
}
|
|
95954
98130
|
this.#idleWaiters.clear();
|
|
95955
98131
|
}
|
|
@@ -95959,14 +98135,14 @@ var RuntimeTurnActivity = class {
|
|
|
95959
98135
|
if (this.count() === 0) {
|
|
95960
98136
|
return Promise.resolve();
|
|
95961
98137
|
}
|
|
95962
|
-
return new Promise((
|
|
98138
|
+
return new Promise((resolve21, reject2) => {
|
|
95963
98139
|
const abort = () => {
|
|
95964
98140
|
this.#idleWaiters.delete(idle);
|
|
95965
98141
|
reject2(signal.reason);
|
|
95966
98142
|
};
|
|
95967
98143
|
const idle = () => {
|
|
95968
98144
|
signal.removeEventListener("abort", abort);
|
|
95969
|
-
|
|
98145
|
+
resolve21();
|
|
95970
98146
|
};
|
|
95971
98147
|
this.#idleWaiters.add(idle);
|
|
95972
98148
|
signal.addEventListener("abort", abort, { once: true });
|
|
@@ -96130,7 +98306,7 @@ var ActiveRuntimeTurn = class {
|
|
|
96130
98306
|
// src/engine/session/turn/session-execution.ts
|
|
96131
98307
|
var waitForTurnCompletion = (turn, waitSignal) => {
|
|
96132
98308
|
waitSignal.throwIfAborted();
|
|
96133
|
-
return new Promise((
|
|
98309
|
+
return new Promise((resolve21, reject2) => {
|
|
96134
98310
|
let settled = false;
|
|
96135
98311
|
const finish = (result) => {
|
|
96136
98312
|
if (settled) {
|
|
@@ -96139,7 +98315,7 @@ var waitForTurnCompletion = (turn, waitSignal) => {
|
|
|
96139
98315
|
settled = true;
|
|
96140
98316
|
waitSignal.removeEventListener("abort", onAbort);
|
|
96141
98317
|
if (result.kind === "completed") {
|
|
96142
|
-
|
|
98318
|
+
resolve21();
|
|
96143
98319
|
} else {
|
|
96144
98320
|
reject2(result.error);
|
|
96145
98321
|
}
|
|
@@ -96353,8 +98529,8 @@ var SessionTurns = class {
|
|
|
96353
98529
|
};
|
|
96354
98530
|
|
|
96355
98531
|
// src/engine/session/workspace/workspace-directory.ts
|
|
96356
|
-
import { homedir as
|
|
96357
|
-
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";
|
|
96358
98534
|
|
|
96359
98535
|
// src/engine/session/workspace/local-authorization-error.ts
|
|
96360
98536
|
var LocalAuthorizationError = class extends OperationError {
|
|
@@ -96385,7 +98561,7 @@ function encodePath(path6) {
|
|
|
96385
98561
|
return `path-${encoded}`;
|
|
96386
98562
|
}
|
|
96387
98563
|
function expandCurrentUserHome(path6) {
|
|
96388
|
-
return path6.replace(/^~(?=$|\/|\\)/,
|
|
98564
|
+
return path6.replace(/^~(?=$|\/|\\)/, homedir5());
|
|
96389
98565
|
}
|
|
96390
98566
|
function decodePath(value, prefix) {
|
|
96391
98567
|
const encoded = value.slice(prefix.length);
|
|
@@ -96416,7 +98592,7 @@ var WorkspaceDirectoryService = class {
|
|
|
96416
98592
|
return this.#defaultWorkspace;
|
|
96417
98593
|
}
|
|
96418
98594
|
if (id === "home") {
|
|
96419
|
-
return
|
|
98595
|
+
return homedir5();
|
|
96420
98596
|
}
|
|
96421
98597
|
if (id.startsWith("path-")) {
|
|
96422
98598
|
const path6 = expandCurrentUserHome(decodePath(id, "path-"));
|
|
@@ -96451,7 +98627,7 @@ var WorkspaceDirectoryService = class {
|
|
|
96451
98627
|
}
|
|
96452
98628
|
};
|
|
96453
98629
|
label = (path6) => {
|
|
96454
|
-
const suffix = relative3(
|
|
98630
|
+
const suffix = relative3(homedir5(), path6);
|
|
96455
98631
|
return suffix === "" ? "~" : !isAbsolute16(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path6;
|
|
96456
98632
|
};
|
|
96457
98633
|
identify = async (bindingId, requestedPath2, signal) => {
|
|
@@ -96500,7 +98676,7 @@ var WorkspaceDirectoryService = class {
|
|
|
96500
98676
|
continue;
|
|
96501
98677
|
}
|
|
96502
98678
|
try {
|
|
96503
|
-
const path6 = await this.resolvePath(
|
|
98679
|
+
const path6 = await this.resolvePath(join30(target, child.name), signal);
|
|
96504
98680
|
entries.push({ directoryId: encodePath(path6), name: child.name });
|
|
96505
98681
|
} catch (cause) {
|
|
96506
98682
|
signal.throwIfAborted();
|
|
@@ -96685,13 +98861,13 @@ function buildSessionLayer(options) {
|
|
|
96685
98861
|
|
|
96686
98862
|
// src/engine/session/content/external-content-store.ts
|
|
96687
98863
|
import { createHash as createHash8 } from "node:crypto";
|
|
96688
|
-
import { extname as extname2, join as
|
|
98864
|
+
import { extname as extname2, join as join32 } from "node:path";
|
|
96689
98865
|
import { pathToFileURL as pathToFileURL3 } from "node:url";
|
|
96690
98866
|
|
|
96691
98867
|
// src/engine/storage/files/scratch-directory.ts
|
|
96692
98868
|
import { randomUUID as randomUUID18 } from "node:crypto";
|
|
96693
|
-
import { lstat as lstat4, mkdir as mkdir5, readdir as readdir6, readFile as
|
|
96694
|
-
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";
|
|
96695
98871
|
async function atomicWrite(path6, bytes, signal) {
|
|
96696
98872
|
const temporary = `${path6}.${randomUUID18()}.tmp`;
|
|
96697
98873
|
try {
|
|
@@ -96705,7 +98881,7 @@ async function atomicWrite(path6, bytes, signal) {
|
|
|
96705
98881
|
var ScratchDirectory = class {
|
|
96706
98882
|
#root;
|
|
96707
98883
|
constructor(parent) {
|
|
96708
|
-
this.#root =
|
|
98884
|
+
this.#root = join31(parent, randomUUID18());
|
|
96709
98885
|
}
|
|
96710
98886
|
/** Refreshes this directory's lease and removes sibling directories whose lease is older than `leaseMilliseconds`. */
|
|
96711
98887
|
refreshLease = async (leaseMilliseconds) => {
|
|
@@ -96716,7 +98892,7 @@ var ScratchDirectory = class {
|
|
|
96716
98892
|
if (!directory.isDirectory() || !/^[a-f0-9-]{36}$/u.test(directory.name)) {
|
|
96717
98893
|
continue;
|
|
96718
98894
|
}
|
|
96719
|
-
const path6 =
|
|
98895
|
+
const path6 = join31(dirname11(this.#root), directory.name);
|
|
96720
98896
|
if (path6 === this.#root) {
|
|
96721
98897
|
continue;
|
|
96722
98898
|
}
|
|
@@ -96731,10 +98907,10 @@ var ScratchDirectory = class {
|
|
|
96731
98907
|
};
|
|
96732
98908
|
/** Writes `bytes` atomically to `<group>/<name>` with owner-only permissions and returns the path. */
|
|
96733
98909
|
write = async (group, name2, bytes, signal) => {
|
|
96734
|
-
const directory =
|
|
98910
|
+
const directory = join31(this.#root, group);
|
|
96735
98911
|
await mkdir5(directory, { mode: 448, recursive: true });
|
|
96736
98912
|
signal.throwIfAborted();
|
|
96737
|
-
const path6 =
|
|
98913
|
+
const path6 = join31(directory, name2);
|
|
96738
98914
|
await atomicWrite(path6, bytes, signal);
|
|
96739
98915
|
return path6;
|
|
96740
98916
|
};
|
|
@@ -96758,7 +98934,7 @@ var ScratchDirectory = class {
|
|
|
96758
98934
|
read = async (path6, signal) => {
|
|
96759
98935
|
const resolved = await this.resolveFile(path6);
|
|
96760
98936
|
signal.throwIfAborted();
|
|
96761
|
-
return resolved === null ? null : new Uint8Array(await
|
|
98937
|
+
return resolved === null ? null : new Uint8Array(await readFile8(resolved, { signal }));
|
|
96762
98938
|
};
|
|
96763
98939
|
removeAll = async () => {
|
|
96764
98940
|
await rm5(this.#root, { force: true, recursive: true });
|
|
@@ -96785,7 +98961,7 @@ var LocalExternalContentStore = class {
|
|
|
96785
98961
|
#expirationTimer;
|
|
96786
98962
|
#cleanup = Promise.resolve();
|
|
96787
98963
|
constructor(stateDirectory) {
|
|
96788
|
-
this.#scratch = new ScratchDirectory(
|
|
98964
|
+
this.#scratch = new ScratchDirectory(join32(stateDirectory, "tmp", "session-content"));
|
|
96789
98965
|
this.#expirationTimer = setInterval(() => {
|
|
96790
98966
|
void this.#expire().catch(() => void 0);
|
|
96791
98967
|
}, 6e4);
|
|
@@ -97193,7 +99369,7 @@ var AgentProcessPool = class {
|
|
|
97193
99369
|
|
|
97194
99370
|
// src/engine/session/settings/agent-settings-cache.ts
|
|
97195
99371
|
import { createHash as createHash9, randomUUID as randomUUID19 } from "node:crypto";
|
|
97196
|
-
import { join as
|
|
99372
|
+
import { join as join33 } from "node:path";
|
|
97197
99373
|
var CACHE_FILE_LIMIT = 32 * 1024 * 1024;
|
|
97198
99374
|
var CACHE_FORMAT = 1;
|
|
97199
99375
|
var generationSchema = external_exports.union([external_exports.literal("initial"), external_exports.uuid()]);
|
|
@@ -97258,8 +99434,8 @@ var AgentSettingsCache = class {
|
|
|
97258
99434
|
#generationPath;
|
|
97259
99435
|
#generation = 0;
|
|
97260
99436
|
constructor(stateDirectory) {
|
|
97261
|
-
this.#directory =
|
|
97262
|
-
this.#generationPath =
|
|
99437
|
+
this.#directory = join33(stateDirectory, "agent-settings");
|
|
99438
|
+
this.#generationPath = join33(this.#directory, "generation");
|
|
97263
99439
|
}
|
|
97264
99440
|
get generation() {
|
|
97265
99441
|
return this.#generation;
|
|
@@ -97270,7 +99446,7 @@ var AgentSettingsCache = class {
|
|
|
97270
99446
|
};
|
|
97271
99447
|
open = async (agent2, signal) => {
|
|
97272
99448
|
const inspections = /* @__PURE__ */ new Map();
|
|
97273
|
-
const path6 =
|
|
99449
|
+
const path6 = join33(this.#directory, `${hash2(agent2.id)}.json`);
|
|
97274
99450
|
const fingerprint = hash2([
|
|
97275
99451
|
agent2.agentVersion,
|
|
97276
99452
|
agent2.adapterVersion,
|
|
@@ -97361,6 +99537,243 @@ var AgentSettingsCache = class {
|
|
|
97361
99537
|
};
|
|
97362
99538
|
};
|
|
97363
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
|
+
|
|
97364
99777
|
// src/engine/runtime/relay/diagnostics.ts
|
|
97365
99778
|
var MAX_DIAGNOSTIC_TEXT_LENGTH = 256;
|
|
97366
99779
|
function sanitizeDiagnosticText(value) {
|
|
@@ -97544,7 +99957,7 @@ var RelayConnectionDiagnostics = class {
|
|
|
97544
99957
|
};
|
|
97545
99958
|
|
|
97546
99959
|
// src/engine/runtime/relay/run-relay-connection.ts
|
|
97547
|
-
import { WebSocket as
|
|
99960
|
+
import { WebSocket as WebSocket9 } from "undici";
|
|
97548
99961
|
|
|
97549
99962
|
// src/engine/runtime/catalog/handle-agent-catalog-discovery.ts
|
|
97550
99963
|
import { WebSocket as WebSocket3 } from "undici";
|
|
@@ -98295,7 +100708,7 @@ function createContentWriteCommands(context) {
|
|
|
98295
100708
|
import { WebSocket as WebSocket5 } from "undici";
|
|
98296
100709
|
|
|
98297
100710
|
// src/engine/session/content/session-files.ts
|
|
98298
|
-
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";
|
|
98299
100712
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
98300
100713
|
function requestedPath(value) {
|
|
98301
100714
|
if (value.includes("\0")) {
|
|
@@ -98319,7 +100732,7 @@ async function resolveFile(value, workingDirectory, signal) {
|
|
|
98319
100732
|
if (isAbsolute17(requested.path) && normalize3(requested.path) !== requested.path) {
|
|
98320
100733
|
return null;
|
|
98321
100734
|
}
|
|
98322
|
-
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)];
|
|
98323
100736
|
for (const candidate of candidates) {
|
|
98324
100737
|
if (!isAbsolute17(candidate) || normalize3(candidate) !== candidate) {
|
|
98325
100738
|
continue;
|
|
@@ -99214,6 +101627,9 @@ var sessionPromptSuggestionReadCommand = {
|
|
|
99214
101627
|
}
|
|
99215
101628
|
};
|
|
99216
101629
|
|
|
101630
|
+
// src/engine/runtime/command/registry/runtime.ts
|
|
101631
|
+
import { WebSocket as WebSocket7 } from "undici";
|
|
101632
|
+
|
|
99217
101633
|
// src/engine/runtime/observability/environment-diagnostics.ts
|
|
99218
101634
|
import { release } from "node:os";
|
|
99219
101635
|
function version2(value) {
|
|
@@ -99321,10 +101737,59 @@ var runtimePingCommand = {
|
|
|
99321
101737
|
promptSuggestions: true,
|
|
99322
101738
|
sessionTitleGeneration: true,
|
|
99323
101739
|
requestId: message.requestId,
|
|
99324
|
-
scopedFileRead: supportsScopedLocalFileRead()
|
|
101740
|
+
scopedFileRead: supportsScopedLocalFileRead(),
|
|
101741
|
+
usageQuota: true
|
|
99325
101742
|
});
|
|
99326
101743
|
}
|
|
99327
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
|
+
}
|
|
99328
101793
|
|
|
99329
101794
|
// src/engine/runtime/command/registry/session.ts
|
|
99330
101795
|
async function prepareSession(command, recovery, closed, config2, resolveAgent, directories, sessions, metrics, signal) {
|
|
@@ -99717,6 +102182,7 @@ function createCommandRegistry(context) {
|
|
|
99717
102182
|
const commands = [
|
|
99718
102183
|
runtimeDiagnosticsCommand,
|
|
99719
102184
|
runtimePingCommand,
|
|
102185
|
+
createRuntimeUsageReadCommand(),
|
|
99720
102186
|
sessionHistoryPageLoadCommand,
|
|
99721
102187
|
previewHistoryPageLoadCommand,
|
|
99722
102188
|
...createNativeSessionCommands(context),
|
|
@@ -99778,7 +102244,7 @@ function createRuntimeCommandDispatcher(options) {
|
|
|
99778
102244
|
}
|
|
99779
102245
|
|
|
99780
102246
|
// src/engine/runtime/relay/connect.ts
|
|
99781
|
-
import { WebSocket as
|
|
102247
|
+
import { WebSocket as WebSocket8 } from "undici";
|
|
99782
102248
|
var CONNECTION_TIMEOUT_MILLISECONDS = 6e4;
|
|
99783
102249
|
var RelayConnectionError = class extends Error {
|
|
99784
102250
|
code;
|
|
@@ -99792,7 +102258,7 @@ var RelayConnectionError = class extends Error {
|
|
|
99792
102258
|
};
|
|
99793
102259
|
function connectRelay(url2, signal, transportFailed = () => void 0) {
|
|
99794
102260
|
signal.throwIfAborted();
|
|
99795
|
-
return new Promise((
|
|
102261
|
+
return new Promise((resolve21, reject2) => {
|
|
99796
102262
|
let releaseTransport = () => void 0;
|
|
99797
102263
|
let removeTransportObserver = () => void 0;
|
|
99798
102264
|
let released = false;
|
|
@@ -99843,7 +102309,7 @@ function connectRelay(url2, signal, transportFailed = () => void 0) {
|
|
|
99843
102309
|
const endpoint = new URL(url2);
|
|
99844
102310
|
const headers = relayAuthorization(endpoint);
|
|
99845
102311
|
endpoint.searchParams.delete("token");
|
|
99846
|
-
const socket = new
|
|
102312
|
+
const socket = new WebSocket8(endpoint, {
|
|
99847
102313
|
dispatcher,
|
|
99848
102314
|
headers
|
|
99849
102315
|
});
|
|
@@ -99916,7 +102382,7 @@ function connectRelay(url2, signal, transportFailed = () => void 0) {
|
|
|
99916
102382
|
}
|
|
99917
102383
|
finished = true;
|
|
99918
102384
|
cleanup();
|
|
99919
|
-
|
|
102385
|
+
resolve21({ release: release2, socket });
|
|
99920
102386
|
};
|
|
99921
102387
|
function onTimeout() {
|
|
99922
102388
|
fail(
|
|
@@ -100049,6 +102515,7 @@ async function runRelayConnection({
|
|
|
100049
102515
|
reportUpgradeAvailability,
|
|
100050
102516
|
directories,
|
|
100051
102517
|
sessionTurns,
|
|
102518
|
+
usageService,
|
|
100052
102519
|
nativeSessions,
|
|
100053
102520
|
operations,
|
|
100054
102521
|
publisher,
|
|
@@ -100080,13 +102547,14 @@ async function runRelayConnection({
|
|
|
100080
102547
|
eventProjection,
|
|
100081
102548
|
externalContent,
|
|
100082
102549
|
sessionTurns,
|
|
102550
|
+
usageService,
|
|
100083
102551
|
diagnostics,
|
|
100084
102552
|
socket,
|
|
100085
102553
|
signal: connectionController.signal,
|
|
100086
102554
|
timer
|
|
100087
102555
|
});
|
|
100088
102556
|
void reportUpgradeAvailability((result) => {
|
|
100089
|
-
if (socket.readyState ===
|
|
102557
|
+
if (socket.readyState === WebSocket9.OPEN) {
|
|
100090
102558
|
send(socket, result);
|
|
100091
102559
|
}
|
|
100092
102560
|
}, signal).catch((cause) => {
|
|
@@ -100095,7 +102563,7 @@ async function runRelayConnection({
|
|
|
100095
102563
|
}
|
|
100096
102564
|
});
|
|
100097
102565
|
try {
|
|
100098
|
-
await new Promise((
|
|
102566
|
+
await new Promise((resolve21, reject2) => {
|
|
100099
102567
|
let finished = false;
|
|
100100
102568
|
let ready = false;
|
|
100101
102569
|
const cleanup = () => {
|
|
@@ -100113,7 +102581,7 @@ async function runRelayConnection({
|
|
|
100113
102581
|
}
|
|
100114
102582
|
finished = true;
|
|
100115
102583
|
cleanup();
|
|
100116
|
-
|
|
102584
|
+
resolve21();
|
|
100117
102585
|
};
|
|
100118
102586
|
const rejectConnection = (failure2) => {
|
|
100119
102587
|
if (finished) {
|
|
@@ -100137,14 +102605,14 @@ async function runRelayConnection({
|
|
|
100137
102605
|
};
|
|
100138
102606
|
const connectionLiveness = new RelayConnectionLiveness(timer, {
|
|
100139
102607
|
send: (message) => {
|
|
100140
|
-
if (socket.readyState !==
|
|
102608
|
+
if (socket.readyState !== WebSocket9.OPEN) {
|
|
100141
102609
|
return false;
|
|
100142
102610
|
}
|
|
100143
102611
|
try {
|
|
100144
102612
|
send(socket, message);
|
|
100145
102613
|
return true;
|
|
100146
102614
|
} catch (error62) {
|
|
100147
|
-
if (socket.readyState !==
|
|
102615
|
+
if (socket.readyState !== WebSocket9.OPEN) {
|
|
100148
102616
|
return false;
|
|
100149
102617
|
}
|
|
100150
102618
|
throw error62;
|
|
@@ -100246,7 +102714,7 @@ async function runRelayConnection({
|
|
|
100246
102714
|
}
|
|
100247
102715
|
|
|
100248
102716
|
// src/engine/runtime/relay/session-event-publisher.ts
|
|
100249
|
-
import { WebSocket as
|
|
102717
|
+
import { WebSocket as WebSocket10 } from "undici";
|
|
100250
102718
|
var MAX_BUFFERED_BYTES = 32 * 1024 * 1024;
|
|
100251
102719
|
var MAX_PENDING_BYTES2 = 32 * 1024 * 1024;
|
|
100252
102720
|
var MAX_EVENT_BATCH_BYTES = 1024 * 1024;
|
|
@@ -100301,7 +102769,7 @@ var RuntimeSessionEventPublisher = class {
|
|
|
100301
102769
|
};
|
|
100302
102770
|
#send = (message) => {
|
|
100303
102771
|
const connection = this.#connection;
|
|
100304
|
-
if (connection.kind !== "connected" || connection.socket.readyState !==
|
|
102772
|
+
if (connection.kind !== "connected" || connection.socket.readyState !== WebSocket10.OPEN) {
|
|
100305
102773
|
return;
|
|
100306
102774
|
}
|
|
100307
102775
|
const socket = connection.socket;
|
|
@@ -100363,7 +102831,7 @@ var RuntimeSessionEventPublisher = class {
|
|
|
100363
102831
|
});
|
|
100364
102832
|
}
|
|
100365
102833
|
const connection = this.#connection;
|
|
100366
|
-
if (connection.kind !== "connected" || connection.socket.readyState !==
|
|
102834
|
+
if (connection.kind !== "connected" || connection.socket.readyState !== WebSocket10.OPEN) {
|
|
100367
102835
|
return;
|
|
100368
102836
|
}
|
|
100369
102837
|
const socket = connection.socket;
|
|
@@ -100402,7 +102870,7 @@ var RuntimeSessionEventPublisher = class {
|
|
|
100402
102870
|
flushEvents = (socket) => {
|
|
100403
102871
|
this.cancelFlush();
|
|
100404
102872
|
const connection = this.#connection;
|
|
100405
|
-
if (connection.kind !== "connected" || connection.socket !== socket || socket.readyState !==
|
|
102873
|
+
if (connection.kind !== "connected" || connection.socket !== socket || socket.readyState !== WebSocket10.OPEN) {
|
|
100406
102874
|
return;
|
|
100407
102875
|
}
|
|
100408
102876
|
let sent = 0;
|
|
@@ -100449,12 +102917,12 @@ function waitForRelayRetry(signal, timer) {
|
|
|
100449
102917
|
if (signal.aborted) {
|
|
100450
102918
|
return Promise.resolve();
|
|
100451
102919
|
}
|
|
100452
|
-
return new Promise((
|
|
102920
|
+
return new Promise((resolve21) => {
|
|
100453
102921
|
const retry = timer.schedule(finish, RELAY_RECONNECT_DELAY_MILLISECONDS);
|
|
100454
102922
|
function finish() {
|
|
100455
102923
|
retry.cancel();
|
|
100456
102924
|
signal.removeEventListener("abort", finish);
|
|
100457
|
-
|
|
102925
|
+
resolve21();
|
|
100458
102926
|
}
|
|
100459
102927
|
signal.addEventListener("abort", finish, { once: true });
|
|
100460
102928
|
});
|
|
@@ -100499,11 +102967,13 @@ async function runRuntime(config2, parentSignal, timer = systemTimer, options =
|
|
|
100499
102967
|
const publisher = new RuntimeSessionEventPublisher(timer);
|
|
100500
102968
|
const externalContent = __using(_stack, new LocalExternalContentStore(stateDirectory), true);
|
|
100501
102969
|
const processes = new AgentProcessPool(config2.localContext.maxAcpProcesses, timer);
|
|
102970
|
+
let usageService = null;
|
|
100502
102971
|
const { adapters, externalizeSessionUpdate } = createRuntimeAdapterRegistry(
|
|
100503
102972
|
config2.adapters,
|
|
100504
102973
|
processes,
|
|
100505
102974
|
(sessionId, content, contentSignal) => externalContent.put({ ...content, sessionId, signal: contentSignal }),
|
|
100506
|
-
externalContent.linkedResources
|
|
102975
|
+
externalContent.linkedResources,
|
|
102976
|
+
(report) => usageService?.recordPassiveUpdate(report)
|
|
100507
102977
|
);
|
|
100508
102978
|
const resolveAgent = async (agentId, resolveSignal, sessionId) => {
|
|
100509
102979
|
const catalogAgent = await resolveCatalogAgent(config2, agentId, resolveSignal);
|
|
@@ -100515,6 +102985,11 @@ async function runRuntime(config2, parentSignal, timer = systemTimer, options =
|
|
|
100515
102985
|
externalizeSessionUpdate
|
|
100516
102986
|
};
|
|
100517
102987
|
};
|
|
102988
|
+
usageService = new RuntimeUsageService({
|
|
102989
|
+
listAgents: () => config2.catalog.read().agents,
|
|
102990
|
+
resolveAgent,
|
|
102991
|
+
defaultWorkspace: config2.defaultWorkspace
|
|
102992
|
+
});
|
|
100518
102993
|
const layer = buildSessionLayer({
|
|
100519
102994
|
processes,
|
|
100520
102995
|
...options.turnActivity === void 0 ? {} : { turnActivity: options.turnActivity },
|
|
@@ -100593,6 +103068,7 @@ async function runRuntime(config2, parentSignal, timer = systemTimer, options =
|
|
|
100593
103068
|
eventProjection,
|
|
100594
103069
|
externalContent,
|
|
100595
103070
|
sessionTurns: activeSessions,
|
|
103071
|
+
usageService,
|
|
100596
103072
|
connectionEpoch,
|
|
100597
103073
|
reportUpgradeAvailability,
|
|
100598
103074
|
diagnostics,
|
|
@@ -100676,7 +103152,7 @@ function relayUrlFromConnection(connection) {
|
|
|
100676
103152
|
return relayUrl;
|
|
100677
103153
|
}
|
|
100678
103154
|
async function resolveWorkspace(path6) {
|
|
100679
|
-
const requested =
|
|
103155
|
+
const requested = resolve19(path6);
|
|
100680
103156
|
let resolved;
|
|
100681
103157
|
try {
|
|
100682
103158
|
resolved = await ensureCanonicalDirectory(requested);
|
|
@@ -100775,7 +103251,7 @@ var MobiusRuntimeEngine = class {
|
|
|
100775
103251
|
#connections;
|
|
100776
103252
|
#installation = { kind: "uninitialized" };
|
|
100777
103253
|
constructor(params) {
|
|
100778
|
-
this.#engineDataDir =
|
|
103254
|
+
this.#engineDataDir = resolve20(params.engineDataDir);
|
|
100779
103255
|
this.#agentLaunchEnvironment = Object.freeze({ ...params.agentLaunchEnvironment });
|
|
100780
103256
|
this.#maxAcpProcesses = params.maxAcpProcesses ?? 1e3;
|
|
100781
103257
|
this.#connections = new ConnectionManager(this.#ensureInstallation);
|
|
@@ -100896,4 +103372,4 @@ export {
|
|
|
100896
103372
|
* MIT Licensed
|
|
100897
103373
|
*)
|
|
100898
103374
|
*/
|
|
100899
|
-
//# sourceMappingURL=chunk-
|
|
103375
|
+
//# sourceMappingURL=chunk-GUE7ZQI6.js.map
|