dsh-agy 0.2.3 → 0.2.4

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.
@@ -1,5 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { _ as generateAntigravityRequestId } from "./accounts-BvX5zmPa.mjs";
2
+ import { v as generateAntigravityRequestId } from "./accounts-DbTTxX_z.mjs";
3
+ import { i as isLevelThinkingModel } from "./catalog-iuikPZIb.mjs";
3
4
  import { createHash } from "node:crypto";
4
5
  const DEFAULT_TTL_MS = 36e5;
5
6
  const MAX_ENTRIES = 2e3;
@@ -145,7 +146,7 @@ function buildToolNameIndex(messages) {
145
146
  for (const message of messages) for (const block of message.content) if (block.type === "tool-call") index.set(block.id, block.name);
146
147
  return index;
147
148
  }
148
- function blockToParts(block, toolNames) {
149
+ function blockToParts(block, toolNames, images) {
149
150
  switch (block.type) {
150
151
  case "text": return [{ text: block.text }];
151
152
  case "reasoning": return [{
@@ -175,11 +176,19 @@ function blockToParts(block, toolNames) {
175
176
  is_error: block.isError === true
176
177
  }
177
178
  } }];
179
+ case "image": {
180
+ const resolved = images.get(block.attachment.attachmentId);
181
+ if (!resolved) throw new Error(`agy translate: unresolved image attachment "${block.attachment.attachmentId}"`);
182
+ return [{ inlineData: {
183
+ mimeType: resolved.mediaType,
184
+ data: resolved.data
185
+ } }];
186
+ }
178
187
  default: return [];
179
188
  }
180
189
  }
