dsh-agy 0.1.3 → 0.2.1
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/lib/cli/index.mjs +4 -4
- package/lib/{exchange-BNNR9Cba.mjs → exchange-BkQRoBzy.mjs} +2 -2
- package/lib/{exchange-BNNR9Cba.mjs.map → exchange-BkQRoBzy.mjs.map} +1 -1
- package/lib/{import-D7455oFm.mjs → import-KAAtJXZP.mjs} +3 -3
- package/lib/{import-D7455oFm.mjs.map → import-KAAtJXZP.mjs.map} +1 -1
- package/lib/index.mjs +1 -1
- package/lib/{models-CfP-YGGN.mjs → models-BpIXp4vx.mjs} +2 -2
- package/lib/{models-CfP-YGGN.mjs.map → models-BpIXp4vx.mjs.map} +1 -1
- package/lib/{parse-CiEzD9d_.mjs → parse-D8bV2yqa.mjs} +25 -11
- package/lib/parse-D8bV2yqa.mjs.map +1 -0
- package/lib/{plugin-common-DPgWbKSr.mjs → plugin-common-BDQB_5km.mjs} +18 -5
- package/lib/plugin-common-BDQB_5km.mjs.map +1 -0
- package/lib/{session-Drzy1MBH.mjs → session-CyoQxOqv.mjs} +32 -24
- package/lib/session-CyoQxOqv.mjs.map +1 -0
- package/lib/{translate-CLzL4gLS.mjs → translate-CYV7R-UO.mjs} +57 -8
- package/lib/translate-CYV7R-UO.mjs.map +1 -0
- package/lib/web/plugin.mjs +6 -6
- package/package.json +1 -1
- package/lib/parse-CiEzD9d_.mjs.map +0 -1
- package/lib/plugin-common-DPgWbKSr.mjs.map +0 -1
- package/lib/session-Drzy1MBH.mjs.map +0 -1
- package/lib/translate-CLzL4gLS.mjs.map +0 -1
|
@@ -89,9 +89,10 @@ const AGY_VERSION_FALLBACK = "1.18.3";
|
|
|
89
89
|
function getAgyBootstrapUserAgent(version = AGY_VERSION_FALLBACK) {
|
|
90
90
|
return `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Antigravity/${version} Chrome/138.0.7204.235 Electron/37.3.1 Safari/537.36`;
|
|
91
91
|
}
|
|
92
|
-
/** Client-Metadata payload for bootstrap calls
|
|
93
|
-
|
|
94
|
-
|
|
92
|
+
/** Client-Metadata payload for bootstrap calls — ideType only (backend enum
|
|
93
|
+
* validation rejects freely-added platform/pluginType; AGENTS.md invariant). */
|
|
94
|
+
function getAgyBootstrapClientMetadata() {
|
|
95
|
+
return "{\"ideType\":\"ANTIGRAVITY\"}";
|
|
95
96
|
}
|
|
96
97
|
//#endregion
|
|
97
98
|
//#region src/runtime/identity.ts
|
|
@@ -764,6 +765,7 @@ function decideRotation(kind, account, consecutiveFailures, retryAfterMs, catego
|
|
|
764
765
|
action: "cool",
|
|
765
766
|
backoffMs
|
|
766
767
|
};
|
|
768
|
+
case "request-error": return { action: "noop" };
|
|
767
769
|
case "transient": return {
|
|
768
770
|
action: "retry",
|
|
769
771
|
backoffMs
|
|
@@ -871,9 +873,6 @@ function getFingerprintData() {
|
|
|
871
873
|
function randomFrom(arr) {
|
|
872
874
|
return arr[Math.floor(Math.random() * arr.length)];
|
|
873
875
|
}
|
|
874
|
-
function platformToDisplayName(platform) {
|
|
875
|
-
return platform.startsWith("windows") ? "WINDOWS" : "MACOS";
|
|
876
|
-
}
|
|
877
876
|
/** Generate a randomized device fingerprint representing one apparent device. */
|
|
878
877
|
function generateFingerprint(data = getFingerprintData(), version = randomFrom(data.versionPool)) {
|
|
879
878
|
const platform = randomFrom(data.platforms);
|
|
@@ -882,25 +881,16 @@ function generateFingerprint(data = getFingerprintData(), version = randomFrom(d
|
|
|
882
881
|
sessionToken: randomBytes(16).toString("hex"),
|
|
883
882
|
userAgent: `antigravity/${version} ${platform}`,
|
|
884
883
|
apiClient: randomFrom(data.sdkClients),
|
|
885
|
-
clientMetadata: {
|
|
886
|
-
ideType: randomFrom(data.ideTypes),
|
|
887
|
-
platform: platformToDisplayName(platform),
|
|
888
|
-
pluginType: randomFrom(data.pluginTypes)
|
|
889
|
-
},
|
|
884
|
+
clientMetadata: { ideType: randomFrom(data.ideTypes) },
|
|
890
885
|
createdAt: Date.now()
|
|
891
886
|
};
|
|
892
887
|
}
|
|
893
888
|
/** Per-request randomized headers (platform + SDK client pools). */
|
|
894
889
|
function getRandomizedHeaders(data = getFingerprintData(), version = randomFrom(data.versionPool)) {
|
|
895
|
-
const platform = randomFrom(data.platforms);
|
|
896
890
|
return {
|
|
897
|
-
"User-Agent": `antigravity/${version} ${
|
|
891
|
+
"User-Agent": `antigravity/${version} ${randomFrom(data.platforms)}`,
|
|
898
892
|
"X-Goog-Api-Client": randomFrom(data.sdkClients),
|
|
899
|
-
"Client-Metadata": JSON.stringify({
|
|
900
|
-
ideType: randomFrom(data.ideTypes),
|
|
901
|
-
platform: platformToDisplayName(platform),
|
|
902
|
-
pluginType: randomFrom(data.pluginTypes)
|
|
903
|
-
})
|
|
893
|
+
"Client-Metadata": JSON.stringify({ ideType: randomFrom(data.ideTypes) })
|
|
904
894
|
};
|
|
905
895
|
}
|
|
906
896
|
/** Rewrite the version inside a fingerprint UA; reports whether it changed. */
|
|
@@ -919,8 +909,6 @@ function recordFingerprintVersion(history, fingerprint, reason) {
|
|
|
919
909
|
reason
|
|
920
910
|
}].slice(-5);
|
|
921
911
|
}
|
|
922
|
-
//#endregion
|
|
923
|
-
//#region src/session.ts
|
|
924
912
|
/**
|
|
925
913
|
* Resolve the impersonation headers for one request from the account's
|
|
926
914
|
* persistent fingerprint (stable identity), falling back to full per-request
|
|
@@ -949,6 +937,14 @@ var AgySessionManager = class {
|
|
|
949
937
|
failureCounts = /* @__PURE__ */ new Map();
|
|
950
938
|
/** Accounts whose request-time project discovery already failed (no retry per request). */
|
|
951
939
|
projectRetryFailed = /* @__PURE__ */ new Set();
|
|
940
|
+
/**
|
|
941
|
+
* Session affinity (time-window approximation): DSH exposes no conversation
|
|
942
|
+
* id, so instead of pinning per session we reuse the last-used account while
|
|
943
|
+
* it is fresh. Keeps upstream prefix caching and sessionId continuity across
|
|
944
|
+
* the turns of one conversation (OmniRoute pins by session for the same
|
|
945
|
+
* reason). Cleared on rotate so a failure re-picks from activeIndex.
|
|
946
|
+
*/
|
|
947
|
+
lastUsed = null;
|
|
952
948
|
constructor(options) {
|
|
953
949
|
this.store = options.store;
|
|
954
950
|
this.onRotate = options.onRotate;
|
|
@@ -1001,6 +997,13 @@ var AgySessionManager = class {
|
|
|
1001
997
|
for (const account of storage.accounts) clearExpiredState(account, now);
|
|
1002
998
|
let resolved = resolveActiveAccount(storage);
|
|
1003
999
|
if (!resolved) return void 0;
|
|
1000
|
+
if (this.lastUsed && now - this.lastUsed.at < 6e5) {
|
|
1001
|
+
const last = storage.accounts[this.lastUsed.index];
|
|
1002
|
+
if (last && last.enabled !== false && !isCoolingDown(last, now)) resolved = {
|
|
1003
|
+
account: last,
|
|
1004
|
+
index: this.lastUsed.index
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1004
1007
|
if (isCoolingDown(resolved.account, now)) {
|
|
1005
1008
|
const nextIndex = pickNextAccountIndex(storage.accounts, resolved.index, now);
|
|
1006
1009
|
if (nextIndex !== resolved.index) resolved = {
|
|
@@ -1024,7 +1027,7 @@ var AgySessionManager = class {
|
|
|
1024
1027
|
if (!auth) return void 0;
|
|
1025
1028
|
const key = this.accountKey(picked.account);
|
|
1026
1029
|
if (!picked.account.projectId && !this.projectRetryFailed.has(key)) try {
|
|
1027
|
-
const { loadCodeAssist } = await import("./exchange-
|
|
1030
|
+
const { loadCodeAssist } = await import("./exchange-BkQRoBzy.mjs").then((n) => n.n);
|
|
1028
1031
|
const { projectId } = await loadCodeAssist(auth.access);
|
|
1029
1032
|
if (projectId) {
|
|
1030
1033
|
await this.store.mutate((s) => {
|
|
@@ -1044,6 +1047,10 @@ var AgySessionManager = class {
|
|
|
1044
1047
|
} catch {
|
|
1045
1048
|
this.projectRetryFailed.add(key);
|
|
1046
1049
|
}
|
|
1050
|
+
this.lastUsed = {
|
|
1051
|
+
index: picked.index,
|
|
1052
|
+
at: Date.now()
|
|
1053
|
+
};
|
|
1047
1054
|
return {
|
|
1048
1055
|
auth,
|
|
1049
1056
|
account: picked.account,
|
|
@@ -1086,6 +1093,7 @@ var AgySessionManager = class {
|
|
|
1086
1093
|
storage.activeIndex = nextIndex;
|
|
1087
1094
|
this.onRotate?.(session.index, nextIndex, kind);
|
|
1088
1095
|
}
|
|
1096
|
+
this.lastUsed = null;
|
|
1089
1097
|
}
|
|
1090
1098
|
await this.store.save(storage);
|
|
1091
1099
|
}
|
|
@@ -1106,9 +1114,9 @@ var AgySessionManager = class {
|
|
|
1106
1114
|
error: "No agy account configured — run `dsh-agy login` first."
|
|
1107
1115
|
};
|
|
1108
1116
|
try {
|
|
1109
|
-
const { toAgyRequestBody } = await import("./translate-
|
|
1117
|
+
const { toAgyRequestBody } = await import("./translate-CYV7R-UO.mjs").then((n) => n.n);
|
|
1110
1118
|
const { fetchAgyFirstOk } = await Promise.resolve().then(() => constants_exports);
|
|
1111
|
-
const { parseAgySse } = await import("./parse-
|
|
1119
|
+
const { parseAgySse } = await import("./parse-D8bV2yqa.mjs").then((n) => n.n);
|
|
1112
1120
|
const body = toAgyRequestBody({
|
|
1113
1121
|
provider: "agy",
|
|
1114
1122
|
model,
|
|
@@ -1218,4 +1226,4 @@ var AgySessionManager = class {
|
|
|
1218
1226
|
//#endregion
|
|
1219
1227
|
export { OAUTH_TOKEN_URL as C, getAgyBootstrapUserAgent as D, getAgyBootstrapClientMetadata as E, OAUTH_AUTHORIZE_URL as S, fetchAgyFirstOk as T, AGY_CLIENT_ID as _, MASTER_KEY_REF as a, AGY_ENDPOINT_FALLBACKS as b, loadMasterKey as c, resolveMasterKeyCodec as d, calculateTokenExpiry as f, generateAntigravityRequestId as g, deriveAntigravitySessionId as h, JsonAccountStore as i, persistMasterKey as l, resolveAntigravityVersionBounded as m, generateFingerprint as n, createAesGcmCodec as o, resolveAntigravityVersion as p, recordFingerprintVersion as r, deriveKey as s, AgySessionManager as t, resolveDshHome as u, AGY_CLIENT_SECRET as v, OAUTH_USERINFO_URL as w, AGY_SCOPES as x, AGY_DEFAULT_REDIRECT_URI as y };
|
|
1220
1228
|
|
|
1221
|
-
//# sourceMappingURL=session-
|
|
1229
|
+
//# sourceMappingURL=session-CyoQxOqv.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-CyoQxOqv.mjs","names":["ENC_PREFIX","fingerprintData"],"sources":["../src/oauth/constants.ts","../src/runtime/identity.ts","../src/runtime/version.ts","../src/oauth/auth.ts","../src/oauth/refresh.ts","../src/store/keyring.ts","../src/store/accounts.ts","../src/runtime/rotation.ts","../src/runtime/fingerprint-data.json","../src/runtime/fingerprint.ts","../src/session.ts"],"sourcesContent":["/**\n * Antigravity (agy) OAuth and API constants.\n *\n * The client id/secret below are the public Google consumer-OAuth credentials\n * shipped inside the Antigravity desktop product and its `agy` CLI; they are\n * embedded in many public tools (see NOTICE.md). They are not secrets owned by\n * this project.\n */\n\nexport const AGY_CLIENT_ID =\n '1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com'\n\nexport const AGY_CLIENT_SECRET = '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'\n\n/** Required scopes. `openid` must NOT be added: it routes Google into the hanging\n * `firstparty/nativeapp` consent for this client (verified by OmniRoute). */\nexport const AGY_SCOPES: readonly string[] = [\n 'https://www.googleapis.com/auth/cloud-platform',\n 'https://www.googleapis.com/auth/userinfo.email',\n 'https://www.googleapis.com/auth/userinfo.profile',\n 'https://www.googleapis.com/auth/cclog',\n 'https://www.googleapis.com/auth/experimentsandconfigs',\n]\n\nexport const OAUTH_AUTHORIZE_URL = 'https://accounts.google.com/o/oauth2/v2/auth'\nexport const OAUTH_TOKEN_URL = 'https://oauth2.googleapis.com/token'\nexport const OAUTH_USERINFO_URL = 'https://www.googleapis.com/oauth2/v1/userinfo'\n\n/** Default loopback callback used by the standalone CLI listener (fixed port, like opencode). */\nexport const AGY_DEFAULT_REDIRECT_URI = 'http://localhost:51121/oauth-callback'\n\n/**\n * Antigravity API endpoints. The daily runtime host (no .sandbox suffix) is the\n * live endpoint for consumer OAuth accounts — cloudcode-pa.googleapis.com\n * answers RESOURCE_EXHAUSTED for them (verified by live probe), while the\n * daily host answers 200. Order matters: first reachable non-429/403 wins.\n */\nexport const AGY_ENDPOINT_DAILY = 'https://daily-cloudcode-pa.googleapis.com'\nexport const AGY_ENDPOINT_PROD = 'https://cloudcode-pa.googleapis.com'\nexport const AGY_ENDPOINT_DAILY_SANDBOX = 'https://daily-cloudcode-pa.sandbox.googleapis.com'\nexport const AGY_ENDPOINT_AUTOPUSH = 'https://autopush-cloudcode-pa.sandbox.googleapis.com'\n\n/** Runtime/bootstrap endpoint fallback order (daily first, mirroring OmniRoute). */\nexport const AGY_ENDPOINT_FALLBACKS: readonly string[] = [\n AGY_ENDPOINT_DAILY,\n AGY_ENDPOINT_PROD,\n AGY_ENDPOINT_DAILY_SANDBOX,\n AGY_ENDPOINT_AUTOPUSH,\n]\n\n/** Statuses that mean \"this endpoint is not usable for this account\"; skip to the next. */\nexport const AGY_ENDPOINT_SKIP_STATUSES = new Set([429, 403])\n\n/**\n * Try each runtime endpoint in order, skipping unusable ones (429/403/network).\n * Returns the first other response (2xx or a real error like 400/401); when\n * every endpoint is unusable, returns the last skipped response so the caller's\n * classifier can still produce a meaningful error.\n */\nexport async function fetchAgyFirstOk(\n urlPath: string,\n init: RequestInit,\n fetchImpl: typeof fetch = fetch,\n): Promise<Response> {\n let lastSkipped: Response | null = null\n for (const baseEndpoint of AGY_ENDPOINT_FALLBACKS) {\n try {\n const response = await fetchImpl(`${baseEndpoint}${urlPath}`, init)\n if (!AGY_ENDPOINT_SKIP_STATUSES.has(response.status)) return response\n lastSkipped = response\n } catch {\n // network error — try the next endpoint\n }\n }\n if (lastSkipped) return lastSkipped\n throw new Error('all agy endpoints failed')\n}\n\n/** Default Antigravity client version used in User-Agent strings; overridden by the\n * runtime version fetcher (see runtime/fingerprint.ts). */\nexport const AGY_VERSION_FALLBACK = '1.18.3'\n\n/** Electron-style UA used for bootstrap calls (loadCodeAssist/onboardUser). */\nexport function getAgyBootstrapUserAgent(version = AGY_VERSION_FALLBACK): string {\n return `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Antigravity/${version} Chrome/138.0.7204.235 Electron/37.3.1 Safari/537.36`\n}\n\n/** Client-Metadata payload for bootstrap calls — ideType only (backend enum\n * validation rejects freely-added platform/pluginType; AGENTS.md invariant). */\nexport function getAgyBootstrapClientMetadata(): string {\n return '{\"ideType\":\"ANTIGRAVITY\"}'\n}\n","/**\n * Antigravity request/session identity generation (mirrors the active\n * OmniRoute implementation; the archived reference stopped maintaining these).\n */\n\nimport { randomBytes } from 'node:crypto'\n\n/** One request id per upstream call: `agent/<epoch>/<8 hex>`. */\nexport function generateAntigravityRequestId(): string {\n return `agent/${Date.now()}/${randomBytes(4).toString('hex')}`\n}\n\n/**\n * Uniformly random session id in `-{0..9e18}` via rejection sampling (avoids\n * modulo bias). The negative numeric shape matches what the backend issues.\n */\nexport function generateAntigravitySessionId(): string {\n const max = 18_446_744_073_709_551_615n // 2^64 - 1\n const target = 9_000_000_000_000_000_000n\n const limit = max - (max % target)\n let value: bigint\n do {\n value = randomBytes(8).readBigUInt64BE()\n } while (value >= limit)\n return `-${(value % target).toString()}`\n}\n\nconst FNV_OFFSET_I64 = -3_750_763_044_362_895_579n\nconst FNV_PRIME_I64 = 1_099_511_628_211n\n\n/** 64-bit FNV-1a hash of a string (stable across processes). */\nexport function fnv1a64(input: string): bigint {\n let hash = FNV_OFFSET_I64\n for (let i = 0; i < input.length; i++) {\n hash ^= BigInt(input.charCodeAt(i))\n hash = BigInt.asIntN(64, hash * FNV_PRIME_I64)\n }\n return hash\n}\n\n/**\n * Stable per-account session id: same account always derives the same id, so\n * multi-turn context caching keys consistently; unknown accounts get a fresh\n * random id.\n */\nexport function deriveAntigravitySessionId(accountKey: string | null | undefined): string | null {\n if (!accountKey || accountKey.trim().length === 0) return null\n const hash = fnv1a64(accountKey.trim())\n // Fold into the positive 9e18 range the backend accepts.\n const target = 9_000_000_000_000_000_000n\n const folded = hash < 0n ? -hash : hash\n return `-${(folded % target).toString()}`\n}\n","/**\n * Fresh Antigravity client version resolution: fetch from the product's own\n * release feeds (6h TTL, single in-flight dedupe), falling back to the pinned\n * pool. Keeps fingerprint User-Agent version strings current — a stale version\n * is the most detectable fingerprint anomaly.\n */\n\nimport { AGY_VERSION_FALLBACK } from '../oauth/constants.ts'\n\nconst VERSION_CACHE_TTL_MS = 6 * 60 * 60 * 1000\nconst VERSION_FETCH_TIMEOUT_MS = 5_000\n\n/** Source 1: Antigravity IDE auto-update release feed (array of {version}). */\nconst IDE_RELEASE_FEED_URL = 'https://antigravity-auto-updater-974169037036.us-central1.run.app/releases'\n/** Source 2: agy CLI GitHub releases (object with tag_name). */\nconst CLI_RELEASE_URL = 'https://api.github.com/repos/google-antigravity/antigravity-cli/releases/latest'\n\nexport interface FetchLike {\n (input: string | URL, init?: RequestInit): Promise<Response>\n}\n\nexport interface VersionState {\n cache?: { version: string; fetchedAt: number }\n inFlight: Promise<string> | null\n}\n\nfunction compareSemver(a: string, b: string): number {\n const pa = a.split('.').map((n) => Number(n) || 0)\n const pb = b.split('.').map((n) => Number(n) || 0)\n for (let i = 0; i < 3; i++) {\n const diff = (pa[i] ?? 0) - (pb[i] ?? 0)\n if (diff !== 0) return diff\n }\n return 0\n}\n\nfunction pickNewestVersion(...versions: Array<unknown>): string | null {\n const valid = versions\n .filter((v): v is string => typeof v === 'string' && /^\\d+\\.\\d+\\.\\d+$/.test(v))\n if (valid.length === 0) return null\n return valid.reduce<string | null>((best, v) => (!best || compareSemver(v, best) > 0 ? v : best), null)\n}\n\nfunction parseIdeReleaseFeed(payload: unknown): string | null {\n if (!Array.isArray(payload)) return null\n return pickNewestVersion(...payload.map((entry) => (entry as { version?: unknown })?.version))\n}\n\nfunction parseCliRelease(payload: unknown): string | null {\n if (!payload || typeof payload !== 'object') return null\n const release = payload as { name?: unknown; tag_name?: unknown }\n return pickNewestVersion(release.tag_name ?? release.name)\n}\n\nasync function fetchJsonWithTimeout(fetchImpl: FetchLike, url: string): Promise<unknown> {\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), VERSION_FETCH_TIMEOUT_MS)\n try {\n const response = await fetchImpl(url, {\n headers: { Accept: 'application/json', 'User-Agent': 'dsh-agy/0.1' },\n signal: controller.signal,\n })\n if (!response.ok) throw new Error(`Version source ${url} returned ${response.status}`)\n return response.json()\n } finally {\n clearTimeout(timeoutId)\n }\n}\n\nasync function resolveProductVersion(\n state: VersionState,\n fallback: string,\n sourceUrl: string,\n parse: (payload: unknown) => string | null,\n fetchImpl: FetchLike,\n): Promise<string> {\n const now = Date.now()\n if (state.cache && now - state.cache.fetchedAt < VERSION_CACHE_TTL_MS) {\n return pickNewestVersion(state.cache.version, fallback) ?? fallback\n }\n if (state.inFlight) return state.inFlight\n\n state.inFlight = (async () => {\n let resolved: string | null = null\n try {\n resolved = parse(await fetchJsonWithTimeout(fetchImpl, sourceUrl))\n } catch {\n resolved = null\n }\n const version = pickNewestVersion(resolved, state.cache?.version, fallback) ?? fallback\n if (resolved) state.cache = { version, fetchedAt: Date.now() }\n return version\n })()\n\n try {\n return await state.inFlight\n } finally {\n state.inFlight = null\n }\n}\n\n/** Resolve the newest known Antigravity version from the IDE feed. */\nexport function resolveAntigravityIdeVersion(fetchImpl: FetchLike = fetch): Promise<string> {\n return resolveProductVersion(ideState, AGY_VERSION_FALLBACK, IDE_RELEASE_FEED_URL, parseIdeReleaseFeed, fetchImpl)\n}\n\n/** Resolve the newest known Antigravity version from the CLI releases. */\nexport function resolveAntigravityCliVersion(fetchImpl: FetchLike = fetch): Promise<string> {\n return resolveProductVersion(cliState, AGY_VERSION_FALLBACK, CLI_RELEASE_URL, parseCliRelease, fetchImpl)\n}\n\n/** Best available version: newest of both sources, cached 6h. */\nexport async function resolveAntigravityVersion(fetchImpl: FetchLike = fetch): Promise<string> {\n const [ide, cli] = await Promise.all([resolveAntigravityIdeVersion(fetchImpl), resolveAntigravityCliVersion(fetchImpl)])\n return pickNewestVersion(ide, cli) ?? AGY_VERSION_FALLBACK\n}\n\n/**\n * Bounded resolve for fingerprint generation: never block the failure path on\n * cold version feeds. Resolves undefined on timeout/error so callers fall\n * back to the pinned version pool; the abandoned fetch keeps running and\n * populates the 6h cache for later calls.\n */\nexport async function resolveAntigravityVersionBounded(timeoutMs = 750): Promise<string | undefined> {\n let timer: NodeJS.Timeout | undefined\n try {\n return await Promise.race([\n resolveAntigravityVersion().catch(() => undefined),\n new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), timeoutMs)\n }),\n ])\n } finally {\n clearTimeout(timer)\n }\n}\n\n/** Synchronously peek at a fresh cached version (no network). */\nexport function peekCachedAntigravityVersion(): string | undefined {\n const now = Date.now()\n for (const state of [ideState, cliState]) {\n if (state.cache && now - state.cache.fetchedAt < VERSION_CACHE_TTL_MS) {\n return state.cache.version\n }\n }\n return undefined\n}\n\nconst ideState: VersionState = { inFlight: null }\nconst cliState: VersionState = { inFlight: null }\n","/** Packed refresh-string helpers and access-token expiry math. */\n\nimport type { OAuthAuthDetails, RefreshParts } from '../types.ts'\n\nconst ACCESS_TOKEN_EXPIRY_BUFFER_MS = 60 * 1000\n\n/** Split the packed refresh string into its constituent refresh token and project ids. */\nexport function parseRefreshParts(refresh: string): RefreshParts {\n const [refreshToken = '', projectId = '', managedProjectId = ''] = (refresh ?? '').split('|')\n return {\n refreshToken: refreshToken || undefined,\n projectId: projectId || undefined,\n managedProjectId: managedProjectId || undefined,\n }\n}\n\n/** Serialize refresh token parts into the stored string format. */\nexport function formatRefreshParts(parts: RefreshParts): string {\n const projectSegment = parts.projectId ?? ''\n const base = `${parts.refreshToken ?? ''}|${projectSegment}`\n return parts.managedProjectId ? `${base}|${parts.managedProjectId}` : base\n}\n\n/** Whether the access token is expired or missing, with a buffer for clock skew. */\nexport function accessTokenExpired(auth: OAuthAuthDetails): boolean {\n if (!auth.access || typeof auth.expires !== 'number') {\n return true\n }\n return auth.expires <= Date.now() + ACCESS_TOKEN_EXPIRY_BUFFER_MS\n}\n\n/** Absolute expiry timestamp from a duration; malformed durations expire immediately. */\nexport function calculateTokenExpiry(requestTimeMs: number, expiresInSeconds: unknown): number {\n const seconds = typeof expiresInSeconds === 'number' ? expiresInSeconds : 3600\n if (Number.isNaN(seconds) || seconds <= 0) {\n return requestTimeMs\n }\n return requestTimeMs + seconds * 1000\n}\n","/**\n * Refresh an agy access token, handling Google's varied error payload shapes and\n * marking revocation (`invalid_grant`) distinctly so callers can drop the account.\n */\n\nimport type { OAuthAuthDetails } from '../types.ts'\nimport { calculateTokenExpiry, formatRefreshParts, parseRefreshParts } from './auth.ts'\nimport { AGY_CLIENT_ID, AGY_CLIENT_SECRET, OAUTH_TOKEN_URL } from './constants.ts'\n\ninterface OAuthErrorPayload {\n error?:\n | string\n | {\n code?: string\n status?: string\n message?: string\n }\n error_description?: string\n}\n\nexport class AgyTokenRefreshError extends Error {\n code?: string\n description?: string\n status: number\n statusText: string\n\n constructor(options: {\n message: string\n code?: string\n description?: string\n status: number\n statusText: string\n }) {\n super(options.message)\n this.name = 'AgyTokenRefreshError'\n this.code = options.code\n this.description = options.description\n this.status = options.status\n this.statusText = options.statusText\n }\n}\n\n/** Parse Google token-endpoint error payloads, tolerating varied shapes. */\nexport function parseOAuthErrorPayload(text: string | undefined): { code?: string; description?: string } {\n if (!text) return {}\n\n try {\n const payload = JSON.parse(text) as OAuthErrorPayload\n if (!payload || typeof payload !== 'object') {\n return { description: text }\n }\n\n let code: string | undefined\n if (typeof payload.error === 'string') {\n code = payload.error\n } else if (payload.error && typeof payload.error === 'object') {\n code = payload.error.status ?? payload.error.code\n if (!payload.error_description && payload.error.message) {\n return { code, description: payload.error.message }\n }\n }\n\n const description = payload.error_description\n if (description) return { code, description }\n\n if (payload.error && typeof payload.error === 'object' && payload.error.message) {\n return { code, description: payload.error.message }\n }\n\n return { code }\n } catch {\n return { description: text }\n }\n}\n\nexport type RefreshResult =\n | { type: 'success'; auth: OAuthAuthDetails }\n | { type: 'revoked' }\n | { type: 'failed'; error: AgyTokenRefreshError }\n\n/**\n * Refresh the access token for an account. `revoked` means Google rejected the\n * refresh token (`invalid_grant`) — the account must be re-authenticated.\n */\nexport async function refreshAccessToken(auth: OAuthAuthDetails): Promise<RefreshResult> {\n const parts = parseRefreshParts(auth.refresh)\n if (!parts.refreshToken) {\n return { type: 'failed', error: new AgyTokenRefreshError({\n message: 'Missing refresh token',\n status: 400,\n statusText: 'Bad Request',\n }) }\n }\n\n try {\n const startTime = Date.now()\n const response = await fetch(OAUTH_TOKEN_URL, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: parts.refreshToken,\n client_id: AGY_CLIENT_ID,\n client_secret: AGY_CLIENT_SECRET,\n }),\n })\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => undefined)\n const { code, description } = parseOAuthErrorPayload(errorText)\n const details = [code, description ?? errorText].filter(Boolean).join(': ')\n const baseMessage = `Agy token refresh failed (${response.status} ${response.statusText})`\n const message = details ? `${baseMessage} - ${details}` : baseMessage\n\n if (code === 'invalid_grant') {\n return { type: 'revoked' }\n }\n\n return {\n type: 'failed',\n error: new AgyTokenRefreshError({\n message,\n code,\n description: description ?? errorText,\n status: response.status,\n statusText: response.statusText,\n }),\n }\n }\n\n const payload = (await response.json()) as {\n access_token: string\n expires_in?: number\n refresh_token?: string\n }\n\n const refreshedParts = {\n refreshToken: payload.refresh_token ?? parts.refreshToken,\n projectId: parts.projectId,\n managedProjectId: parts.managedProjectId,\n }\n\n return {\n type: 'success',\n auth: {\n access: payload.access_token,\n expires: calculateTokenExpiry(startTime, payload.expires_in),\n refresh: formatRefreshParts(refreshedParts),\n },\n }\n } catch (error) {\n if (error instanceof AgyTokenRefreshError) throw error\n return {\n type: 'failed',\n error: new AgyTokenRefreshError({\n message: error instanceof Error ? error.message : 'Unknown refresh error',\n status: 0,\n statusText: '',\n }),\n }\n }\n}\n","/**\n * Master-key management and AES-256-GCM secret codec for the account store.\n *\n * The master key lives in the DSH credentials document (`~/.dsh/.credentials.yaml`,\n * 0600) under `AGY_MASTER_KEY` so both the in-harness plugin (via\n * `ctx.credentials`) and the standalone `dsh-agy` CLI (direct file read) can\n * encrypt and decrypt the same account store.\n */\n\nimport { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'\nimport { readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { existsSync, mkdirSync, statSync } from 'node:fs'\n\nexport const MASTER_KEY_REF = 'AGY_MASTER_KEY'\n\n/** Encrypt/decrypt secrets at rest. */\nexport interface SecretCodec {\n encrypt(plaintext: string): string\n decrypt(payload: string): string\n}\n\nconst ENC_PREFIX = 'enc:v1:'\n\n/** AES-256-GCM codec; ciphertext format `enc:v1:<iv-b64>:<tag-b64>:<data-b64>`. */\nexport function createAesGcmCodec(key: Buffer): SecretCodec {\n if (key.length !== 32) {\n throw new Error(`createAesGcmCodec: master key must be 32 bytes, got ${key.length}`)\n }\n return {\n encrypt(plaintext: string): string {\n const iv = randomBytes(12)\n const cipher = createCipheriv('aes-256-gcm', key, iv)\n const data = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()])\n const tag = cipher.getAuthTag()\n return `${ENC_PREFIX}${iv.toString('base64url')}:${tag.toString('base64url')}:${data.toString('base64url')}`\n },\n decrypt(payload: string): string {\n if (!payload.startsWith(ENC_PREFIX)) {\n throw new Error('decrypt: payload is not in encrypted format')\n }\n const [, , ivB64 = '', tagB64 = '', dataB64 = ''] = payload.split(':')\n const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(ivB64, 'base64url'))\n decipher.setAuthTag(Buffer.from(tagB64, 'base64url'))\n const plain = Buffer.concat([decipher.update(Buffer.from(dataB64, 'base64url')), decipher.final()])\n return plain.toString('utf8')\n },\n }\n}\n\n/** Derive a 32-byte key from an arbitrary master-key string (SHA-256). */\nexport function deriveKey(masterKey: string): Buffer {\n return createHash('sha256').update(masterKey, 'utf8').digest()\n}\n\n/** Default DSH home (`~/.dsh`), honoring `$DSH_HOME`. */\nexport function resolveDshHome(): string {\n return process.env.DSH_HOME ? resolve(process.env.DSH_HOME) : join(homedir(), '.dsh')\n}\n\nfunction homedir(): string {\n return process.env.HOME ?? process.env.USERPROFILE ?? '.'\n}\n\n/**\n * Minimal reader for the DSH credentials document: a flat YAML mapping of\n * `KEY: \"value\"` / `KEY: value` lines. Values are unquoted with JSON-style\n * escaping for double-quoted scalars; anything more complex fails loudly.\n */\nexport function readCredentialsDocument(file: string): Map<string, string> {\n if (!existsSync(file)) return new Map()\n const entries = new Map<string, string>()\n const text = readFileSync(file, 'utf8')\n for (const line of text.split(/\\r?\\n/)) {\n const trimmed = line.trim()\n if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('---')) continue\n const match = /^([A-Za-z_][A-Za-z0-9_]*):\\s*(.*)$/.exec(trimmed)\n if (!match) continue\n const [, key = '', rawValue = ''] = match\n let value: string\n if (rawValue.startsWith('\"')) {\n try {\n value = JSON.parse(rawValue) as string\n } catch {\n throw new Error(`readCredentialsDocument: invalid quoted value for \"${key}\" in ${file}`)\n }\n } else if (rawValue.startsWith(\"'\")) {\n if (!rawValue.endsWith(\"'\") || rawValue.length < 2) {\n throw new Error(`readCredentialsDocument: unterminated single-quoted value for \"${key}\" in ${file}`)\n }\n value = rawValue.slice(1, -1).replace(/''/g, \"'\")\n } else {\n value = rawValue\n }\n if (value.length === 0) continue\n entries.set(key, value)\n }\n return entries\n}\n\n/**\n * POSIX owner-only enforcement. Windows mode bits never report 0600 (and\n * chmod is a no-op there), so the check is skipped on win32; the encrypted\n * account file and credentials document remain the only defense-in-depth\n * layer on that platform.\n */\nexport function assertOwnerOnly(file: string): void {\n if (process.platform === 'win32') return\n const mode = statSync(file).mode & 0o777\n if (mode !== 0o600) {\n throw new Error(\n `dsh-agy: ${file} is readable beyond its owner (mode ${mode.toString(8)}); ` +\n 'run \"chmod 600\" before starting again',\n )\n }\n}\n\n/**\n * Load the master key from the DSH credentials document. Returns undefined when\n * the document or the reference is absent.\n */\nexport function loadMasterKey(dshHome: string): string | undefined {\n const file = join(dshHome, '.credentials.yaml')\n if (!existsSync(file)) return undefined\n assertOwnerOnly(file)\n return readCredentialsDocument(file).get(MASTER_KEY_REF)\n}\n\n/**\n * Generate and persist a fresh master key (0600) in the DSH credentials document.\n *\n * Append-only + atomic rename: the DSH credentials service owns this file and\n * preserves comments and the formatting of untouched entries (and may hold\n * YAML constructs this minimal reader cannot parse). Rewriting the whole file\n * from our parsed view would silently drop those; appending keeps them.\n */\nexport function persistMasterKey(dshHome: string, masterKey: string): void {\n const file = join(dshHome, '.credentials.yaml')\n mkdirSync(dirname(file), { recursive: true })\n const existingText = existsSync(file) ? readFileSync(file, 'utf8') : ''\n if (existingText.length > 0 && readCredentialsDocument(file).has(MASTER_KEY_REF)) {\n throw new Error(`persistMasterKey: ${MASTER_KEY_REF} already exists in ${file}`)\n }\n const entry = `${MASTER_KEY_REF}: ${JSON.stringify(masterKey)}`\n const next = existingText.length > 0 && !existingText.endsWith('\\n')\n ? `${existingText}\\n${entry}\\n`\n : `${existingText}${entry}\\n`\n const tmp = `${file}.tmp-masterkey`\n writeFileSync(tmp, next, { mode: 0o600 })\n renameSync(tmp, file)\n}\n\n/**\n * Resolve (load or create) the master key for a dsh home, then build the codec.\n * Creating a key writes the credentials document; read-only setups should call\n * {@link loadMasterKey} first and surface a friendly error instead.\n */\nexport function resolveMasterKeyCodec(dshHome: string): { codec: SecretCodec; created: boolean } {\n let masterKey = loadMasterKey(dshHome)\n let created = false\n if (!masterKey) {\n masterKey = randomBytes(32).toString('hex')\n persistMasterKey(dshHome, masterKey)\n created = true\n }\n return { codec: createAesGcmCodec(deriveKey(masterKey)), created }\n}\n","/**\n * Account pool store: an interface plus a JSON-file implementation\n * (proper-lockfile cross-process mutual exclusion, 0600 permissions, versioned\n * migrations, AES-encrypted refresh tokens) and an in-memory fake for tests.\n */\n\nimport { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport lockfile from 'proper-lockfile'\nimport type {\n AccountStorage,\n AccountStorageV1,\n AccountStorageV2,\n AccountStorageV3,\n AccountStorageV4,\n ManagedAccount,\n} from '../types.ts'\nimport { assertOwnerOnly } from './keyring.ts'\nimport type { SecretCodec } from './keyring.ts'\n\nexport const CURRENT_STORAGE_VERSION = 4\nconst ENC_PREFIX = 'enc:v1:'\n\n/** Cross-process file lock adapter (proper-lockfile behind a small seam for tests). */\nexport interface FileLock {\n withLock<T>(file: string, fn: () => Promise<T>): Promise<T>\n}\n\nexport const properFileLock: FileLock = {\n async withLock<T>(file: string, fn: () => Promise<T>): Promise<T> {\n const release = await lockfile.lock(file, {\n stale: 30_000,\n update: 10_000,\n retries: { retries: 10, factor: 1.5, minTimeout: 50, maxTimeout: 2_000 },\n })\n try {\n return await fn()\n } finally {\n await release()\n }\n },\n}\n\n/** No-op lock for tests / single-process use. */\nexport const noopFileLock: FileLock = {\n async withLock<T>(_file: string, fn: () => Promise<T>): Promise<T> {\n return fn()\n },\n}\n\nexport interface AccountStore {\n /** Load the current (migrated) storage document. */\n load(): Promise<AccountStorageV4>\n /** Persist the full document (encrypting secrets). */\n save(storage: AccountStorageV4): Promise<void>\n /** Load-mutate-save atomically under the file lock; returns the mutation result. */\n mutate<T>(fn: (storage: AccountStorageV4) => T | Promise<T>): Promise<T>\n}\n\nexport interface JsonAccountStoreOptions {\n file: string\n codec: SecretCodec\n lock?: FileLock\n}\n\nfunction isEncrypted(value: string): boolean {\n return value.startsWith(ENC_PREFIX)\n}\n\n/** Decrypt one account's refresh field when encrypted; plaintext passes through (legacy). */\nfunction decryptAccount(account: ManagedAccount, codec: SecretCodec): ManagedAccount {\n if (isEncrypted(account.refresh)) {\n return { ...account, refresh: codec.decrypt(account.refresh) }\n }\n return account\n}\n\n/** Encrypt one account's refresh field (plaintext stays plaintext if no codec change). */\nfunction encryptAccount(account: ManagedAccount, codec: SecretCodec): ManagedAccount {\n if (!isEncrypted(account.refresh)) {\n return { ...account, refresh: codec.encrypt(account.refresh) }\n }\n return account\n}\n\nexport function decryptStorage(storage: AccountStorageV4, codec: SecretCodec): AccountStorageV4 {\n return { ...storage, accounts: storage.accounts.map((a) => decryptAccount(a, codec)) }\n}\n\nexport function encryptStorage(storage: AccountStorageV4, codec: SecretCodec): AccountStorageV4 {\n return { ...storage, accounts: storage.accounts.map((a) => encryptAccount(a, codec)) }\n}\n\n// ──── Migrations ────────────────────────────────────────────────────────────\n\nexport function migrateV1ToV2(v1: AccountStorageV1): AccountStorageV2 {\n return {\n version: 2,\n accounts: v1.accounts.map((acc) => ({\n email: acc.email,\n refreshToken: acc.refreshToken,\n projectId: acc.projectId,\n managedProjectId: acc.managedProjectId,\n addedAt: acc.addedAt,\n lastUsed: acc.lastUsed,\n lastSwitchReason: acc.lastSwitchReason,\n rateLimitResetTimes: acc.isRateLimited && acc.rateLimitResetTime\n ? { default: acc.rateLimitResetTime }\n : undefined,\n })),\n activeIndex: v1.activeIndex,\n }\n}\n\nexport function migrateV2ToV3(v2: AccountStorageV2): AccountStorageV3 {\n return {\n version: 3,\n accounts: v2.accounts.map((acc) => ({\n email: acc.email,\n refresh: `${acc.refreshToken}|${acc.projectId ?? ''}|${acc.managedProjectId ?? ''}`,\n projectId: acc.projectId,\n managedProjectId: acc.managedProjectId,\n addedAt: acc.addedAt,\n lastUsed: acc.lastUsed,\n enabled: true,\n lastSwitchReason: acc.lastSwitchReason,\n rateLimitResetTimes: acc.rateLimitResetTimes,\n })),\n activeIndex: v2.activeIndex,\n }\n}\n\nexport function migrateV3ToV4(v3: AccountStorageV3): AccountStorageV4 {\n return { version: 4, accounts: v3.accounts, activeIndex: v3.activeIndex }\n}\n\nexport function migrateStorage(raw: AccountStorage): AccountStorageV4 {\n switch (raw.version) {\n case 1:\n return migrateStorage(migrateV1ToV2(raw))\n case 2:\n return migrateStorage(migrateV2ToV3(raw))\n case 3:\n return migrateStorage(migrateV3ToV4(raw))\n case 4:\n return raw\n default:\n throw new Error(`migrateStorage: unsupported storage version ${(raw as { version: number }).version}`)\n }\n}\n\n// ──── JSON file implementation ──────────────────────────────────────────────\n\nexport class JsonAccountStore implements AccountStore {\n private readonly file: string\n private readonly codec: SecretCodec\n private readonly lock: FileLock\n\n constructor(options: JsonAccountStoreOptions) {\n this.file = options.file\n this.codec = options.codec\n this.lock = options.lock ?? properFileLock\n }\n\n /**\n * Ensure the store document exists before locking: proper-lockfile resolves\n * the target's realpath and fails with ENOENT when it is absent.\n */\n private ensureFile(): void {\n if (existsSync(this.file)) return\n mkdirSync(dirname(this.file), { recursive: true })\n const tmp = `${this.file}.tmp-init`\n writeFileSync(tmp, JSON.stringify({ version: CURRENT_STORAGE_VERSION, accounts: [], activeIndex: 0 }) + '\\n', { mode: 0o600 })\n renameSync(tmp, this.file)\n }\n\n async load(): Promise<AccountStorageV4> {\n let text: string\n try {\n text = readFileSync(this.file, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return { version: CURRENT_STORAGE_VERSION, accounts: [], activeIndex: 0 }\n }\n throw error\n }\n assertOwnerOnly(this.file)\n const raw = JSON.parse(text) as AccountStorage\n const migrated = migrateStorage(raw)\n return decryptStorage(migrated, this.codec)\n }\n\n async save(storage: AccountStorageV4): Promise<void> {\n const encrypted = encryptStorage(storage, this.codec)\n mkdirSync(dirname(this.file), { recursive: true })\n const tmp = `${this.file}.tmp`\n writeFileSync(tmp, JSON.stringify(encrypted, null, 2) + '\\n', { mode: 0o600 })\n renameSync(tmp, this.file)\n }\n\n async mutate<T>(fn: (storage: AccountStorageV4) => T | Promise<T>): Promise<T> {\n this.ensureFile()\n return this.lock.withLock(this.file, async () => {\n const storage = await this.load()\n const result = await fn(storage)\n await this.save(storage)\n return result\n })\n }\n}\n\n// ──── In-memory fake (the second adapter that justifies the seam) ───────────\n\nexport class InMemoryAccountStore implements AccountStore {\n private storage: AccountStorageV4\n\n constructor(initial: AccountStorageV4 = { version: CURRENT_STORAGE_VERSION, accounts: [], activeIndex: 0 }) {\n this.storage = initial\n }\n\n async load(): Promise<AccountStorageV4> {\n return structuredClone(this.storage)\n }\n\n async save(storage: AccountStorageV4): Promise<void> {\n this.storage = structuredClone(storage)\n }\n\n async mutate<T>(fn: (storage: AccountStorageV4) => T | Promise<T>): Promise<T> {\n const storage = structuredClone(this.storage)\n const result = await fn(storage)\n this.storage = storage\n return result\n }\n}\n\n// ──── Pool helpers ──────────────────────────────────────────────────────────\n\n/** Keep one account per email (case-insensitive), first occurrence wins. */\nexport function deduplicateAccountsByEmail(accounts: ManagedAccount[]): ManagedAccount[] {\n const seen = new Set<string>()\n const result: ManagedAccount[] = []\n for (const account of accounts) {\n const key = account.email?.toLowerCase()\n if (key && seen.has(key)) continue\n if (key) seen.add(key)\n result.push(account)\n }\n return result\n}\n\n/** Pick the active account, falling back to the first enabled one. */\nexport function resolveActiveAccount(\n storage: AccountStorageV4,\n): { account: ManagedAccount; index: number } | undefined {\n const accounts = storage.accounts\n if (accounts.length === 0) return undefined\n const active = accounts[storage.activeIndex]\n if (active && active.enabled !== false) return { account: active, index: storage.activeIndex }\n const fallbackIndex = accounts.findIndex((a) => a.enabled !== false)\n if (fallbackIndex === -1) return undefined\n return { account: accounts[fallbackIndex]!, index: fallbackIndex }\n}\n","/**\n * Rotation state machine: decides retry / cool / rotate / revoke for one failed\n * attempt, with tiered backoff and soft-quota pre-checks.\n */\n\nimport type { CachedQuota, FailureKind, ManagedAccount, RotationAction } from '../types.ts'\nimport type { RateLimitCategory } from './classify.ts'\n\nexport const BACKOFF_TIERS_MS = [5_000, 10_000, 20_000, 30_000, 60_000] as const\n\n/** Below this remaining fraction the account is treated as soft-quota-exhausted. */\nexport const SOFT_QUOTA_THRESHOLD = 0.15\n\nexport const MAX_ACCOUNTS = 10\n\nfunction backoffFor(consecutiveFailures: number, maxJitterMs = 1_000): number {\n const index = Math.min(Math.max(consecutiveFailures, 0), BACKOFF_TIERS_MS.length - 1)\n const base = BACKOFF_TIERS_MS[index] ?? BACKOFF_TIERS_MS[BACKOFF_TIERS_MS.length - 1]!\n return base + Math.floor(Math.random() * maxJitterMs)\n}\n\n/** Whether the account's cached quota for a model is below the soft threshold. */\nexport function isOverSoftQuota(\n account: ManagedAccount,\n model: string | undefined,\n now = Date.now(),\n): boolean {\n if (!model) return false\n const cached = account.cachedQuota?.[model]\n if (!cached || typeof cached.remainingFraction !== 'number') return false\n if (cached.resetTime && Date.parse(cached.resetTime) <= now) return false\n return cached.remainingFraction < SOFT_QUOTA_THRESHOLD\n}\n\n/** Whether the account is currently in a cooldown window. */\nexport function isCoolingDown(account: ManagedAccount, now = Date.now()): boolean {\n return (account.coolingDownUntil ?? 0) > now\n}\n\n/** Whether any model rate limit on the account is still active. */\nexport function isRateLimited(account: ManagedAccount, now = Date.now()): boolean {\n const times = account.rateLimitResetTimes ?? {}\n return Object.values(times).some((reset) => typeof reset === 'number' && reset > now)\n}\n\n/** Record a rate-limit reset for one model key. */\nexport function recordRateLimit(account: ManagedAccount, modelKey: string, resetAtMs: number): void {\n account.rateLimitResetTimes = { ...(account.rateLimitResetTimes ?? {}), [modelKey]: resetAtMs }\n}\n\n/** Clear expired rate limits and cooldowns in place. */\nexport function clearExpiredState(account: ManagedAccount, now = Date.now()): void {\n if (account.rateLimitResetTimes) {\n const fresh = Object.fromEntries(\n Object.entries(account.rateLimitResetTimes).filter(([, reset]) => reset > now),\n )\n account.rateLimitResetTimes = Object.keys(fresh).length > 0 ? fresh : undefined\n }\n if (account.coolingDownUntil && account.coolingDownUntil <= now) {\n account.coolingDownUntil = undefined\n account.cooldownReason = undefined\n }\n}\n\n/** 24h cooldown for a fully exhausted daily quota (single-account: stop hitting the wall). */\nexport const FULL_QUOTA_COOLDOWN_MS = 24 * 60 * 60 * 1000\n/** 5min cooldown for per-minute rate limits. */\nexport const RATE_LIMIT_COOLDOWN_MS = 5 * 60 * 1000\n\n/**\n * Decide what to do after one failed attempt.\n * @param kind - classified failure kind.\n * @param category - 429 sub-category when kind is rate-limit.\n * @param account - the account that failed (mutated with cooldown/rate-limit state).\n * @param consecutiveFailures - consecutive failures on this account.\n * @param retryAfterMs - server-provided retry delay when present.\n */\nexport function decideRotation(\n kind: FailureKind,\n account: ManagedAccount,\n consecutiveFailures: number,\n retryAfterMs?: number,\n category: RateLimitCategory = 'unknown',\n): RotationAction {\n const now = Date.now()\n const backoffMs = backoffFor(consecutiveFailures)\n\n switch (kind) {\n case 'rate-limit': {\n if (category === 'soft_rate_limit') {\n // Transient burst: retry the same account almost immediately.\n return { action: 'retry', backoffMs: Math.min(retryAfterMs ?? backoffMs, 3000) }\n }\n if (category === 'quota_exhausted') {\n // Daily/plan quota gone: long cooldown; a single account just waits.\n account.coolingDownUntil = now + FULL_QUOTA_COOLDOWN_MS\n account.cooldownReason = undefined\n return { action: 'cool', backoffMs: FULL_QUOTA_COOLDOWN_MS }\n }\n const cooldownMs = retryAfterMs ?? RATE_LIMIT_COOLDOWN_MS\n account.coolingDownUntil = now + cooldownMs\n account.cooldownReason = undefined // per-model resets live in rateLimitResetTimes\n return { action: 'rotate', backoffMs }\n }\n case 'auth-failure': {\n // Terminal: account credentials are dead; never auto-recover.\n account.verificationRequired = true\n account.verificationRequiredAt = now\n account.verificationRequiredReason = 'auth-failure'\n account.enabled = false\n return { action: 'revoke' }\n }\n case 'network-error': {\n account.coolingDownUntil = now + backoffMs\n account.cooldownReason = 'network-error'\n return { action: 'rotate', backoffMs }\n }\n case 'project-error': {\n account.coolingDownUntil = now + backoffMs\n account.cooldownReason = 'project-error'\n return { action: 'cool', backoffMs }\n }\n case 'request-error': {\n // Request-construction error (e.g. generic 400): permanent, retrying\n // resends the same broken payload. No cooldown, no rotation, no revoke —\n // the adapter surfaces it as a terminal UPSTREAM error.\n return { action: 'noop' }\n }\n case 'transient': {\n return { action: 'retry', backoffMs }\n }\n }\n}\n\n/**\n * Pick the next account index for rotation (round-robin across enabled,\n * non-cooling accounts; falls back to the active one when all are cooling).\n */\nexport function pickNextAccountIndex(\n accounts: ManagedAccount[],\n currentIndex: number,\n now = Date.now(),\n): number {\n if (accounts.length <= 1) return currentIndex\n const enabled = accounts.map((a, i) => ({ account: a, index: i }))\n .filter(({ account, index }) => index !== currentIndex && account.enabled !== false && !isCoolingDown(account, now))\n if (enabled.length === 0) return currentIndex\n // Round-robin: first candidate after current index, else first eligible.\n const after = enabled.find((e) => e.index > currentIndex)\n return (after ?? enabled[0]!)!.index\n}\n\n/** Build the soft-quota cache TTL: short when low, long when healthy. */\nexport function computeSoftQuotaCacheTtlMs(remainingFraction: number | undefined, now = Date.now()): number {\n if (typeof remainingFraction !== 'number') return 10 * 60 * 1000\n if (remainingFraction < SOFT_QUOTA_THRESHOLD) return 60 * 1000\n if (remainingFraction < 0.5) return 5 * 60 * 1000\n return 15 * 60 * 1000\n}\n\nexport type { CachedQuota }\n","","/**\n * Device fingerprint generation for rate-limit mitigation (two layers):\n *\n * 1. Per-request randomized headers — platform/arch/SDK-client pools.\n * 2. Per-account persistent fingerprint — deviceId/sessionToken/UA snapshot\n * with bounded history (≤5 versions, restorable), regenerated when an\n * account's capacity looks exhausted.\n *\n * All tunable pools live in fingerprint-data.json so they can be updated\n * without a code release (the reference implementation stopped at an old\n * version string once archived — that staleness is the detectable signal).\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { randomBytes, randomUUID } from 'node:crypto'\nimport type { ClientMetadata, Fingerprint, FingerprintVersion } from '../types.ts'\nimport fingerprintData from './fingerprint-data.json'\n\nexport interface FingerprintData {\n versionPool: string[]\n platforms: string[]\n architectures: string[]\n osVersions: Record<string, string[]>\n sdkClients: string[]\n ideTypes: string[]\n pluginTypes: string[]\n}\n\nexport const DEFAULT_FINGERPRINT_DATA = fingerprintData as FingerprintData\n\nexport const MAX_FINGERPRINT_HISTORY = 5\n\nconst USER_OVERRIDE_FILE = 'agy-fingerprint-data.json'\n\n/**\n * Effective fingerprint data: a user override at `$DSH_HOME/agy-fingerprint-data.json`\n * wins when present and parseable (hot-updatable without a code release — the\n * bundled copy is compiled in), otherwise the bundled defaults.\n */\nlet cachedData: FingerprintData | null = null\nexport function getFingerprintData(): FingerprintData {\n if (cachedData) return cachedData\n try {\n const dshHome = process.env.DSH_HOME ? process.env.DSH_HOME : join(process.env.HOME ?? '.', '.dsh')\n const overrideFile = join(dshHome, USER_OVERRIDE_FILE)\n if (existsSync(overrideFile)) {\n const parsed = JSON.parse(readFileSync(overrideFile, 'utf8')) as FingerprintData\n if (parsed && Array.isArray(parsed.versionPool) && parsed.versionPool.length > 0) {\n cachedData = parsed\n return cachedData\n }\n }\n } catch {\n // unreadable override — fall through to bundled defaults\n }\n cachedData = DEFAULT_FINGERPRINT_DATA\n return cachedData\n}\n\nfunction randomFrom<T>(arr: readonly T[]): T {\n return arr[Math.floor(Math.random() * arr.length)]!\n}\n\n/** Generate a randomized device fingerprint representing one apparent device. */\nexport function generateFingerprint(\n data: FingerprintData = getFingerprintData(),\n version = randomFrom(data.versionPool),\n): Fingerprint {\n const platform = randomFrom(data.platforms)\n return {\n deviceId: randomUUID(),\n sessionToken: randomBytes(16).toString('hex'),\n userAgent: `antigravity/${version} ${platform}`,\n apiClient: randomFrom(data.sdkClients),\n // Client-Metadata must only transmit ideType (backend enum validation\n // rejects freely-added platform/pluginType; AGENTS.md invariant).\n clientMetadata: {\n ideType: randomFrom(data.ideTypes),\n },\n createdAt: Date.now(),\n }\n}\n\n/** The only header composed from a fingerprint (the rest are per-request random). */\nexport function buildFingerprintHeaders(fingerprint: Fingerprint | null): { 'User-Agent'?: string } {\n if (!fingerprint) return {}\n return { 'User-Agent': fingerprint.userAgent }\n}\n\n/** Per-request randomized headers (platform + SDK client pools). */\nexport function getRandomizedHeaders(\n data: FingerprintData = getFingerprintData(),\n version = randomFrom(data.versionPool),\n): { 'User-Agent': string; 'X-Goog-Api-Client': string; 'Client-Metadata': string } {\n const platform = randomFrom(data.platforms)\n return {\n 'User-Agent': `antigravity/${version} ${platform}`,\n 'X-Goog-Api-Client': randomFrom(data.sdkClients),\n 'Client-Metadata': JSON.stringify({\n ideType: randomFrom(data.ideTypes),\n }),\n }\n}\n\n/** Rewrite the version inside a fingerprint UA; reports whether it changed. */\nexport function updateFingerprintVersion(fingerprint: Fingerprint, version: string): boolean {\n const pattern = /^(antigravity\\/)([\\d.]+)/\n const match = fingerprint.userAgent.match(pattern)\n if (!match || match[2] === version) return false\n fingerprint.userAgent = fingerprint.userAgent.replace(pattern, `$1${version}`)\n return true\n}\n\n/** Append a fingerprint to the account history (bounded), then use it as current. */\nexport function recordFingerprintVersion(\n history: FingerprintVersion[] | undefined,\n fingerprint: Fingerprint,\n reason: FingerprintVersion['reason'],\n): FingerprintVersion[] {\n const next = [...(history ?? []), { fingerprint, timestamp: Date.now(), reason }]\n return next.slice(-MAX_FINGERPRINT_HISTORY)\n}\n\n/**\n * Restore a stable prior identity: the oldest restorable fingerprint\n * (`initial`, else most recent `restored`). Returns `current` when the history\n * holds nothing restorable (e.g. the initial entry was evicted).\n */\nexport function restoreFingerprint(\n history: FingerprintVersion[] | undefined,\n current: Fingerprint | undefined,\n): Fingerprint | undefined {\n if (!history || history.length === 0) return current\n const initial = history.find((v) => v.reason === 'initial')\n const restored = [...history].reverse().find((v) => v.reason === 'restored')\n const restorable = initial ?? restored\n if (!restorable) return current\n return restorable.fingerprint\n}\n","/**\n * Account session manager: the shared runtime glue between the store, the\n * OAuth refresh path, rotation/fingerprint logic, and the adapter. Used by the\n * in-harness plugin shell, the CLI, and the web routes.\n */\n\nimport type { AgyAccountSession } from './adapter/adapter.ts'\nimport type { AccountStorageV4, FailureKind, ManagedAccount, OAuthAuthDetails } from './types.ts'\nimport { refreshAccessToken } from './oauth/refresh.ts'\nimport { accessTokenExpired, formatRefreshParts, parseRefreshParts } from './oauth/auth.ts'\nimport type { AccountStore } from './store/accounts.ts'\nimport { resolveActiveAccount } from './store/accounts.ts'\nimport {\n clearExpiredState,\n decideRotation,\n isCoolingDown,\n pickNextAccountIndex,\n} from './runtime/rotation.ts'\nimport {\n DEFAULT_FINGERPRINT_DATA,\n generateFingerprint,\n getRandomizedHeaders,\n recordFingerprintVersion,\n updateFingerprintVersion,\n} from './runtime/fingerprint.ts'\nimport { deriveAntigravitySessionId } from './runtime/identity.ts'\nimport { peekCachedAntigravityVersion, resolveAntigravityVersionBounded } from './runtime/version.ts'\nimport type { Fingerprint } from './types.ts'\n\nexport interface SessionManagerOptions {\n store: AccountStore\n /** Called after rotation changes the active index (for logging/UI). */\n onRotate?: (fromIndex: number, toIndex: number, reason: FailureKind) => void\n}\n\n/**\n * Session affinity window: reuse the last-used account for new requests within\n * this window (proxy for one DSH conversation, which exposes no id). After the\n * window or on failure the pool re-balances.\n */\nexport const SESSION_AFFINITY_WINDOW_MS = 10 * 60 * 1000\n\ninterface TokenCacheEntry {\n access: string\n expires: number\n}\n\n/**\n * Resolve the impersonation headers for one request from the account's\n * persistent fingerprint (stable identity), falling back to full per-request\n * randomization when the account has no fingerprint yet.\n */\nexport function impersonationHeadersFor(account: ManagedAccount): AgyAccountSession['impersonation'] {\n const fingerprint = account.fingerprint\n if (fingerprint) {\n return {\n 'User-Agent': fingerprint.userAgent,\n 'X-Goog-Api-Client': fingerprint.apiClient,\n 'Client-Metadata': JSON.stringify(fingerprint.clientMetadata),\n }\n }\n const randomized = getRandomizedHeaders(DEFAULT_FINGERPRINT_DATA)\n return {\n 'User-Agent': randomized['User-Agent'],\n 'X-Goog-Api-Client': randomized['X-Goog-Api-Client'],\n 'Client-Metadata': randomized['Client-Metadata'],\n }\n}\n\nexport class AgySessionManager {\n private readonly store: AccountStore\n private readonly onRotate: SessionManagerOptions['onRotate']\n private readonly tokenCache = new Map<string, TokenCacheEntry>()\n /** In-flight refresh promises keyed by account: concurrent requests share one refresh. */\n private readonly refreshInFlight = new Map<string, Promise<OAuthAuthDetails | undefined>>()\n private readonly failureCounts = new Map<string, number>()\n /** Accounts whose request-time project discovery already failed (no retry per request). */\n private readonly projectRetryFailed = new Set<string>()\n\n /**\n * Session affinity (time-window approximation): DSH exposes no conversation\n * id, so instead of pinning per session we reuse the last-used account while\n * it is fresh. Keeps upstream prefix caching and sessionId continuity across\n * the turns of one conversation (OmniRoute pins by session for the same\n * reason). Cleared on rotate so a failure re-picks from activeIndex.\n */\n private lastUsed: { index: number; at: number } | null = null\n\n constructor(options: SessionManagerOptions) {\n this.store = options.store\n this.onRotate = options.onRotate\n }\n\n private accountKey(account: ManagedAccount): string {\n return account.email ?? `idx-${account.refresh}`\n }\n\n /** Resolve a usable access token for the account, refreshing when expired. */\n private async accessTokenFor(account: ManagedAccount): Promise<OAuthAuthDetails | undefined> {\n const key = this.accountKey(account)\n const cached = this.tokenCache.get(key)\n const now = Date.now()\n if (cached && !accessTokenExpired({ access: cached.access, expires: cached.expires, refresh: account.refresh })) {\n return { access: cached.access, expires: cached.expires, refresh: account.refresh }\n }\n\n const inFlight = this.refreshInFlight.get(key)\n if (inFlight) return inFlight\n\n const refreshing = (async (): Promise<OAuthAuthDetails | undefined> => {\n const result = await refreshAccessToken({ access: cached?.access ?? '', expires: cached?.expires ?? 0, refresh: account.refresh })\n if (result.type === 'success') {\n this.tokenCache.set(key, { access: result.auth.access, expires: result.auth.expires })\n return result.auth\n }\n if (result.type === 'revoked') {\n // Account credentials are dead — mark it disabled; the next failure path\n // will surface the message.\n this.tokenCache.delete(key)\n return undefined\n }\n return undefined\n })()\n\n this.refreshInFlight.set(key, refreshing)\n try {\n return await refreshing\n } finally {\n this.refreshInFlight.delete(key)\n }\n }\n\n private async pickAccount(storage: AccountStorageV4): Promise<{ account: ManagedAccount; index: number } | undefined> {\n const now = Date.now()\n for (const account of storage.accounts) clearExpiredState(account, now)\n\n let resolved = resolveActiveAccount(storage)\n if (!resolved) return undefined\n // Session affinity (time-window approximation): reuse the last-used account\n // while it is fresh and healthy, so one conversation stays on one account\n // (upstream prefix cache + sessionId continuity). DSH exposes no\n // conversation id, so the window is the proxy; rotate clears it.\n if (this.lastUsed && now - this.lastUsed.at < SESSION_AFFINITY_WINDOW_MS) {\n const last = storage.accounts[this.lastUsed.index]\n if (last && last.enabled !== false && !isCoolingDown(last, now)) {\n resolved = { account: last, index: this.lastUsed.index }\n }\n }\n // Skip accounts that are cooling down (rate-limit cooldowns).\n if (isCoolingDown(resolved.account, now)) {\n const nextIndex = pickNextAccountIndex(storage.accounts, resolved.index, now)\n if (nextIndex !== resolved.index) {\n resolved = { account: storage.accounts[nextIndex]!, index: nextIndex }\n }\n }\n return resolved\n }\n\n /**\n * Adapter hook: resolve the active session (refresh if needed), healing a\n * missing projectId at request time — the OAuth-time loadCodeAssist may have\n * transiently failed even when the Google account owns a Cloud Code project\n * (mirrors OmniRoute's ensureAntigravityProjectAssigned + persistence).\n */\n async getSession(): Promise<AgyAccountSession | undefined> {\n const storage = await this.store.load()\n const picked = await this.pickAccount(storage)\n if (!picked) return undefined\n\n const auth = await this.accessTokenFor(picked.account)\n if (!auth) return undefined\n\n const key = this.accountKey(picked.account)\n if (!picked.account.projectId && !this.projectRetryFailed.has(key)) {\n try {\n const { loadCodeAssist } = await import('./oauth/exchange.ts')\n const { projectId } = await loadCodeAssist(auth.access)\n if (projectId) {\n await this.store.mutate((s) => {\n const account = s.accounts[picked.index]\n if (account) {\n account.projectId = projectId\n // Keep the packed refresh string in sync.\n const parts = parseRefreshParts(account.refresh)\n account.refresh = formatRefreshParts({\n refreshToken: parts.refreshToken,\n projectId,\n managedProjectId: parts.managedProjectId,\n })\n }\n })\n picked.account.projectId = projectId\n } else {\n this.projectRetryFailed.add(key)\n }\n } catch {\n this.projectRetryFailed.add(key)\n }\n }\n\n this.lastUsed = { index: picked.index, at: Date.now() }\n return {\n auth,\n account: picked.account,\n index: picked.index,\n impersonation: impersonationHeadersFor(picked.account),\n }\n }\n\n /** Adapter hook: apply rotation decisions and fingerprint regeneration. */\n async reportFailure(\n kind: FailureKind,\n session: AgyAccountSession,\n info?: { retryAfterMs?: number; status?: number; rateLimitCategory?: import('./runtime/classify.ts').RateLimitCategory },\n ): Promise<void> {\n const storage = await this.store.load()\n const account = storage.accounts[session.index]\n if (!account) return\n\n const key = this.accountKey(account)\n const consecutive = (this.failureCounts.get(key) ?? 0) + 1\n this.failureCounts.set(key, consecutive)\n\n const decision = decideRotation(kind, account, consecutive, info?.retryAfterMs, info?.rateLimitCategory)\n\n if (decision.action === 'revoke') {\n this.tokenCache.delete(key)\n this.failureCounts.delete(key)\n await this.store.save(storage)\n return\n }\n\n // Fingerprint lifecycle: create on first rate-limit, regenerate after\n // repeated failures (bounded by history inside recordFingerprintVersion).\n // UA versions come from the version resolver (bounded, cached 6h) so\n // fingerprints never pin a stale Antigravity client version.\n if (kind === 'rate-limit') {\n if (!account.fingerprint) {\n account.fingerprint = generateFingerprint(undefined, await resolveAntigravityVersionBounded())\n account.fingerprintHistory = recordFingerprintVersion(account.fingerprintHistory, account.fingerprint, 'initial')\n } else {\n // In-place UA refresh from the cached version (no network on this path).\n const cached = peekCachedAntigravityVersion()\n if (cached) updateFingerprintVersion(account.fingerprint, cached)\n if (consecutive >= 2) {\n const fresh = generateFingerprint(undefined, await resolveAntigravityVersionBounded())\n account.fingerprintHistory = recordFingerprintVersion(account.fingerprintHistory, fresh, 'regenerated')\n account.fingerprint = fresh\n }\n }\n }\n\n if (decision.action === 'rotate') {\n const nextIndex = pickNextAccountIndex(storage.accounts, session.index)\n if (nextIndex !== session.index) {\n storage.activeIndex = nextIndex\n this.onRotate?.(session.index, nextIndex, kind)\n }\n // The pinned account failed — drop the affinity so the pool re-balances.\n this.lastUsed = null\n }\n\n await this.store.save(storage)\n }\n\n /** Adapter hook: reset the failure counter after a clean completion. */\n async markSuccess(session: AgyAccountSession): Promise<void> {\n const account = session.account\n const key = this.accountKey(account)\n this.failureCounts.delete(key)\n }\n\n /**\n * Test call: one short streaming request against the live backend.\n * Returns the collected text or a structured error message.\n */\n async testCall(model: string, prompt = 'Reply with exactly: OK', maxTokens = 1024): Promise<{ ok: boolean; text?: string; error?: string }> {\n const session = await this.getSession()\n if (!session) return { ok: false, error: 'No agy account configured — run `dsh-agy login` first.' }\n try {\n const { toAgyRequestBody } = await import('./adapter/translate.ts')\n const { fetchAgyFirstOk } = await import('./oauth/constants.ts')\n const { parseAgySse } = await import('./adapter/parse.ts')\n const body = toAgyRequestBody(\n {\n provider: 'agy',\n model,\n messages: [{ id: 'test-1', role: 'user', content: [{ type: 'text', text: prompt }] }],\n maxTokens,\n } as never,\n { projectId: session.account.projectId, sessionId: deriveAntigravitySessionId(session.account.email) ?? undefined },\n )\n const headers = {\n authorization: `Bearer ${session.auth.access}`,\n 'content-type': 'application/json',\n accept: 'text/event-stream',\n ...session.impersonation,\n }\n const response = await fetchAgyFirstOk('/v1internal:streamGenerateContent?alt=sse', {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n })\n if (!response.ok) {\n const text = await response.text().catch(() => '')\n return { ok: false, error: `HTTP ${response.status}: ${text.slice(0, 300)}` }\n }\n if (!response.body) return { ok: false, error: 'no response body' }\n const text: string[] = []\n for await (const chunk of parseAgySse(response.body)) {\n if (chunk.type === 'text-delta') text.push(chunk.text)\n }\n return { ok: text.length > 0, text: text.join(''), error: text.length > 0 ? undefined : 'empty response' }\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error.message : String(error) }\n }\n }\n\n /** Export one account as a paste-credential blob (for migration to another host). */\n async exportBlob(index: number): Promise<{ blob?: string; error?: string }> {\n const storage = await this.store.load()\n const account = storage.accounts[index]\n if (!account) return { error: 'account not found' }\n const auth = await this.accessTokenFor(account)\n if (!auth) return { error: 'refresh failed (revoked?)' }\n const { encodeCredentialBlob } = await import('./oauth/blob.ts')\n const parts = parseRefreshParts(account.refresh)\n return {\n blob: encodeCredentialBlob('agy', {\n access_token: auth.access,\n refresh_token: parts.refreshToken,\n expires_in: Math.max(0, Math.round((auth.expires - Date.now()) / 1000)),\n }),\n }\n }\n\n /** CLI/web helper: verify an account's credentials (refresh + userinfo). */\n async verifyAccount(index: number): Promise<{ ok: boolean; email?: string; error?: string }> {\n const storage = await this.store.load()\n const account = storage.accounts[index]\n if (!account) return { ok: false, error: 'account not found' }\n const auth = await this.accessTokenFor(account)\n if (!auth) return { ok: false, error: 'refresh failed (revoked?)' }\n try {\n const response = await fetch('https://www.googleapis.com/oauth2/v1/userinfo?alt=json', {\n headers: { Authorization: `Bearer ${auth.access}` },\n })\n if (!response.ok) return { ok: false, error: `userinfo ${response.status}` }\n const info = (await response.json()) as { email?: string }\n // Credentials are live again — clear any auth-failure disable so the\n // account re-enters rotation without a manual re-import.\n await this.store.mutate((s) => {\n const target = s.accounts[index]\n if (target) {\n target.enabled = true\n target.verificationRequired = false\n target.verificationRequiredAt = undefined\n target.verificationRequiredReason = undefined\n target.verificationUrl = undefined\n }\n })\n return { ok: true, email: info.email }\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error.message : String(error) }\n }\n }\n}\n\nexport type { Fingerprint }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,MAAa,gBACX;AAEF,MAAa,oBAAoB;;;AAIjC,MAAa,aAAgC;CAC3C;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,sBAAsB;AACnC,MAAa,kBAAkB;AAC/B,MAAa,qBAAqB;;AAGlC,MAAa,2BAA2B;;;;;;;AAQxC,MAAa,qBAAqB;AAClC,MAAa,oBAAoB;AACjC,MAAa,6BAA6B;AAC1C,MAAa,wBAAwB;;AAGrC,MAAa,yBAA4C;CACvD;CACA;CACA;CACA;AACF;;AAGA,MAAa,6CAA6B,IAAI,IAAI,CAAC,KAAK,GAAG,CAAC;;;;;;;AAQ5D,eAAsB,gBACpB,SACA,MACA,YAA0B,OACP;CACnB,IAAI,cAA+B;CACnC,KAAK,MAAM,gBAA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,EAAE,SAAS;IAC1B,IAAI,QAAQ;KACV,OAAO,UAAU;KACjB,OAAO,uBAAuB;KAC9B,OAAO,yBAAyB,KAAA;KAChC,OAAO,6BAA6B,KAAA;KACpC,OAAO,kBAAkB,KAAA;IAC3B;GACF,CAAC;GACD,OAAO;IAAE,IAAI;IAAM,OAAO,KAAK;GAAM;EACvC,SAAS,OAAO;GACd,OAAO;IAAE,IAAI;IAAO,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GAAE;EACpF;CACF;AACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
2
|
-
import { g as generateAntigravityRequestId } from "./session-
|
|
2
|
+
import { g as generateAntigravityRequestId } from "./session-CyoQxOqv.mjs";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
3
4
|
const DEFAULT_TTL_MS = 36e5;
|
|
4
5
|
const MAX_ENTRIES = 2e3;
|
|
5
6
|
const store = /* @__PURE__ */ new Map();
|
|
@@ -38,6 +39,21 @@ function getThoughtSignature(toolCallId) {
|
|
|
38
39
|
}
|
|
39
40
|
//#endregion
|
|
40
41
|
//#region src/adapter/translate.ts
|
|
42
|
+
/**
|
|
43
|
+
* Translate a DSH GenerateOptions into the Antigravity wrapped request.
|
|
44
|
+
*
|
|
45
|
+
* Envelope shape follows the actively-maintained OmniRoute wire format
|
|
46
|
+
* (the archived opencode reference predates it): top-level `project`,
|
|
47
|
+
* `requestId`, `model`, `userAgent`, `requestType`, with the Gemini-style
|
|
48
|
+
* body under `request` (contents/systemInstruction/tools/generationConfig/
|
|
49
|
+
* sessionId). `toolConfig` VALIDATED is attached when tools are present, and
|
|
50
|
+
* Claude-path requests strip trailing model turns (Vertex rejects "assistant
|
|
51
|
+
* message prefill").
|
|
52
|
+
*
|
|
53
|
+
* Thinking blocks are carried as-is (Gemini `thought` parts); nothing is
|
|
54
|
+
* stripped or re-signed — that signature dance was an artifact of the
|
|
55
|
+
* reference plugin's interception architecture (see docs/ARCHITECTURE.md).
|
|
56
|
+
*/
|
|
41
57
|
var translate_exports = /* @__PURE__ */ __exportAll({
|
|
42
58
|
AGY_SCHEMA_ALLOWLIST: () => AGY_SCHEMA_ALLOWLIST,
|
|
43
59
|
isClaudeModel: () => isClaudeModel,
|
|
@@ -63,7 +79,8 @@ function stripTrailingModelTurn(contents) {
|
|
|
63
79
|
* Denylisting is whack-a-mole, so keep only the keywords the upstream
|
|
64
80
|
* accepts. Container shapes are handled distinctly: `properties` is a
|
|
65
81
|
* name->schema map (keys preserved), `items`/`additionalProperties` are
|
|
66
|
-
* nested schemas
|
|
82
|
+
* nested schemas (additionalProperties also accepts a boolean — live-verified
|
|
83
|
+
* against the Antigravity upstream), `required`/`enum` are plain arrays.
|
|
67
84
|
*
|
|
68
85
|
* Keyword VALUES are also constrained by the protobuf shape (verified
|
|
69
86
|
* empirically): `type` must be a single enum string (union arrays like
|
|
@@ -169,13 +186,45 @@ function messageToContent(message, toolNames) {
|
|
|
169
186
|
parts
|
|
170
187
|
};
|
|
171
188
|
}
|
|
189
|
+
/**
|
|
190
|
+
* Builtin Gemini tools must not shadow functionDeclarations names (upstream
|
|
191
|
+
* treats them as native tools; verified by OmniRoute's GEMINI_BUILTIN_TOOL_NAMES).
|
|
192
|
+
*/
|
|
193
|
+
const AGY_BUILTIN_TOOL_NAMES = /* @__PURE__ */ new Set([
|
|
194
|
+
"google_search",
|
|
195
|
+
"web_search",
|
|
196
|
+
"search_web",
|
|
197
|
+
"googleSearch"
|
|
198
|
+
]);
|
|
199
|
+
/** Upstream functionDeclarations names are `[a-zA-Z0-9_]` and ≤64 chars (OmniRoute-verified). */
|
|
200
|
+
const AGY_TOOL_NAME_MAX_LENGTH = 64;
|
|
201
|
+
/** Sanitize a tool name to the upstream charset/length; dedupe via a short hash. */
|
|
202
|
+
function sanitizeToolName(name, seen) {
|
|
203
|
+
let candidate = name.replace(/[^a-zA-Z0-9_]/g, "_") || "tool";
|
|
204
|
+
if (candidate.length > AGY_TOOL_NAME_MAX_LENGTH || seen.has(candidate)) {
|
|
205
|
+
const hash = createHash("sha256").update(candidate).digest("hex").slice(0, 8);
|
|
206
|
+
const prefix = candidate.slice(0, AGY_TOOL_NAME_MAX_LENGTH - hash.length - 1);
|
|
207
|
+
candidate = `${prefix}_${hash}`;
|
|
208
|
+
let i = 2;
|
|
209
|
+
while (seen.has(candidate)) candidate = `${prefix}_${i++}_${hash}`;
|
|
210
|
+
}
|
|
211
|
+
seen.add(candidate);
|
|
212
|
+
return candidate;
|
|
213
|
+
}
|
|
172
214
|
function toolsToDeclarations(tools) {
|
|
173
215
|
if (!tools || tools.length === 0) return void 0;
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
216
|
+
const seenNames = /* @__PURE__ */ new Set();
|
|
217
|
+
const declarations = [];
|
|
218
|
+
for (const tool of tools) {
|
|
219
|
+
if (AGY_BUILTIN_TOOL_NAMES.has(tool.name)) continue;
|
|
220
|
+
declarations.push({
|
|
221
|
+
name: sanitizeToolName(tool.name, seenNames),
|
|
222
|
+
description: tool.description,
|
|
223
|
+
parameters: sanitizeToolSchema(tool.parameters)
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
if (declarations.length === 0) return void 0;
|
|
227
|
+
return [{ functionDeclarations: declarations }];
|
|
179
228
|
}
|
|
180
229
|
/** Build the wrapped Antigravity request body for one call. */
|
|
181
230
|
function toAgyRequestBody(options, context) {
|
|
@@ -206,4 +255,4 @@ function toAgyRequestBody(options, context) {
|
|
|
206
255
|
//#endregion
|
|
207
256
|
export { translate_exports as n, setThoughtSignature as r, toAgyRequestBody as t };
|
|
208
257
|
|
|
209
|
-
//# sourceMappingURL=translate-
|
|
258
|
+
//# sourceMappingURL=translate-CYV7R-UO.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"translate-CYV7R-UO.mjs","names":[],"sources":["../src/runtime/signature-cache.ts","../src/adapter/translate.ts"],"sourcesContent":["/**\n * Gemini thought-signature cache for Antigravity tool calls.\n *\n * The Antigravity backend requires every outbound `functionCall` part to carry\n * a `thoughtSignature` (400 \"Function call is missing a thought_signature\"\n * otherwise). Signatures arrive on the *response* side — as a sibling field of\n * functionCall parts, and on thought parts — and must be replayed on the next\n * turn for the same tool call id. When nothing is cached, the translator\n * injects the `skip_thought_signature_validator` sentinel (the established\n * bypass both reference implementations use by default).\n *\n * Process-local with TTL; a cold process falls back to the sentinel, which the\n * upstream accepts, so cross-process persistence is not required for\n * correctness.\n */\n\nexport const THOUGHT_SIGNATURE_SENTINEL = 'skip_thought_signature_validator'\n\ninterface CacheEntry {\n signature: string\n expiresAt: number\n}\n\nconst DEFAULT_TTL_MS = 60 * 60 * 1000\nconst MAX_ENTRIES = 2000\n\nconst store = new Map<string, CacheEntry>()\n\nfunction pruneExpired(now = Date.now()): void {\n if (store.size < MAX_ENTRIES / 2) return\n for (const [key, entry] of store) {\n if (entry.expiresAt <= now) store.delete(key)\n }\n}\n\n/** Store the signature observed for one tool call id (response side). */\nexport function setThoughtSignature(toolCallId: string, signature: string, ttlMs = DEFAULT_TTL_MS): void {\n if (!toolCallId || !signature) return\n pruneExpired()\n if (store.size >= MAX_ENTRIES) {\n // Evict the oldest entry to keep the cache bounded.\n let oldestKey: string | null = null\n let oldestExpiry = Infinity\n for (const [key, entry] of store) {\n if (entry.expiresAt < oldestExpiry) {\n oldestExpiry = entry.expiresAt\n oldestKey = key\n }\n }\n if (oldestKey) store.delete(oldestKey)\n }\n store.set(toolCallId, { signature, expiresAt: Date.now() + ttlMs })\n}\n\n/** Resolve the signature for one tool call id, or null when unknown/expired. */\nexport function getThoughtSignature(toolCallId: string): string | null {\n if (!toolCallId) return null\n const entry = store.get(toolCallId)\n if (!entry) return null\n if (entry.expiresAt <= Date.now()) {\n store.delete(toolCallId)\n return null\n }\n return entry.signature\n}\n","/**\n * Translate a DSH GenerateOptions into the Antigravity wrapped request.\n *\n * Envelope shape follows the actively-maintained OmniRoute wire format\n * (the archived opencode reference predates it): top-level `project`,\n * `requestId`, `model`, `userAgent`, `requestType`, with the Gemini-style\n * body under `request` (contents/systemInstruction/tools/generationConfig/\n * sessionId). `toolConfig` VALIDATED is attached when tools are present, and\n * Claude-path requests strip trailing model turns (Vertex rejects \"assistant\n * message prefill\").\n *\n * Thinking blocks are carried as-is (Gemini `thought` parts); nothing is\n * stripped or re-signed — that signature dance was an artifact of the\n * reference plugin's interception architecture (see docs/ARCHITECTURE.md).\n */\n\nimport { createHash } from 'node:crypto'\nimport type { ContentBlock, GenerateOptions, Message, ToolSchema } from '@deepseek-ai/dsh-llm'\nimport { generateAntigravityRequestId } from '../runtime/identity.ts'\nimport { getThoughtSignature, THOUGHT_SIGNATURE_SENTINEL } from '../runtime/signature-cache.ts'\n\nexport type AgyPart =\n | { text: string }\n | { thought: true; text: string }\n | { thoughtSignature: string; functionCall: { id: string; name: string; args: unknown } }\n | { functionResponse: { name: string; response: unknown } }\n\nexport interface AgyContent {\n role: 'user' | 'model'\n parts: AgyPart[]\n}\n\nexport interface AgyRequestBody {\n project?: string\n requestId?: string\n model: string\n userAgent?: string\n requestType?: 'agent'\n request: {\n contents: AgyContent[]\n systemInstruction?: { parts: Array<{ text: string }> }\n tools?: Array<{ functionDeclarations: Array<{ name: string; description: string; parameters: unknown }> }>\n toolConfig?: { functionCallingConfig: { mode: 'VALIDATED' } }\n generationConfig?: {\n temperature?: number\n maxOutputTokens?: number\n stopSequences?: string[]\n }\n sessionId?: string\n }\n}\n\n/** Whether a model id belongs to a Claude-branded model (Vertex-hosted). */\nexport function isClaudeModel(model: string): boolean {\n return model.startsWith('claude-') || model.includes('/claude')\n}\n\n/**\n * Vertex (the Antigravity Claude backend) rejects conversations ending on an\n * assistant/model turn (\"assistant message prefill\"); never strip to empty.\n */\nexport function stripTrailingModelTurn(contents: AgyContent[]): AgyContent[] {\n while (contents.length > 1 && contents[contents.length - 1]?.role === 'model') {\n contents.pop()\n }\n return contents\n}\n\n/**\n * The Antigravity backend parses tool `parameters` as a strict protobuf\n * schema and rejects ANY unknown keyword with 400 (verified empirically:\n * `$schema`, `propertyNames`, `pattern`, `minLength`, ... each fail in turn).\n * Denylisting is whack-a-mole, so keep only the keywords the upstream\n * accepts. Container shapes are handled distinctly: `properties` is a\n * name->schema map (keys preserved), `items`/`additionalProperties` are\n * nested schemas (additionalProperties also accepts a boolean — live-verified\n * against the Antigravity upstream), `required`/`enum` are plain arrays.\n *\n * Keyword VALUES are also constrained by the protobuf shape (verified\n * empirically): `type` must be a single enum string (union arrays like\n * `[\"string\",\"number\"]` are rejected) and every `enum` item must be a\n * string (booleans/numbers are rejected). Values are normalized to the\n * nearest valid form instead of being dropped wholesale.\n */\n// Exported for the contract invariant test (tests/adapter.test.ts); not part of\n// the package public API (translate.ts is an internal module).\nexport const AGY_SCHEMA_ALLOWLIST = new Set([\n 'type', 'format', 'title', 'description', 'nullable',\n 'items', 'enum', 'default', 'properties', 'required', 'additionalProperties',\n])\nconst AGY_SCHEMA_MAP_KEYS = new Set(['properties'])\nconst AGY_SCHEMA_NESTED_KEYS = new Set(['items', 'additionalProperties'])\nconst AGY_SCHEMA_LIST_KEYS = new Set(['required', 'enum'])\n\nfunction sanitizeToolSchema(schema: unknown): unknown {\n if (!schema || typeof schema !== 'object') return schema\n if (Array.isArray(schema)) return schema.map((entry) => sanitizeToolSchema(entry))\n\n // Normalize union types: upstream `type` is a single enum string. Pick the\n // first non-null string type (`\"null\"` maps to the `nullable` keyword);\n // fall back to `string` when no usable type remains.\n let normalized = schema as Record<string, unknown>\n if (Array.isArray(normalized.type)) {\n const types = normalized.type.filter((t): t is string => typeof t === 'string' && t !== 'null')\n normalized = { ...normalized, type: types[0] ?? 'string' }\n }\n\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(normalized)) {\n if (!AGY_SCHEMA_ALLOWLIST.has(key)) continue\n if (AGY_SCHEMA_MAP_KEYS.has(key)) {\n const map: Record<string, unknown> = {}\n for (const [name, child] of Object.entries(value as Record<string, unknown>)) {\n map[name] = sanitizeToolSchema(child)\n }\n result[key] = map\n continue\n }\n if (AGY_SCHEMA_NESTED_KEYS.has(key)) {\n result[key] = sanitizeToolSchema(value)\n continue\n }\n if (AGY_SCHEMA_LIST_KEYS.has(key)) {\n // Upstream `enum` items must be strings; filter the rest and omit an\n // empty enum entirely (an empty array would be rejected too).\n if (key === 'enum' && Array.isArray(value)) {\n const filtered = value.filter((v): v is string => typeof v === 'string')\n if (filtered.length > 0) result[key] = filtered\n } else {\n result[key] = value\n }\n continue\n }\n result[key] = value\n }\n return result\n}\n\n/** Collect tool-call names by id so tool-result blocks can name their function. */\nfunction buildToolNameIndex(messages: readonly Message[]): Map<string, string> {\n const index = new Map<string, string>()\n for (const message of messages) {\n for (const block of message.content) {\n if (block.type === 'tool-call') {\n index.set(block.id, block.name)\n }\n }\n }\n return index\n}\n\nfunction blockToParts(block: ContentBlock, toolNames: Map<string, string>): AgyPart[] {\n switch (block.type) {\n case 'text':\n return [{ text: block.text }]\n case 'reasoning':\n return [{ thought: true, text: block.text }]\n case 'tool-call': {\n // Upstream parses functionCall.args as google.protobuf.Struct and\n // rejects a raw string with 400. Guarantee an object: parse the string\n // form, fall back to {} when it is truncated/malformed (the failure\n // mode for long multi-turn histories).\n let args: unknown = {}\n if (typeof block.arguments === 'object' && block.arguments !== null && !Array.isArray(block.arguments)) {\n args = block.arguments\n } else if (typeof block.arguments === 'string') {\n try {\n const parsed: unknown = JSON.parse(block.arguments)\n if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n args = parsed\n }\n } catch {\n // truncated/malformed JSON -> empty object\n }\n }\n // Antigravity rejects functionCall parts without a thoughtSignature\n // (400). Replay the signature captured for this tool call id on the\n // previous turn; the sentinel is the established bypass when nothing is\n // cached (both reference implementations default to it).\n const signature = getThoughtSignature(block.id) ?? THOUGHT_SIGNATURE_SENTINEL\n return [{\n thoughtSignature: signature,\n functionCall: { id: block.id, name: block.name, args },\n }]\n }\n case 'tool-result': {\n const name = toolNames.get(block.toolCallId) ?? block.toolCallId\n const text = block.content\n .filter((b): b is Extract<ContentBlock, { type: 'text' }> => b.type === 'text')\n .map((b) => b.text)\n .join('\\n')\n return [{\n functionResponse: {\n name,\n response: { result: text, is_error: block.isError === true },\n },\n }]\n }\n default:\n return [] // unknown block types (merge-extensible) are skipped\n }\n}\n\nfunction messageToContent(message: Message, toolNames: Map<string, string>): AgyContent | null {\n const parts = message.content.flatMap((block) => blockToParts(block, toolNames))\n if (parts.length === 0) return null\n const role = message.role === 'assistant' ? 'model' : 'user'\n return { role, parts }\n}\n\n/**\n * Builtin Gemini tools must not shadow functionDeclarations names (upstream\n * treats them as native tools; verified by OmniRoute's GEMINI_BUILTIN_TOOL_NAMES).\n */\nconst AGY_BUILTIN_TOOL_NAMES = new Set(['google_search', 'web_search', 'search_web', 'googleSearch'])\n\n/** Upstream functionDeclarations names are `[a-zA-Z0-9_]` and ≤64 chars (OmniRoute-verified). */\nconst AGY_TOOL_NAME_MAX_LENGTH = 64\n\n/** Sanitize a tool name to the upstream charset/length; dedupe via a short hash. */\nfunction sanitizeToolName(name: string, seen: Set<string>): string {\n let candidate = name.replace(/[^a-zA-Z0-9_]/g, '_') || 'tool'\n if (candidate.length > AGY_TOOL_NAME_MAX_LENGTH || seen.has(candidate)) {\n const hash = createHash('sha256').update(candidate).digest('hex').slice(0, 8)\n const prefix = candidate.slice(0, AGY_TOOL_NAME_MAX_LENGTH - hash.length - 1)\n candidate = `${prefix}_${hash}`\n let i = 2\n while (seen.has(candidate)) candidate = `${prefix}_${i++}_${hash}`\n }\n seen.add(candidate)\n return candidate\n}\n\nfunction toolsToDeclarations(tools: ToolSchema[] | undefined): AgyRequestBody['request']['tools'] {\n if (!tools || tools.length === 0) return undefined\n const seenNames = new Set<string>()\n const declarations = []\n for (const tool of tools) {\n if (AGY_BUILTIN_TOOL_NAMES.has(tool.name)) continue\n declarations.push({\n name: sanitizeToolName(tool.name, seenNames),\n description: tool.description,\n parameters: sanitizeToolSchema(tool.parameters),\n })\n }\n if (declarations.length === 0) return undefined\n return [{ functionDeclarations: declarations }]\n}\n\n/** Build the wrapped Antigravity request body for one call. */\nexport function toAgyRequestBody(\n options: GenerateOptions,\n context: { projectId?: string; sessionId?: string },\n): AgyRequestBody {\n const toolNames = buildToolNameIndex(options.messages)\n let contents = options.messages\n .map((message) => messageToContent(message, toolNames))\n .filter((c): c is AgyContent => c !== null)\n if (isClaudeModel(options.model)) {\n contents = stripTrailingModelTurn(contents)\n }\n\n const tools = toolsToDeclarations(options.tools)\n const generationConfig: NonNullable<AgyRequestBody['request']['generationConfig']> = {}\n if (options.temperature !== undefined) generationConfig.temperature = options.temperature\n if (options.maxTokens !== undefined) generationConfig.maxOutputTokens = options.maxTokens\n if (options.stop !== undefined && options.stop.length > 0) generationConfig.stopSequences = options.stop\n\n return {\n project: context.projectId || undefined,\n requestId: generateAntigravityRequestId(),\n model: options.model,\n userAgent: 'antigravity',\n requestType: 'agent',\n request: {\n contents,\n ...(options.system ? { systemInstruction: { parts: [{ text: options.system }] } } : {}),\n ...(tools ? { tools } : {}),\n ...(tools ? { toolConfig: { functionCallingConfig: { mode: 'VALIDATED' } } } : {}),\n ...(Object.keys(generationConfig).length > 0 ? { generationConfig } : {}),\n ...(context.sessionId ? { sessionId: context.sessionId } : {}),\n },\n }\n}\n"],"mappings":";;;AAuBA,MAAM,iBAAiB;AACvB,MAAM,cAAc;AAEpB,MAAM,wBAAQ,IAAI,IAAwB;AAE1C,SAAS,aAAa,MAAM,KAAK,IAAI,GAAS;CAC5C,IAAI,MAAM,OAAO,cAAc,GAAG;CAClC,KAAK,MAAM,CAAC,KAAK,UAAU,OACzB,IAAI,MAAM,aAAa,KAAK,MAAM,OAAO,GAAG;AAEhD;;AAGA,SAAgB,oBAAoB,YAAoB,WAAmB,QAAQ,gBAAsB;CACvG,IAAI,CAAC,cAAc,CAAC,WAAW;CAC/B,aAAa;CACb,IA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AAS,KAAA,KAAa,QAAQ,KAAK,SAAS,GAAG,iBAAiB,gBAAgB,QAAQ;CAEpG,OAAO;EACL,SAAS,QAAQ,aAAa,KAAA;EAC9B,WAAW,6BAA6B;EACxC,OAAO,QAAQ;EACf,WAAW;EACX,aAAa;EACb,SAAS;GACP;GACA,GAAI,QAAQ,SAAS,EAAE,mBAAmB,EAAE,OAAO,CAAC,EAAE,MAAM,QAAQ,OAAO,CAAC,EAAE,EAAE,IAAI,CAAC;GACrF,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;GACzB,GAAI,QAAQ,EAAE,YAAY,EAAE,uBAAuB,EAAE,MAAM,YAAY,EAAE,EAAE,IAAI,CAAC;GAChF,GAAI,OAAO,KAAK,gBAAgB,CAAC,CAAC,SAAS,IAAI,EAAE,iBAAiB,IAAI,CAAC;GACvE,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC9D;CACF;AACF"}
|
package/lib/web/plugin.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { m as resolveAntigravityVersionBounded, n as generateFingerprint, r as recordFingerprintVersion } from "../session-
|
|
2
|
-
import { t as createAgyRuntime } from "../plugin-common-
|
|
3
|
-
import { t as exchangeAntigravity } from "../exchange-
|
|
4
|
-
import { n as upsertImportedAccount, r as authorizeAntigravity, t as importManySources } from "../import-
|
|
1
|
+
import { m as resolveAntigravityVersionBounded, n as generateFingerprint, r as recordFingerprintVersion } from "../session-CyoQxOqv.mjs";
|
|
2
|
+
import { t as createAgyRuntime } from "../plugin-common-BDQB_5km.mjs";
|
|
3
|
+
import { t as exchangeAntigravity } from "../exchange-BkQRoBzy.mjs";
|
|
4
|
+
import { n as upsertImportedAccount, r as authorizeAntigravity, t as importManySources } from "../import-KAAtJXZP.mjs";
|
|
5
5
|
//#region src/web/i18n.ts
|
|
6
6
|
const I18N_DICT = {
|
|
7
7
|
en: {
|
|
@@ -1318,7 +1318,7 @@ function createAgyWebRoutes(options) {
|
|
|
1318
1318
|
const session = await sessions.getSession().catch(() => void 0);
|
|
1319
1319
|
if (!session || session.index !== entry.index) continue;
|
|
1320
1320
|
try {
|
|
1321
|
-
const { fetchAvailableModels } = await import("../models-
|
|
1321
|
+
const { fetchAvailableModels } = await import("../models-BpIXp4vx.mjs").then((n) => n.n);
|
|
1322
1322
|
const discovered = await fetchAvailableModels(session.auth.access, session.account.projectId);
|
|
1323
1323
|
const models = Object.entries(discovered.models ?? {});
|
|
1324
1324
|
if (models.length > 0) {
|
|
@@ -1474,7 +1474,7 @@ function createAgyWebRoutes(options) {
|
|
|
1474
1474
|
return;
|
|
1475
1475
|
}
|
|
1476
1476
|
try {
|
|
1477
|
-
const { listAgyModels } = await import("../models-
|
|
1477
|
+
const { listAgyModels } = await import("../models-BpIXp4vx.mjs").then((n) => n.n);
|
|
1478
1478
|
const models = await listAgyModels(session.auth.access, session.account.projectId);
|
|
1479
1479
|
sendJson(res, 200, {
|
|
1480
1480
|
account: session.account.email ?? null,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-agy",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"packageManager": "pnpm@11.10.0",
|
|
5
5
|
"description": "Google Antigravity (agy) OAuth auth + model access plugin for DeepSeek Harness: multi-account pool, 429 rotation, device fingerprinting, CLI and web login.",
|
|
6
6
|
"type": "module",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"parse-CiEzD9d_.mjs","names":[],"sources":["../src/adapter/parse.ts"],"sourcesContent":["/**\n * Parse Antigravity SSE responses (Gemini-style `candidates[]` events) into the\n * DSH StreamChunk protocol: block-start / text-delta / reasoning-delta /\n * tool-call-delta / block-end / usage / finish.\n *\n * Wire shape: each `data:` payload is a JSON array of candidate objects with\n * `content.parts[]` (text / {thought:true} / functionCall), `usageMetadata`,\n * and `finishReason`. Streams terminate with `data: [DONE]`.\n */\n\nimport type { FinishReason, StreamChunk } from '@deepseek-ai/dsh-llm'\nimport { CallId } from '@deepseek-ai/dsh-llm'\n\nexport interface SsePart {\n text?: string\n thought?: boolean\n thoughtSignature?: string\n functionCall?: { id?: string; name?: string; args?: unknown }\n}\n\nexport interface SseCandidate {\n index?: number\n content?: {\n role?: string\n parts?: SsePart[]\n }\n finishReason?: string\n}\n\nexport interface SsePayload {\n candidates?: SseCandidate[]\n usageMetadata?: {\n promptTokenCount?: number\n candidatesTokenCount?: number\n totalTokenCount?: number\n cachedContentTokenCount?: number\n }\n error?: { code?: number; status?: string; message?: string }\n}\n\n/**\n * Parse one SSE `data:` line; returns null for `[DONE]` or empty lines.\n * Accepts the `{\"response\": {...}}` envelope (daily endpoint wire shape) and\n * the bare array/object shapes older clients emitted.\n */\nexport function parseSseDataLine(line: string): SsePayload | null {\n const trimmed = line.trim()\n if (!trimmed.startsWith('data:')) return null\n const data = trimmed.slice(5).trim()\n if (data === '' || data === '[DONE]') return null\n const parsed = JSON.parse(data) as unknown\n const root = (parsed as { response?: unknown })?.response ?? parsed\n const payload = (Array.isArray(root) ? root[0] : root) as SsePayload | undefined\n return payload ?? null\n}\n\nfunction mapFinishReason(reason: string | undefined): FinishReason {\n switch (reason) {\n case 'MAX_TOKENS':\n return { kind: 'max-tokens' }\n case 'STOP':\n return { kind: 'stop' }\n case 'TOOL_CALLS':\n case 'FUNCTION_CALL':\n return { kind: 'tool-calls' }\n default:\n return { kind: 'stop' }\n }\n}\n\n/**\n * Consume an SSE text stream and yield StreamChunks. One accumulating block is\n * kept open at a time; tool-call argument deltas accumulate until a different\n * part kind, usage metadata, or stream end closes it.\n */\nexport interface ParseAgySseOptions {\n signal?: AbortSignal\n /**\n * Invoked when a functionCall part carries a sibling thoughtSignature, and\n * when a thought part carries one, keyed by the functionCall id (or the\n * thought signature is ignored unless paired). The adapter persists these\n * for replay on the next turn (see signature-cache.ts).\n */\n onToolSignature?(toolCallId: string, signature: string): void\n}\n\nexport async function* parseAgySse(\n body: ReadableStream<Uint8Array>,\n options: ParseAgySseOptions = {},\n): AsyncGenerator<StreamChunk> {\n const { signal } = options\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n let blockIndex = 0\n let finishReason: FinishReason = { kind: 'stop' }\n let sawUsage = false\n let lastUsage: { inputTokens: number; outputTokens: number; cacheReadTokens?: number } | null = null\n\n interface OpenBlock {\n kind: 'text' | 'reasoning' | 'tool-call'\n id?: string\n name?: string\n arguments: string\n text: string\n }\n let open: OpenBlock | null = null\n\n const closeBlock = (): StreamChunk | null => {\n if (!open) return null\n const block: StreamChunk = open.kind === 'tool-call'\n ? {\n type: 'block-end',\n index: blockIndex,\n block: {\n type: 'tool-call',\n id: CallId(open.id ?? `call-${blockIndex}`),\n name: open.name ?? '',\n arguments: open.arguments,\n },\n }\n : {\n type: 'block-end',\n index: blockIndex,\n block: { type: open.kind, text: open.text },\n }\n open = null\n blockIndex += 1\n return block\n }\n\n const ensureBlock = (kind: OpenBlock['kind'], meta: { id?: string; name?: string } = {}): StreamChunk | null => {\n if (open && open.kind !== kind) {\n void closeBlock()\n }\n if (!open) {\n open = { kind, arguments: '', text: '', id: meta.id, name: meta.name }\n const blockType = kind === 'tool-call' ? 'tool-call' : kind\n return { type: 'block-start', index: blockIndex, blockType }\n }\n return null\n }\n\n try {\n while (true) {\n if (signal?.aborted) {\n throw new DOMException('aborted', 'AbortError')\n }\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n let newlineIndex: number\n while ((newlineIndex = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newlineIndex)\n buffer = buffer.slice(newlineIndex + 1)\n if (!line.startsWith('data:')) continue\n const payload = parseSseDataLine(line)\n if (!payload) continue\n if (payload.error) {\n const message = payload.error.message ?? payload.error.status ?? 'upstream error'\n throw new Error(`agy stream error (${payload.error.code ?? 'unknown'}): ${message}`)\n }\n for (const candidate of payload.candidates ?? []) {\n if (candidate.finishReason) {\n finishReason = mapFinishReason(candidate.finishReason)\n }\n for (const part of candidate.content?.parts ?? []) {\n if (part.text !== undefined && part.thought !== true) {\n const start = ensureBlock('text')\n if (start) yield start\n open!.text += part.text\n yield { type: 'text-delta', index: blockIndex, text: part.text }\n } else if (part.text !== undefined && part.thought === true) {\n const start = ensureBlock('reasoning')\n if (start) yield start\n open!.text += part.text\n yield { type: 'reasoning-delta', index: blockIndex, text: part.text }\n } else if (part.functionCall) {\n // Use the upstream functionCall id when present so the signature\n // captured on this part can be replayed for the same id next turn.\n const upstreamId = part.functionCall.id || String(blockIndex)\n const start = ensureBlock('tool-call', {\n id: upstreamId,\n name: part.functionCall.name,\n })\n if (start) yield start\n if (part.thoughtSignature) {\n options.onToolSignature?.(upstreamId, part.thoughtSignature)\n }\n const argsJson = typeof part.functionCall.args === 'string'\n ? part.functionCall.args\n : JSON.stringify(part.functionCall.args ?? {})\n open!.arguments += argsJson\n yield {\n type: 'tool-call-delta',\n index: blockIndex,\n id: CallId(open!.id ?? ''),\n name: open!.name,\n argumentsDelta: argsJson,\n }\n }\n }\n }\n if (payload.usageMetadata) {\n // The upstream sends usageMetadata on EVERY SSE event (cumulative).\n // Do NOT close the block here: closing per event would split one\n // continuous text stream into a block per chunk (frontend renders\n // block boundaries as line breaks). Stash the last (full) totals\n // and emit one usage chunk at stream end.\n sawUsage = true\n // DSH TokenUsage buckets are DISJOINT: inputTokens must be the\n // uncached portion only; cache reads are reported separately.\n // Reporting the full promptTokenCount here double-counts cached\n // tokens in the stats line's cache-hit percentage (it divides by\n // uncached + cacheRead + cacheWrite).\n const promptTokens = payload.usageMetadata.promptTokenCount ?? 0\n const cachedTokens = payload.usageMetadata.cachedContentTokenCount ?? 0\n lastUsage = {\n inputTokens: Math.max(0, promptTokens - cachedTokens),\n outputTokens: payload.usageMetadata.candidatesTokenCount ?? 0,\n cacheReadTokens: cachedTokens,\n }\n }\n }\n }\n const closed = closeBlock()\n if (closed) yield closed\n if (lastUsage) {\n yield { type: 'usage', usage: lastUsage }\n } else if (sawUsage) {\n yield { type: 'usage', usage: { inputTokens: 0, outputTokens: 0 } }\n }\n yield { type: 'finish', reason: finishReason }\n } finally {\n reader.releaseLock()\n }\n}\n"],"mappings":";;;;;;;;;;;;AA6CA,SAAgB,iBAAiB,MAAiC;CAChE,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,CAAC,QAAQ,WAAW,OAAO,GAAG,OAAO;CACzC,MAAM,OAAO,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK;CACnC,IAAI,SAAS,MAAM,SAAS,UAAU,OAAO;CAC7C,MAAM,SAAS,KAAK,MAAM,IAAI;CAC9B,MAAM,OAAQ,QAAmC,YAAY;CAE7D,QADiB,MAAM,QAAQ,IAAI,IAAI,KAAK,KAAK,SAC/B;AACpB;AAEA,SAAS,gBAAgB,QAA0C;CACjE,QAAQ,QAAR;EACE,KAAK,cACH,OAAO,EAAE,MAAM,aAAa;EAC9B,KAAK,QACH,OAAO,EAAE,MAAM,OAAO;EACxB,KAAK;EACL,KAAK,iBACH,OAAO,EAAE,MAAM,aAAa;EAC9B,SACE,OAAO,EAAE,MAAM,OAAO;CAC1B;AACF;AAkBA,gBAAuB,YACrB,MACA,UAA8B,CAAC,GACF;CAC7B,MAAM,EAAE,WAAW;CACnB,MAAM,SAAS,KAAK,UAAU;CAC9B,MAAM,UAAU,IAAI,YAAY;CAChC,IAAI,SAAS;CACb,IAAI,aAAa;CACjB,IAAI,eAA6B,EAAE,MAAM,OAAO;CAChD,IAAI,WAAW;CACf,IAAI,YAA4F;CAShG,IAAI,OAAyB;CAE7B,MAAM,mBAAuC;EAC3C,IAAI,CAAC,MAAM,OAAO;EAClB,MAAM,QAAqB,KAAK,SAAS,cACrC;GACE,MAAM;GACN,OAAO;GACP,OAAO;IACL,MAAM;IACN,IAAI,OAAO,KAAK,MAAM,QAAQ,YAAY;IAC1C,MAAM,KAAK,QAAQ;IACnB,WAAW,KAAK;GAClB;EACF,IACA;GACE,MA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