181
- function messageToContent(message, toolNames) {
182
- const parts = message.content.flatMap((block) => blockToParts(block, toolNames));
190
+ function messageToContent(message, toolNames, images) {
191
+ const parts = message.content.flatMap((block) => block.type === "image" && message.role !== "user" ? [] : blockToParts(block, toolNames, images));
183
192
  if (parts.length === 0) return null;
184
193
  return {
185
194
  role: message.role === "assistant" ? "model" : "user",
@@ -196,6 +205,12 @@ const AGY_BUILTIN_TOOL_NAMES = /* @__PURE__ */ new Set([
196
205
  "search_web",
197
206
  "googleSearch"
198
207
  ]);
208
+ /** Level-thinking: single id + selectable low/medium/high via thinkingLevel (catalog thinking:'level'). */
209
+ const LEVEL_THINKING_LEVELS = /* @__PURE__ */ new Set([
210
+ "low",
211
+ "medium",
212
+ "high"
213
+ ]);
199
214
  /** Upstream functionDeclarations names are `[a-zA-Z0-9_]` and ≤64 chars (OmniRoute-verified). */
200
215
  const AGY_TOOL_NAME_MAX_LENGTH = 64;
201
216
  /** Sanitize a tool name to the upstream charset/length; dedupe via a short hash. */
@@ -229,13 +244,19 @@ function toolsToDeclarations(tools) {
229
244
  /** Build the wrapped Antigravity request body for one call. */
230
245
  function toAgyRequestBody(options, context) {
231
246
  const toolNames = buildToolNameIndex(options.messages);
232
- let contents = options.messages.map((message) => messageToContent(message, toolNames)).filter((c) => c !== null);
247
+ const images = context.images ?? /* @__PURE__ */ new Map();
248
+ let contents = options.messages.map((message) => messageToContent(message, toolNames, images)).filter((c) => c !== null);
233
249
  if (isClaudeModel(options.model)) contents = stripTrailingModelTurn(contents);
234
250
  const tools = toolsToDeclarations(options.tools);
235
251
  const generationConfig = {};
236
252
  if (options.temperature !== void 0) generationConfig.temperature = options.temperature;
237
253
  if (options.maxTokens !== void 0) generationConfig.maxOutputTokens = options.maxTokens;
238
254
  if (options.stop !== void 0 && options.stop.length > 0) generationConfig.stopSequences = options.stop;
255
+ const effort = options.reasoningEffort?.toLowerCase();
256
+ if (effort && isLevelThinkingModel(options.model) && LEVEL_THINKING_LEVELS.has(effort)) generationConfig.thinkingConfig = {
257
+ thinkingLevel: effort,
258
+ includeThoughts: true
259
+ };
239
260
  return {
240
261
  project: context.projectId || void 0,
241
262
  requestId: generateAntigravityRequestId(),
@@ -255,4 +276,4 @@ function toAgyRequestBody(options, context) {
255
276
  //#endregion
256
277
  export { translate_exports as n, setThoughtSignature as r, toAgyRequestBody as t };
257
278
 
258
- //# sourceMappingURL=translate-C1SMdm5J.mjs.map
279
+ //# sourceMappingURL=translate-COjBTH4-.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"translate-COjBTH4-.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'\nimport { catalogModel, isLevelThinkingModel } from './catalog.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 | { inlineData: { mimeType: string; data: string } }\n\n/** Image bytes pre-resolved from the durable attachment store, keyed by attachment id. */\nexport interface AgyResolvedImage {\n mediaType: string\n /** Pure base64 (no data: prefix). */\n data: string\n}\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 thinkingConfig?: { thinkingLevel: string; includeThoughts: boolean }\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(\n block: ContentBlock,\n toolNames: Map<string, string>,\n images: Map<string, AgyResolvedImage>,\n): 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 case 'image': {\n // Bytes are pre-resolved by the adapter before translation; a missing\n // entry breaks that invariant and must fail loudly, never silently drop.\n const resolved = images.get(block.attachment.attachmentId)\n if (!resolved) {\n throw new Error(`agy translate: unresolved image attachment \"${block.attachment.attachmentId}\"`)\n }\n return [{ inlineData: { mimeType: resolved.mediaType, data: resolved.data } }]\n }\n default:\n return [] // unknown block types (merge-extensible) are skipped\n }\n}\n\nfunction messageToContent(\n message: Message,\n toolNames: Map<string, string>,\n images: Map<string, AgyResolvedImage>,\n): AgyContent | null {\n const parts = message.content.flatMap((block) =>\n // Non-user images are out of scope by policy (docs ANTIGRAVITY-API §3.2):\n // skip them like any other untranslatable block instead of tripping the\n // unresolved-map guard, which protects only the user-image invariant.\n block.type === 'image' && message.role !== 'user'\n ? []\n : blockToParts(block, toolNames, images),\n )\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/** Level-thinking: single id + selectable low/medium/high via thinkingLevel (catalog thinking:'level'). */\nconst LEVEL_THINKING_LEVELS = new Set(['low', 'medium', 'high'])\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; images?: Map<string, AgyResolvedImage> },\n): AgyRequestBody {\n const toolNames = buildToolNameIndex(options.messages)\n const images = context.images ?? new Map<string, AgyResolvedImage>()\n let contents = options.messages\n .map((message) => messageToContent(message, toolNames, images))\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 // Level-thinking: map the DSH reasoning effort to thinkingConfig.\n // Id-bound models (thinking !== 'level') never emit it — default is UI hint, not wire default.\n const effort = options.reasoningEffort?.toLowerCase()\n if (effort && isLevelThinkingModel(options.model) && LEVEL_THINKING_LEVELS.has(effort)) {\n generationConfig.thinkingConfig = { thinkingLevel: effort, includeThoughts: true }\n }\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,IAAI,MAAM,QAAQ,aAAa;EAE7B,IAAI,YAA2B;EAC/B,IAAI,eAAe;EACnB,KAAK,MAAM,CAAC,KAAK,UAAU,OACzB,IAAI,MAAM,YAAY,cAAc;GAClC,eAAe,MAAM;GACrB,YAAY;EACd;EAEF,IAAI,WA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QAAQ;CAG5C,MAAM,QAAQ,oBAAoB,QAAQ,KAAK;CAC/C,MAAM,mBAA+E,CAAC;CACtF,IAAI,QAAQ,gBAAgB,KAAA,GAAW,iBAAiB,cAAc,QAAQ;CAC9E,IAAI,QAAQ,cAAc,KAAA,GAAW,iBAAiB,kBAAkB,QAAQ;CAChF,IAAI,QAAQ,SAAS,KAAA,KAAa,QAAQ,KAAK,SAAS,GAAG,iBAAiB,gBAAgB,QAAQ;CAGpG,MAAM,SAAS,QAAQ,iBAAiB,YAAY;CACpD,IAAI,UAAU,qBAAqB,QAAQ,KAAK,KAAK,sBAAsB,IAAI,MAAM,GACnF,iBAAiB,iBAAiB;EAAE,eAAe;EAAQ,iBAAiB;CAAK;CAGnF,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"}
@@ -1,7 +1,8 @@
1
- import { d as generateFingerprint, f as recordFingerprintVersion, h as resolveAntigravityVersionBounded, u as isAgyDisabled } from "../accounts-BvX5zmPa.mjs";
2
- import { t as createAgyRuntime } from "../plugin-common-Bmz4Ife-.mjs";
3
- import { t as exchangeAntigravity } from "../exchange-CteHnRzO.mjs";
4
- import { n as upsertImportedAccount, r as authorizeAntigravity, t as importManySources } from "../import-C7EV_tne.mjs";
1
+ import { d as isAgyDisabled, f as generateFingerprint, g as resolveAntigravityVersionBounded, n as maskProxyUrl, p as recordFingerprintVersion } from "../accounts-DbTTxX_z.mjs";
2
+ import { a as proxyUrlForLogs, r as normalizeProxyUrl, t as isProxyReachable } from "../proxy-DQPIwUov.mjs";
3
+ import { t as createAgyRuntime } from "../plugin-common-D7lc-W6b.mjs";
4
+ import { t as exchangeAntigravity } from "../exchange-BvrLu2E4.mjs";
5
+ import { n as upsertImportedAccount, r as authorizeAntigravity, t as importManySources } from "../import-DSvpbB0T.mjs";
5
6
  //#region src/web/i18n.ts
6
7
  const I18N_DICT = {
7
8
  en: {
@@ -895,6 +896,15 @@ function renderDashboardHtml() {
895
896
  '<button class="btn btn-secondary btn-sm" id="btn-action-fp">' + esc(t('fingerprint')) + '</button>' +
896
897
  '<button class="btn btn-danger btn-sm" id="btn-action-delete">' + esc(t('deleteAccount')) + '</button>' +
897
898
  '</div>' +
899
+ '</div>' +
900
+
901
+ '<div style="margin-top:14px;padding:10px 12px;border:1px solid var(--border-l1);border-radius:8px;background:var(--bg-surface-elevated);display:flex;flex-wrap:wrap;gap:8px;align-items:center;">' +
902
+ '<span style="font-size:13px;font-weight:500;white-space:nowrap;">Proxy:</span>' +
903
+ '<input id="proxy-input-' + selectedIndex + '" placeholder="socks5://user:pass@host:1080" style="flex:1;min-width:220px;font-family:var(--ds-font-family-code);font-size:12.5px;padding:6px 10px;background:var(--bg-input);border:1px solid var(--border-l2);border-radius:6px;color:var(--text-primary);outline:none;">' +
904
+ '<button class="btn btn-primary btn-sm" id="btn-proxy-save">Save</button>' +
905
+ '<button class="btn btn-secondary btn-sm" id="btn-proxy-clear">Clear</button>' +
906
+ '<button class="btn btn-secondary btn-sm" id="btn-proxy-test">Test</button>' +
907
+ '<span id="proxy-status" style="font-size:12px;color:var(--text-secondary);">' + ((a.proxy || a.proxyMasked) ? 'Current: ' + esc(a.proxy || a.proxyMasked) : 'No proxy (using env)') + '</span>' +
898
908
  '</div>' +
899
909
 
900
910
  '<div style="margin-top:16px;">' +
@@ -1026,6 +1036,58 @@ function renderDashboardHtml() {
1026
1036
  btnTestAll.disabled = false;
1027
1037
  };
1028
1038
 
1039
+ // Proxy actions
1040
+ const btnProxySave = $('btn-proxy-save');
1041
+ if (btnProxySave) btnProxySave.onclick = async () => {
1042
+ const input = $('proxy-input-' + index);
1043
+ const proxy = input ? input.value.trim() : '';
1044
+ btnProxySave.disabled = true;
1045
+ try {
1046
+ const r = await api('/proxy', { method: 'POST', body: JSON.stringify({ index, proxy }) });
1047
+ const masked = r.proxy || r.proxyMasked || '';
1048
+ const statusEl = $('proxy-status');
1049
+ if (statusEl) statusEl.textContent = masked ? 'Current: ' + masked : 'No proxy (using env)';
1050
+ toast(masked ? 'Proxy saved: ' + masked : 'Proxy cleared (using env)', 'success');
1051
+ render();
1052
+ } catch (e) { toast(String(e), 'error'); }
1053
+ finally { btnProxySave.disabled = false; }
1054
+ };
1055
+ const btnProxyClear = $('btn-proxy-clear');
1056
+ if (btnProxyClear) btnProxyClear.onclick = async () => {
1057
+ btnProxyClear.disabled = true;
1058
+ try {
1059
+ await api('/proxy', { method: 'POST', body: JSON.stringify({ index, proxy: '' }) });
1060
+ const statusEl = $('proxy-status');
1061
+ if (statusEl) statusEl.textContent = 'No proxy (using env)';
1062
+ const input = $('proxy-input-' + index);
1063
+ if (input) input.value = '';
1064
+ toast('Proxy cleared (using env)', 'success');
1065
+ render();
1066
+ } catch (e) { toast(String(e), 'error'); }
1067
+ finally { btnProxyClear.disabled = false; }
1068
+ };
1069
+ const btnProxyTest = $('btn-proxy-test');
1070
+ if (btnProxyTest) btnProxyTest.onclick = async () => {
1071
+ const input = $('proxy-input-' + index);
1072
+ const val = input ? input.value.trim() : '';
1073
+ const body = val ? { index, proxy: val } : { index };
1074
+ btnProxyTest.disabled = true;
1075
+ btnProxyTest.textContent = '...';
1076
+ try {
1077
+ const r = await api('/proxy/test', { method: 'POST', body: JSON.stringify(body) });
1078
+ const masked = r.masked ? esc(r.masked) : '';
1079
+ const statusEl = $('proxy-status');
1080
+ if (r.ok) {
1081
+ toast('Proxy reachable: ' + (r.masked || ''), 'success');
1082
+ if (statusEl) statusEl.textContent = 'Reachable: ' + (r.masked || '');
1083
+ } else {
1084
+ toast('Proxy unreachable: ' + (r.masked || '') + (r.error ? ' - ' + r.error : ''), 'error');
1085
+ if (statusEl) statusEl.textContent = 'Unreachable: ' + (r.masked || '') + (r.error ? ' (' + r.error + ')' : '');
1086
+ }
1087
+ } catch (e) { toast(String(e), 'error'); }
1088
+ finally { btnProxyTest.disabled = false; btnProxyTest.textContent = 'Test'; }
1089
+ };
1090
+
1029
1091
  // Single model tests
1030
1092
  document.querySelectorAll('[data-test-model]').forEach((btn) => {
1031
1093
  btn.onclick = async () => {
@@ -1310,7 +1372,9 @@ function createAgyWebRoutes(options) {
1310
1372
  createdAt: account.fingerprint.createdAt
1311
1373
  } : null,
1312
1374
  fingerprintHistory: (account.fingerprintHistory ?? []).length,
1313
- quota: null
1375
+ quota: null,
1376
+ proxy: account.proxy ? maskProxyUrl(account.proxy) : null,
1377
+ proxyMasked: account.proxy ? maskProxyUrl(account.proxy) : null
1314
1378
  };
1315
1379
  list.push(entry);
1316
1380
  }
@@ -1318,7 +1382,7 @@ function createAgyWebRoutes(options) {
1318
1382
  const session = await sessions.getSession().catch(() => void 0);
1319
1383
  if (!session || session.index !== entry.index) continue;
1320
1384
  try {
1321
- const { fetchAvailableModels } = await import("../models-I1UAEk9x.mjs").then((n) => n.r);
1385
+ const { fetchAvailableModels } = await import("../models-DRWVi33p.mjs").then((n) => n.r);
1322
1386
  const discovered = await fetchAvailableModels(session.auth.access, session.account.projectId);
1323
1387
  const models = Object.entries(discovered.models ?? {});
1324
1388
  if (models.length > 0) {
@@ -1484,7 +1548,7 @@ function createAgyWebRoutes(options) {
1484
1548
  return;
1485
1549
  }
1486
1550
  try {
1487
- const { listAgyModels } = await import("../models-I1UAEk9x.mjs").then((n) => n.r);
1551
+ const { listAgyModels } = await import("../models-DRWVi33p.mjs").then((n) => n.r);
1488
1552
  const models = await listAgyModels(session.auth.access, session.account.projectId);
1489
1553
  sendJson(res, 200, {
1490
1554
  account: session.account.email ?? null,
@@ -1552,6 +1616,107 @@ function createAgyWebRoutes(options) {
1552
1616
  sendJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
1553
1617
  }
1554
1618
  };
1619
+ const handleProxy = async (req, res) => {
1620
+ try {
1621
+ const body = await readJson(req);
1622
+ const rawIdx = Number(body.index);
1623
+ if (!Number.isInteger(rawIdx) || !Number.isFinite(rawIdx) || rawIdx < 0) {
1624
+ sendJson(res, 400, { error: "invalid index" });
1625
+ return;
1626
+ }
1627
+ const index = rawIdx;
1628
+ const raw = typeof body.proxy === "string" ? body.proxy : "";
1629
+ if (!raw.trim()) {
1630
+ await store.mutate((storage) => {
1631
+ const account = storage.accounts[index];
1632
+ if (!account) throw new Error("account not found");
1633
+ delete account.proxy;
1634
+ });
1635
+ sendJson(res, 200, {
1636
+ ok: true,
1637
+ proxy: null,
1638
+ proxyMasked: null,
1639
+ rawLogs: null
1640
+ });
1641
+ return;
1642
+ }
1643
+ let normalized;
1644
+ try {
1645
+ normalized = normalizeProxyUrl(raw);
1646
+ } catch (e) {
1647
+ sendJson(res, 400, { error: e instanceof Error ? e.message : String(e) });
1648
+ return;
1649
+ }
1650
+ await store.mutate((storage) => {
1651
+ const account = storage.accounts[index];
1652
+ if (!account) throw new Error("account not found");
1653
+ account.proxy = normalized;
1654
+ });
1655
+ sendJson(res, 200, {
1656
+ ok: true,
1657
+ proxy: maskProxyUrl(normalized),
1658
+ proxyMasked: maskProxyUrl(normalized),
1659
+ rawLogs: proxyUrlForLogs(normalized)
1660
+ });
1661
+ } catch (error) {
1662
+ sendJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
1663
+ }
1664
+ };
1665
+ const handleProxyTest = async (req, res) => {
1666
+ try {
1667
+ const body = await readJson(req);
1668
+ const rawIdx2 = body.index !== void 0 ? Number(body.index) : NaN;
1669
+ const hasExplicitProxy = typeof body.proxy === "string" && body.proxy.trim() !== "";
1670
+ if (!hasExplicitProxy) {
1671
+ if (!Number.isInteger(rawIdx2) || !Number.isFinite(rawIdx2) || rawIdx2 < 0) {
1672
+ sendJson(res, 400, { error: "invalid index" });
1673
+ return;
1674
+ }
1675
+ } else if (body.index !== void 0) {
1676
+ if (!Number.isInteger(rawIdx2) || !Number.isFinite(rawIdx2) || rawIdx2 < 0) {
1677
+ sendJson(res, 400, { error: "invalid index" });
1678
+ return;
1679
+ }
1680
+ }
1681
+ const index = hasExplicitProxy && body.index === void 0 ? -1 : rawIdx2;
1682
+ let target;
1683
+ if (hasExplicitProxy) try {
1684
+ target = normalizeProxyUrl(body.proxy);
1685
+ } catch (e) {
1686
+ sendJson(res, 400, { error: e instanceof Error ? e.message : String(e) });
1687
+ return;
1688
+ }
1689
+ else {
1690
+ const account = (await store.load()).accounts[index];
1691
+ if (!account) {
1692
+ sendJson(res, 400, { error: "account not found" });
1693
+ return;
1694
+ }
1695
+ if (!account.proxy) {
1696
+ sendJson(res, 400, { error: "no proxy configured for this account" });
1697
+ return;
1698
+ }
1699
+ target = account.proxy;
1700
+ }
1701
+ const masked = maskProxyUrl(target) ?? proxyUrlForLogs(target);
1702
+ let ok = false;
1703
+ let errMsg;
1704
+ try {
1705
+ ok = await isProxyReachable(target, 2e3);
1706
+ if (!ok) errMsg = "proxy unreachable: " + masked;
1707
+ } catch (e) {
1708
+ ok = false;
1709
+ errMsg = e instanceof Error ? e.message : String(e);
1710
+ }
1711
+ sendJson(res, 200, {
1712
+ ok,
1713
+ masked,
1714
+ ...errMsg ? { error: errMsg } : {}
1715
+ });
1716
+ } catch (error) {
1717
+ sendJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
1718
+ }
1719
+ };
1555
1720
  return [
1556
1721
  {
1557
1722
  kind: "exact",
@@ -1634,6 +1799,16 @@ function createAgyWebRoutes(options) {
1634
1799
  kind: "exact",
1635
1800
  path: "/agy/api/fingerprint",
1636
1801
  handler: handleFingerprint
1802
+ },
1803
+ {
1804
+ kind: "exact",
1805
+ path: "/agy/api/proxy",
1806
+ handler: handleProxy
1807
+ },
1808
+ {
1809
+ kind: "exact",
1810
+ path: "/agy/api/proxy/test",
1811
+ handler: handleProxyTest
1637
1812
  }
1638
1813
  ];
1639
1814
  }