@eddyskywalker/dsh-chatgpt-subscription 0.75.1 → 0.75.2

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.
Files changed (30) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/lib/client.js +36 -23
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +399 -99
  5. package/lib/types/client/antigravity-acp/AntigravityAcpSection.d.ts.map +1 -1
  6. package/lib/types/client/antigravity-acp/locales.d.ts +6 -12
  7. package/lib/types/client/antigravity-acp/locales.d.ts.map +1 -1
  8. package/lib/types/client/locales-ru/antigravity-acp.d.ts.map +1 -1
  9. package/lib/types/compat.d.ts +1 -1
  10. package/lib/types/host/antigravity-acp/adapter.d.ts +17 -0
  11. package/lib/types/host/antigravity-acp/adapter.d.ts.map +1 -1
  12. package/lib/types/host/antigravity-acp/auth-cache.d.ts +11 -2
  13. package/lib/types/host/antigravity-acp/auth-cache.d.ts.map +1 -1
  14. package/lib/types/host/antigravity-acp/binary.d.ts +68 -0
  15. package/lib/types/host/antigravity-acp/binary.d.ts.map +1 -1
  16. package/lib/types/host/antigravity-acp/catalog.d.ts.map +1 -1
  17. package/lib/types/host/antigravity-acp/errors.d.ts +10 -0
  18. package/lib/types/host/antigravity-acp/errors.d.ts.map +1 -1
  19. package/lib/types/host/antigravity-acp/login.d.ts +22 -6
  20. package/lib/types/host/antigravity-acp/login.d.ts.map +1 -1
  21. package/lib/types/host/antigravity-acp/mcp-bridge.d.ts +9 -2
  22. package/lib/types/host/antigravity-acp/mcp-bridge.d.ts.map +1 -1
  23. package/lib/types/host/antigravity-acp/routes.d.ts +23 -4
  24. package/lib/types/host/antigravity-acp/routes.d.ts.map +1 -1
  25. package/lib/types/host/antigravity-acp/subagent.d.ts +32 -0
  26. package/lib/types/host/antigravity-acp/subagent.d.ts.map +1 -1
  27. package/lib/types/host/antigravity-acp/types.d.ts +15 -0
  28. package/lib/types/host/antigravity-acp/types.d.ts.map +1 -1
  29. package/lib/types/index.d.ts.map +1 -1
  30. package/package.json +1 -1
package/lib/index.js CHANGED
@@ -817,7 +817,7 @@ const ROUTE_PREFIX$5 = "/api/dsh-chatgpt-subscription";
817
817
  * `test/responses-client.test.ts` asserts the two agree, so a release that
818
818
  * forgets this constant fails the suite instead of shipping quietly.
819
819
  */
820
- const PLUGIN_VERSION = "0.75.1";
820
+ const PLUGIN_VERSION = "0.75.2";
821
821
  const CODEX_CHATGPT_PROVIDER_ID = "codex-chatgpt";
822
822
  const CODEX_API_BASE = "https://chatgpt.com/backend-api/codex";
823
823
  const CODEX_RESPONSES_URL = `${CODEX_API_BASE}/responses`;
@@ -24903,7 +24903,6 @@ var McpBridge = class {
24903
24903
  descriptor;
24904
24904
  token = randomBytes(32).toString("base64url");
24905
24905
  exposed;
24906
- withdrawn = /* @__PURE__ */ new Map();
24907
24906
  parked = /* @__PURE__ */ new Map();
24908
24907
  waiters = /* @__PURE__ */ new Set();
24909
24908
  closed = false;
@@ -24946,7 +24945,15 @@ var McpBridge = class {
24946
24945
  this.parked.clear();
24947
24946
  return calls;
24948
24947
  }
24949
- /** How many calls are currently waiting for an answer. */
24948
+ /**
24949
+ * How many calls the harness has not picked up yet.
24950
+ *
24951
+ * Deliberately the *parked* set - calls the agent has made that the harness has
24952
+ * not taken yet - and not the responses still held open. The cap exists to stop
24953
+ * a runaway agent from piling up calls nobody has picked up; a call the harness
24954
+ * already took is one it answers by the next generation, and counting those as
24955
+ * well would fire the cap during a legitimate multi-step round.
24956
+ */
24950
24957
  get pendingCount() {
24951
24958
  return this.parked.size;
24952
24959
  }
@@ -25095,7 +25102,7 @@ var McpBridge = class {
25095
25102
  async handleToolCall(id, params, response) {
25096
25103
  const record = typeof params === "object" && params !== null && !Array.isArray(params) ? params : {};
25097
25104
  const exposedName = typeof record.name === "string" ? record.name : "";
25098
- const tool = this.exposed.find((entry) => entry.exposedName === exposedName) ?? this.withdrawn.get(exposedName);
25105
+ const tool = this.exposed.find((entry) => entry.exposedName === exposedName);
25099
25106
  if (tool === void 0) {
25100
25107
  respond(response, 200, jsonRpcResult(id, {
25101
25108
  content: [{
@@ -25253,6 +25260,16 @@ const ACP_ERROR_CODES = {
25253
25260
  ACP_DISCONNECTED: "The Antigravity agent process ended mid-turn. Retry to reconnect.",
25254
25261
  /** A JSON-RPC error the line has no specific handling for. */
25255
25262
  ACP_RPC_ERROR: "The Antigravity ACP server returned a JSON-RPC error.",
25263
+ /**
25264
+ * The service declined the account or the request itself - a quota wall, a
25265
+ * policy block, a verification challenge, a rate limit.
25266
+ *
25267
+ * Kept apart from {@link ACP_RPC_ERROR} because the two want opposite
25268
+ * treatment: a transport fault is worth another attempt, while putting the same
25269
+ * account in front of the same wall two more times is how a strict policy turns
25270
+ * one failure into a pattern.
25271
+ */
25272
+ ACP_UPSTREAM_BLOCKED: "The Antigravity service declined this account or request (quota, policy or verification). Retrying here will not change the answer - resolve it in the official client first.",
25256
25273
  /** The server rejected the request parameters or the model id. */
25257
25274
  ACP_INVALID_PARAMS: "The Antigravity ACP server rejected the request parameters or the model id.",
25258
25275
  /** The server does not implement the method this client called. */
@@ -25746,6 +25763,30 @@ function isEffort(value) {
25746
25763
  return EFFORT_ORDER$2.includes(value);
25747
25764
  }
25748
25765
  /**
25766
+ * Which sign-in method to hand the agent when it asks for one.
25767
+ *
25768
+ * The server publishes whatever method list the installed CLI supports, and the
25769
+ * order below is the line's preference: the personal OAuth flow first, then the
25770
+ * terminal flow, then a business account, then the API-key forms. This lives
25771
+ * here - not beside one call site - because two call sites ask the same question:
25772
+ * a main-model session (`adapter.openSession`) and the catalogue read
25773
+ * (`catalog.readCatalogFrom`). They used to disagree, one of them hard-coding
25774
+ * `oauth-personal` and getting a method the server never offered.
25775
+ *
25776
+ * @param authMethods - The ids the server announced in `initialize`.
25777
+ * @returns The method id to request.
25778
+ */
25779
+ function preferAuthMethod(authMethods) {
25780
+ for (const candidate of [
25781
+ "oauth-personal",
25782
+ "terminal-login",
25783
+ "oauth-business",
25784
+ "gemini-api-key",
25785
+ "agent-platform"
25786
+ ]) if (authMethods.includes(candidate)) return candidate;
25787
+ return authMethods[0] ?? "oauth-personal";
25788
+ }
25789
+ /**
25749
25790
  * Collapse the server's tier-suffixed model ids into one selectable model each.
25750
25791
  *
25751
25792
  * The server publishes two different lists that describe the same catalog:
@@ -26019,6 +26060,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26019
26060
  for (const entry of [...this.dormant.values()]) await this.closeDormant(entry);
26020
26061
  for (const turn of [...this.live.values()]) {
26021
26062
  if (this.live.get(turn.dshSessionId) === turn) this.live.delete(turn.dshSessionId);
26063
+ turn.closed = true;
26022
26064
  this.activeTurns = Math.max(0, this.activeTurns - 1);
26023
26065
  turn.queue.close();
26024
26066
  this.cancelTurn(turn);
@@ -26048,10 +26090,12 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26048
26090
  const settings = await this.options.settings.read();
26049
26091
  const images = await resolveRequestImages$1(options, this.options.attachments, signal).catch(() => NO_RESOLVED_IMAGES$3);
26050
26092
  const effort = options.reasoningEffort === void 0 ? settings.defaultReasoningEffort ?? void 0 : String(options.reasoningEffort);
26051
- const live = this.live.get(dshSessionId);
26052
- if (live !== void 0 && live.model === options.model && live.effort === effort && canContinue(options.messages, live.covered, live.fingerprint)) return this.continueTurn(live, options, images, signal, activity);
26053
- if (live !== void 0) await this.closeTurn(live);
26054
26093
  const auxiliary = options.purpose !== void 0;
26094
+ if (!auxiliary) {
26095
+ const live = this.live.get(dshSessionId);
26096
+ if (live !== void 0 && live.model === options.model && live.effort === effort && canContinue(options.messages, live.covered, live.fingerprint)) return this.continueTurn(live, options, images, signal, activity);
26097
+ if (live !== void 0) await this.closeTurn(live);
26098
+ }
26055
26099
  const dormant = auxiliary ? void 0 : this.dormant.get(dshSessionId);
26056
26100
  if (dormant !== void 0) if (this.usableDormant(dormant, options)) {
26057
26101
  const resumed = await this.resumeDormant(dormant, options, settings, effort, images, signal, activity);
@@ -26066,6 +26110,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26066
26110
  this.activeTurns += 1;
26067
26111
  const queue = new UpdateQueue();
26068
26112
  const bridge = new McpBridge(options.tools ?? []);
26113
+ const binding = {};
26069
26114
  let client;
26070
26115
  let reusedSessions = 0;
26071
26116
  try {
@@ -26074,10 +26119,11 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26074
26119
  if (warm !== void 0) {
26075
26120
  client = warm.client;
26076
26121
  reusedSessions = warm.sessions;
26077
- this.attachHandlers(client, queue, activity);
26078
- } else client = this.spawn(launch, queue, activity);
26122
+ this.attachHandlers(client, queue, activity, binding);
26123
+ } else client = this.spawn(launch, queue, activity, binding);
26079
26124
  const descriptor = await bridge.start();
26080
26125
  const sessionId = await this.openSession(client, options, [descriptor], settings);
26126
+ binding.acpSessionId = sessionId;
26081
26127
  await this.applyModelAndEffort(client, sessionId, options.model, effort);
26082
26128
  const prompt = buildPrompt(options, images, 0);
26083
26129
  if ((options.tools ?? []).length > 0) prompt.blocks.unshift({
@@ -26102,9 +26148,10 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26102
26148
  awaitingHarness: false,
26103
26149
  sessionsUsed: reusedSessions + 1,
26104
26150
  tools: fingerprintTools(options.tools),
26105
- parkable
26151
+ parkable,
26152
+ closed: false
26106
26153
  };
26107
- this.live.set(dshSessionId, turn);
26154
+ if (parkable) this.live.set(dshSessionId, turn);
26108
26155
  this.sendPrompt(turn, prompt.blocks);
26109
26156
  return this.pump(turn, signal, activity);
26110
26157
  } catch (error) {
@@ -26328,12 +26375,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26328
26375
  }
26329
26376
  } finally {
26330
26377
  if (!finished) await this.closeTurn(turn);
26331
- else if (!turn.awaitingHarness && this.live.get(turn.dshSessionId) === turn) {
26332
- this.live.delete(turn.dshSessionId);
26333
- this.activeTurns = Math.max(0, this.activeTurns - 1);
26334
- if (turn.parkable) await this.park(turn);
26335
- else await this.release(turn);
26336
- }
26378
+ else if (!turn.awaitingHarness) await this.finishTurn(turn, true);
26337
26379
  }
26338
26380
  }
26339
26381
  /**
@@ -26356,9 +26398,10 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26356
26398
  if ((typeof toolCall?.name === "string" ? toolCall.name : "").startsWith(`mcp_dsh-bridge_`)) return answer();
26357
26399
  return (await this.options.settings.read()).permissionPolicy === "allow" ? answer() : void 0;
26358
26400
  }
26359
- spawn(launch, queue, activity) {
26401
+ spawn(launch, queue, activity, binding) {
26360
26402
  const handlers = {
26361
- onSessionUpdate: (_sessionId, update) => {
26403
+ onSessionUpdate: (sessionId, update) => {
26404
+ if (!ownsSession(binding, sessionId)) return;
26362
26405
  queue.push(update);
26363
26406
  activity.pulse();
26364
26407
  },
@@ -26469,19 +26512,17 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26469
26512
  sessionId: turn.acpSessionId,
26470
26513
  prompt: blocks
26471
26514
  }));
26472
- const usage = asRecord$19(result?.usage);
26515
+ const rawUsage = asRecord$19(result?.usage);
26516
+ const usage = rawUsage === void 0 ? void 0 : readUsage(rawUsage);
26473
26517
  turn.settled = {
26474
26518
  stopReason: typeof result?.stopReason === "string" ? result.stopReason : "end_turn",
26475
- ...usage === void 0 ? {} : { usage: readUsage(usage) }
26519
+ ...usage === void 0 ? {} : { usage }
26520
+ };
26521
+ if (usage !== void 0) this.lastUsage = {
26522
+ ...usage,
26523
+ at: this.now(),
26524
+ durationMs: this.now() - startedAt
26476
26525
  };
26477
- if (usage !== void 0) {
26478
- const read = readUsage(usage);
26479
- if (read !== void 0) this.lastUsage = {
26480
- ...read,
26481
- at: this.now(),
26482
- durationMs: this.now() - startedAt
26483
- };
26484
- }
26485
26526
  } catch (error) {
26486
26527
  turn.settled = { error: asError(error) };
26487
26528
  } finally {
@@ -26497,11 +26538,36 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26497
26538
  * agent's own start-up wait on the next message.
26498
26539
  */
26499
26540
  async closeTurn(turn) {
26500
- if (this.live.get(turn.dshSessionId) === turn) this.live.delete(turn.dshSessionId);
26501
- this.activeTurns = Math.max(0, this.activeTurns - 1);
26541
+ if (turn.closed) return;
26502
26542
  turn.queue.close();
26503
26543
  this.cancelTurn(turn);
26504
- await this.release(turn);
26544
+ await this.finishTurn(turn, false);
26545
+ }
26546
+ /**
26547
+ * Account for one turn exactly once, then hand its process back.
26548
+ *
26549
+ * Every ending goes through here: a completed stream parks the conversation, an
26550
+ * abandoned one releases the process, and a turn whose live entry was replaced
26551
+ * releases it too - it no longer owns this session's conversation, so parking it
26552
+ * would replace the parked one with a transcript nobody is talking to.
26553
+ *
26554
+ * The `closed` flag is what makes this safe to call from a second path: the pump
26555
+ * finishing after a cancellation, and a cancellation arriving after the pump
26556
+ * finished, both used to be able to decrement `activeTurns` or release a process
26557
+ * twice.
26558
+ *
26559
+ * @param turn - The turn being ended.
26560
+ * @param parkAllowed - Whether a conversation may be left parked behind it.
26561
+ */
26562
+ async finishTurn(turn, parkAllowed) {
26563
+ if (turn.closed) return;
26564
+ turn.closed = true;
26565
+ const owned = this.live.get(turn.dshSessionId) === turn;
26566
+ if (owned) this.live.delete(turn.dshSessionId);
26567
+ this.activeTurns = Math.max(0, this.activeTurns - 1);
26568
+ turn.queue.close();
26569
+ if (parkAllowed && turn.parkable && owned) await this.park(turn);
26570
+ else await this.release(turn);
26505
26571
  }
26506
26572
  /**
26507
26573
  * Ask the agent to stop the prompt this turn left running.
@@ -26552,7 +26618,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26552
26618
  const queue = new UpdateQueue();
26553
26619
  try {
26554
26620
  if (entry.model !== options.model || entry.effort !== effort) await this.applyModelAndEffort(entry.client, entry.acpSessionId, options.model, effort);
26555
- this.attachHandlers(entry.client, queue, activity);
26621
+ this.attachHandlers(entry.client, queue, activity, { acpSessionId: entry.acpSessionId });
26556
26622
  const prompt = buildPrompt(options, images, entry.covered);
26557
26623
  const turn = {
26558
26624
  dshSessionId: entry.dshSessionId,
@@ -26572,7 +26638,8 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26572
26638
  awaitingHarness: false,
26573
26639
  sessionsUsed: entry.sessionsUsed,
26574
26640
  tools: entry.tools,
26575
- parkable: true
26641
+ parkable: true,
26642
+ closed: false
26576
26643
  };
26577
26644
  this.live.set(turn.dshSessionId, turn);
26578
26645
  this.activeTurns += 1;
@@ -26673,9 +26740,10 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26673
26740
  }
26674
26741
  }
26675
26742
  /** Re-install per-turn handlers on a reused client. */
26676
- attachHandlers(client, queue, activity) {
26743
+ attachHandlers(client, queue, activity, binding) {
26677
26744
  client.rebind({
26678
- onSessionUpdate: (_sessionId, update) => {
26745
+ onSessionUpdate: (sessionId, update) => {
26746
+ if (!ownsSession(binding, sessionId)) return;
26679
26747
  queue.push(update);
26680
26748
  activity.pulse();
26681
26749
  },
@@ -26914,16 +26982,6 @@ function needsAuth(error, authMethods) {
26914
26982
  const message = error instanceof Error ? error.message : String(error);
26915
26983
  return /authentication required/i.test(message) && authMethods.length > 0;
26916
26984
  }
26917
- function preferAuthMethod(authMethods) {
26918
- for (const candidate of [
26919
- "oauth-personal",
26920
- "terminal-login",
26921
- "oauth-business",
26922
- "gemini-api-key",
26923
- "agent-platform"
26924
- ]) if (authMethods.includes(candidate)) return candidate;
26925
- return authMethods[0] ?? "oauth-personal";
26926
- }
26927
26985
  function readUsage(raw) {
26928
26986
  const input = numberField(raw.inputTokens);
26929
26987
  const output = numberField(raw.outputTokens);
@@ -26938,6 +26996,15 @@ function readUsage(raw) {
26938
26996
  ...numberField(raw.totalTokens) === void 0 ? {} : { totalTokens: numberField(raw.totalTokens) }
26939
26997
  };
26940
26998
  }
26999
+ /**
27000
+ * Text that means the *service* declined the account rather than the agent failing.
27001
+ *
27002
+ * ACP carries upstream failures inside a JSON-RPC error message, so the sentence
27003
+ * is the only place that distinction survives. The list is deliberately about
27004
+ * what a user can act on - a quota, a policy or verification block, a rate limit -
27005
+ * and a match is reported as {@link ACP_UPSTREAM_BLOCKED}, which is not retried.
27006
+ */
27007
+ const UPSTREAM_DECLINED = /\b(?:429|403)\b|rate.?limit|too many requests|quota|resource[_ ]exhausted|terms of service|\btos\b|violat|valid(?:ation)?[_ ]required|permission[_ ]denied|account[_ ](?:disabled|suspended)|policy[_ ]violation|verification|verify your|unusual activity|risk|suspended|forbidden/i;
26941
27008
  function numberField(value) {
26942
27009
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
26943
27010
  }
@@ -26976,12 +27043,43 @@ function settleReason(stopReason) {
26976
27043
  };
26977
27044
  }
26978
27045
  }
27046
+ /**
27047
+ * Whether one `session/update` frame belongs to the turn reading right now.
27048
+ *
27049
+ * A reused process can still be flushing the conversation it ran before: the
27050
+ * `session/cancel` that ended it is a notification, not a barrier, and the process
27051
+ * is handed back to the pool without waiting for its prompt to settle. Those late
27052
+ * frames carry the old session id, and appending them would put another
27053
+ * conversation's text into this answer.
27054
+ *
27055
+ * The id decides whenever it is present. Two cases look similar and are not:
27056
+ *
27057
+ * - A frame that carries *no* id keeps the previous behaviour, because a server
27058
+ * that never repeats the id in a notification must still work - the id has
27059
+ * always been part of the ACP envelope rather than something this line added.
27060
+ * - A frame that names a session while this turn has not created one yet is a
27061
+ * leftover by construction: a warm process is checked out and rewired *before*
27062
+ * `session/new` answers, so anything addressed in that window can only belong
27063
+ * to the conversation it was running before. Keeping it "because we have no id
27064
+ * yet" was the hole in the first version of this filter.
27065
+ *
27066
+ * @param binding - The session this turn owns, once it exists.
27067
+ * @param sessionId - The id the frame carries, empty when it carried none.
27068
+ * @returns whether the frame belongs to this turn.
27069
+ */
27070
+ function ownsSession(binding, sessionId) {
27071
+ if (sessionId === "") return true;
27072
+ if (binding.acpSessionId === void 0) return false;
27073
+ return sessionId === binding.acpSessionId;
27074
+ }
26979
27075
  function asLlmError(error) {
26980
27076
  if (error instanceof LlmError) return error;
27077
+ if (error instanceof Error && error.name === "AbortError") return new LlmError("The Antigravity ACP turn was cancelled.", "ABORTED");
26981
27078
  if (error instanceof AcpError) {
26982
- if (error.code === -32e3) return acpError("ACP_AUTH_REQUIRED");
27079
+ if (error.code === -32e3 || /authentication required/i.test(error.message)) return acpError("ACP_AUTH_REQUIRED");
26983
27080
  if (error.code === -32602) return acpError("ACP_INVALID_PARAMS");
26984
27081
  if (error.code === -32601) return acpError("ACP_METHOD_UNSUPPORTED");
27082
+ if (UPSTREAM_DECLINED.test(error.message)) return acpError("ACP_UPSTREAM_BLOCKED", error.message);
26985
27083
  return acpError("ACP_RPC_ERROR", error.message);
26986
27084
  }
26987
27085
  const message = error instanceof Error ? error.message : String(error);
@@ -27230,7 +27328,7 @@ async function readCatalogFrom(client, signal) {
27230
27328
  version: "1.0.0"
27231
27329
  }
27232
27330
  }, signal));
27233
- const authMethods = Array.isArray(init?.authMethods) ? init.authMethods : [];
27331
+ const authMethods = Array.isArray(init?.authMethods) ? init.authMethods.map((entry) => String(entry.id ?? "")).filter((id) => id !== "") : [];
27234
27332
  const create = async () => {
27235
27333
  const value = asRecord$18(await client.request("session/new", {
27236
27334
  cwd: process.cwd(),
@@ -27245,7 +27343,7 @@ async function readCatalogFrom(client, signal) {
27245
27343
  } catch (error) {
27246
27344
  const message = error instanceof Error ? error.message : String(error);
27247
27345
  if (!/authentication required/i.test(message) || authMethods.length === 0) throw error;
27248
- await client.request("authenticate", { methodId: "oauth-personal" }, signal);
27346
+ await client.request("authenticate", { methodId: preferAuthMethod(authMethods) }, signal);
27249
27347
  session = await create();
27250
27348
  }
27251
27349
  const availableModels = readAvailableModels(asRecord$18(session.models)?.availableModels ?? session.availableModels);
@@ -27400,6 +27498,8 @@ const ACP_BINARY_RELEASES = {
27400
27498
  executable: "agy_acp_server.par"
27401
27499
  }
27402
27500
  };
27501
+ /** How long a resolved executable is reused before the disk is read again. */
27502
+ const BINARY_CACHE_TTL_MS = 5 * 6e4;
27403
27503
  /** Candidate paths the local CLI may live at, most specific first. */
27404
27504
  function localCliCandidates(home, platform) {
27405
27505
  return (platform === "win32" ? [
@@ -27475,6 +27575,11 @@ async function resolveAcpBinary(configured, options = {}) {
27475
27575
  },
27476
27576
  diagnostics: { tried }
27477
27577
  };
27578
+ if (options.download === false) return { diagnostics: {
27579
+ tried,
27580
+ deferred: true,
27581
+ error: "No Antigravity CLI (agy) is installed yet. This line downloads the official ACP server the first time you start a turn, run the self-check, or press refresh."
27582
+ } };
27478
27583
  try {
27479
27584
  return {
27480
27585
  binary: {
@@ -27492,6 +27597,78 @@ async function resolveAcpBinary(configured, options = {}) {
27492
27597
  }
27493
27598
  }
27494
27599
  /**
27600
+ * A cached answer to "which executable may this line run?".
27601
+ *
27602
+ * Resolution touches the disk once per candidate and spawns `agy --version` to
27603
+ * prove the file answers, which is not something a page render should do. The
27604
+ * answer is therefore reused for a few minutes; a change of `binaryPath` and the
27605
+ * refresh click invalidate or force it.
27606
+ *
27607
+ * A cached *passive* answer is never served to an active caller: if the reading
27608
+ * was taken without permission to download and found nothing, a turn asking the
27609
+ * same question must still be allowed to fetch the release.
27610
+ */
27611
+ var AcpBinaryCache = class {
27612
+ resolve;
27613
+ now;
27614
+ ttlMs;
27615
+ value;
27616
+ fetchedAt = 0;
27617
+ withDownload = false;
27618
+ inflight;
27619
+ /** Whether the in-flight read is allowed to install. */
27620
+ inflightDownload = false;
27621
+ /**
27622
+ * @param resolve - Reads the real answer; called at most once per window.
27623
+ * @param now - Clock seam.
27624
+ * @param ttlMs - How long one answer stays valid.
27625
+ */
27626
+ constructor(resolve, now = Date.now, ttlMs = BINARY_CACHE_TTL_MS) {
27627
+ this.resolve = resolve;
27628
+ this.now = now;
27629
+ this.ttlMs = ttlMs;
27630
+ }
27631
+ /** The cached answer, when one is still valid. */
27632
+ peek() {
27633
+ if (this.value === void 0) return void 0;
27634
+ return this.now() - this.fetchedAt < this.ttlMs ? this.value : void 0;
27635
+ }
27636
+ /**
27637
+ * Read the resolution, reusing a valid answer or one in-flight read.
27638
+ *
27639
+ * @param options - `force` re-reads the disk; `download` allows fetching a release.
27640
+ * @returns The executable (when one was found) and what was tried.
27641
+ */
27642
+ async read(options = {}) {
27643
+ if (options.force !== true) {
27644
+ const cached = this.peek();
27645
+ if (cached !== void 0 && (options.download !== true || this.withDownload || cached.binary !== void 0)) return cached;
27646
+ }
27647
+ const download = options.download !== false;
27648
+ if (this.inflight !== void 0) {
27649
+ if (!(download && !this.inflightDownload)) return this.inflight;
27650
+ await this.inflight.catch(() => void 0);
27651
+ }
27652
+ const promise = this.resolve({ download }).then((value) => {
27653
+ this.value = value;
27654
+ this.fetchedAt = this.now();
27655
+ this.withDownload = download;
27656
+ return value;
27657
+ }).finally(() => {
27658
+ if (this.inflight === promise) this.inflight = void 0;
27659
+ });
27660
+ this.inflight = promise;
27661
+ this.inflightDownload = download;
27662
+ return promise;
27663
+ }
27664
+ /** Forget the answer, e.g. because the configured path just changed. */
27665
+ invalidate() {
27666
+ this.value = void 0;
27667
+ this.fetchedAt = 0;
27668
+ this.withDownload = false;
27669
+ }
27670
+ };
27671
+ /**
27495
27672
  * Download and extract one release.
27496
27673
  *
27497
27674
  * The archive is fetched whole (bounded), hashed, and only then extracted; an
@@ -27622,24 +27799,41 @@ function findEndOfCentralDirectory(bytes) {
27622
27799
  *
27623
27800
  * @module dsh-chatgpt-subscription/host/antigravity-acp/login
27624
27801
  */
27802
+ /** How long the login launcher may run before it is considered detached. */
27803
+ const LOGIN_LAUNCH_BUDGET_MS = 1e4;
27804
+ /**
27805
+ * How long a launcher is watched for a start-up failure before it is left alone.
27806
+ *
27807
+ * A successful sign-in keeps the process alive until the browser callback lands,
27808
+ * so this may not wait for the exit: it only has to catch the failures that
27809
+ * happen before the CLI ever gets going - an executable that cannot be spawned,
27810
+ * or a command line the CLI rejects.
27811
+ */
27812
+ const LOGIN_FAILURE_WINDOW_MS = 1e3;
27813
+ /** Most stderr kept for that failure sentence; a login banner is not a diagnostic. */
27814
+ const LOGIN_STDERR_CAP = 2e3;
27625
27815
  /**
27626
27816
  * Start the official sign-in.
27627
27817
  *
27628
- * The process is spawned detached and its stdout/stderr are drained: on a desktop
27629
- * it opens the browser and exits once the callback lands, on a headless host it
27630
- * prints the URL it would have opened. Either way this call returns as soon as
27631
- * the process exists - it never waits for the user.
27818
+ * The process is spawned detached: on a desktop it opens the browser and exits
27819
+ * once the callback lands, on a headless host it prints the URL it would have
27820
+ * opened. Either way this call never waits for the user.
27821
+ *
27822
+ * What it *does* wait for is the failure that happens before the CLI gets going.
27823
+ * The command line is `agy acp --login`, and a rejected command line, a
27824
+ * misconfigured path or a binary that cannot be spawned all exit (or error)
27825
+ * within milliseconds - and the previous version reported "sign-in started" for
27826
+ * every one of them while discarding the only sentence that explained it. The
27827
+ * launcher is therefore watched for {@link LOGIN_FAILURE_WINDOW_MS}: a spawn
27828
+ * error, or a non-zero exit that left stderr behind, is returned as the reason.
27632
27829
  *
27633
27830
  * @param launch - The resolved executable.
27634
- * @returns whether a process was started.
27831
+ * @returns whether a process was started, and why it was not.
27635
27832
  */
27636
27833
  function startLogin(launch) {
27834
+ let child;
27637
27835
  try {
27638
- const child = spawn(launch.command, [
27639
- ...launch.args.slice(0, -1),
27640
- "acp",
27641
- "--login"
27642
- ], {
27836
+ child = spawn(launch.command, [...launch.args, "--login"], {
27643
27837
  detached: true,
27644
27838
  stdio: [
27645
27839
  "ignore",
@@ -27648,15 +27842,57 @@ function startLogin(launch) {
27648
27842
  ],
27649
27843
  windowsHide: true
27650
27844
  });
27651
- child.stderr?.resume();
27652
- child.unref();
27653
- return { started: true };
27654
27845
  } catch (error) {
27655
- return {
27846
+ return Promise.resolve({
27656
27847
  started: false,
27657
27848
  error: error instanceof Error ? error.message : String(error)
27658
- };
27849
+ });
27659
27850
  }
27851
+ return watchLauncher(child);
27852
+ }
27853
+ /**
27854
+ * Watch one launcher through its start-up window.
27855
+ *
27856
+ * @param child - The detached sign-in process.
27857
+ * @returns whether it started, and the CLI's own explanation when it did not.
27858
+ */
27859
+ function watchLauncher(child) {
27860
+ let stderr = "";
27861
+ child.stderr?.setEncoding("utf8");
27862
+ child.stderr?.on("data", (chunk) => {
27863
+ if (stderr.length < LOGIN_STDERR_CAP) stderr += chunk.slice(0, LOGIN_STDERR_CAP - stderr.length);
27864
+ });
27865
+ child.unref();
27866
+ return new Promise((resolve) => {
27867
+ let settled = false;
27868
+ const settle = (result) => {
27869
+ if (settled) return;
27870
+ settled = true;
27871
+ clearTimeout(windowTimer);
27872
+ clearTimeout(detachTimer);
27873
+ resolve(result);
27874
+ };
27875
+ const detail = () => stderr.trim().split(/\r?\n/u).filter((line) => line !== "").slice(-3).join(" ");
27876
+ const failed = (reason) => ({
27877
+ started: false,
27878
+ error: detail() === "" ? reason : reason + ": " + detail()
27879
+ });
27880
+ const windowTimer = setTimeout(() => settle({ started: true }), LOGIN_FAILURE_WINDOW_MS);
27881
+ windowTimer.unref?.();
27882
+ const detachTimer = setTimeout(() => {
27883
+ child.stderr?.removeAllListeners("data");
27884
+ child.removeAllListeners();
27885
+ }, LOGIN_LAUNCH_BUDGET_MS);
27886
+ detachTimer.unref?.();
27887
+ child.once("error", (error) => settle(failed(error.message)));
27888
+ child.once("exit", (code, signal) => {
27889
+ if (code === 0 || signal !== null) {
27890
+ settle({ started: true });
27891
+ return;
27892
+ }
27893
+ settle(failed(`The Antigravity CLI exited with code ${String(code ?? "null")} before sign-in began.`));
27894
+ });
27895
+ });
27660
27896
  }
27661
27897
  /**
27662
27898
  * Ask the agent whether it currently holds usable credentials.
@@ -27749,20 +27985,27 @@ const MAX_BODY_BYTES$8 = 64 * 1024;
27749
27985
  * host restarted twice in an afternoon still shows a current list.
27750
27986
  */
27751
27987
  const CATALOG_FRESHNESS_MS = 1440 * 60 * 1e3;
27752
- /** Build the status payload the card renders. */
27753
- async function readStatus(options) {
27988
+ /**
27989
+ * Build the status payload the card renders.
27990
+ *
27991
+ * @param options - The line's live state and actions.
27992
+ * @param read - `fresh` when this read is a user action rather than a poll.
27993
+ * @returns The status the card renders.
27994
+ */
27995
+ async function readStatus(options, read = {}) {
27996
+ const fresh = read.fresh === true;
27754
27997
  const settings = await options.settings.read();
27755
27998
  if (!settings.enabled) return disabledStatus(settings);
27756
- const resolved = await options.resolveBinary().catch(() => ({ error: "The executable could not be resolved." }));
27999
+ const resolved = await options.resolveBinary({ fresh }).catch(() => ({ error: "The executable could not be resolved." }));
27757
28000
  const catalog = await options.catalog.rehydrate();
27758
- const auth = resolved.binary === void 0 ? { authenticated: false } : await options.auth().catch(() => ({ authenticated: false }));
28001
+ const auth = resolved.binary === void 0 ? { authenticated: false } : await options.auth({ force: fresh }).catch(() => ({ authenticated: false }));
27759
28002
  const models = catalog?.models ?? [];
27760
28003
  const conflict = options.conflict();
27761
28004
  return {
27762
28005
  enabled: settings.enabled,
27763
28006
  binary: resolved.binary === void 0 ? {
27764
28007
  kind: "missing",
27765
- ...resolved.error === void 0 ? {} : { error: missingBinaryMessage(resolved.error) }
28008
+ ...resolved.error === void 0 ? {} : { error: resolved.deferred === true ? resolved.error : missingBinaryMessage(resolved.error) }
27766
28009
  } : {
27767
28010
  kind: resolved.binary.kind,
27768
28011
  path: resolved.binary.path,
@@ -27846,11 +28089,12 @@ function registerAntigravityAcpRoutes(ctx, options) {
27846
28089
  if (!sameSettings(await options.settings.read(), await options.settings.update(update))) ctx.emit?.("llm/adapters-updated");
27847
28090
  if (update.binaryPath !== void 0) {
27848
28091
  options.catalog.invalidate();
28092
+ options.invalidateBinary?.();
27849
28093
  await options.catalog.read({ force: true }).catch(() => void 0);
27850
28094
  }
27851
28095
  return sendJson$10(response, 200, {
27852
28096
  ok: true,
27853
- value: await readStatus(options)
28097
+ value: await readStatus(options, { fresh: true })
27854
28098
  });
27855
28099
  }
27856
28100
  if (path === "login/start") {
@@ -27873,7 +28117,7 @@ function registerAntigravityAcpRoutes(ctx, options) {
27873
28117
  if (method !== "GET") return sendMethodNotAllowed$9(response);
27874
28118
  return sendJson$10(response, 200, {
27875
28119
  ok: true,
27876
- value: await options.auth()
28120
+ value: await options.auth({ force: true })
27877
28121
  });
27878
28122
  }
27879
28123
  if (path === "logout") {
@@ -27919,6 +28163,7 @@ function registerAntigravityAcpRoutes(ctx, options) {
27919
28163
  ok: false,
27920
28164
  error: "Cross-origin request rejected."
27921
28165
  });
28166
+ options.invalidateBinary?.();
27922
28167
  const refreshed = await options.catalog.read({ force: true }).catch(() => void 0);
27923
28168
  await options.auth({ force: true }).catch(() => void 0);
27924
28169
  if (refreshed === void 0) return sendJson$10(response, 502, {
@@ -27927,7 +28172,7 @@ function registerAntigravityAcpRoutes(ctx, options) {
27927
28172
  });
27928
28173
  return sendJson$10(response, 200, {
27929
28174
  ok: true,
27930
- value: await readStatus(options)
28175
+ value: await readStatus(options, { fresh: true })
27931
28176
  });
27932
28177
  }
27933
28178
  return sendJson$10(response, 404, {
@@ -28015,8 +28260,17 @@ async function readRequestJson$10(request) {
28015
28260
  }
28016
28261
  //#endregion
28017
28262
  //#region src/host/antigravity-acp/auth-cache.ts
28018
- /** How long one probe answers for. */
28019
- const AUTH_CACHE_TTL_MS = 6e4;
28263
+ /**
28264
+ * How long one probe answers for.
28265
+ *
28266
+ * Ten minutes, not one. A probe is a whole `agy` process plus a `session/new`
28267
+ * against Google, and the card, the hub overview and the composer badge each poll
28268
+ * this route - at a one-minute window that was a process launch per minute for a
28269
+ * question whose answer changes only when the user signs in or out. Those two
28270
+ * events are exactly what invalidates the cache (`login/start`, `login/status`,
28271
+ * the refresh click), so the window does not delay a real state change.
28272
+ */
28273
+ const AUTH_CACHE_TTL_MS = 10 * 6e4;
28020
28274
  /** The cache itself. */
28021
28275
  var AcpAuthCache = class {
28022
28276
  probe;
@@ -28196,10 +28450,12 @@ function registerAntigravityAcpSubagent(ctx, options) {
28196
28450
  * working directory, and that is all.
28197
28451
  */
28198
28452
  function createProvider(options) {
28453
+ const cap = options.maxActiveRuns ?? 4;
28454
+ let active = 0;
28199
28455
  return {
28200
28456
  name: SUBAGENT_PROVIDER_NAME,
28201
28457
  capabilities: {
28202
- agentOptions: false,
28458
+ agentOptions: true,
28203
28459
  agentPreset: false,
28204
28460
  outputSchema: false,
28205
28461
  depthLimit: false
@@ -28208,27 +28464,44 @@ function createProvider(options) {
28208
28464
  async start(request) {
28209
28465
  const settings = await options.settings.read();
28210
28466
  if (!settings.enabled) throw new LlmError$1("The Antigravity (ACP) line is switched off. Enable it in the subscription overview before delegating to it.", "ACP_DISABLED");
28211
- const launch = await options.resolveLaunch();
28212
- const task = promptText(request.prompt);
28213
- let settled = false;
28214
- const running = startRun(launch, request.cwd, task, settings.permissionPolicy, options, request.signal);
28215
- return {
28216
- id: SUBAGENT_PROVIDER_NAME,
28217
- result: running.result,
28218
- dispose: async () => {
28219
- if (settled) return;
28220
- settled = true;
28221
- running.settle({
28222
- output: running.output(),
28223
- stopReason: "aborted"
28224
- });
28225
- await running.client.dispose().catch(() => void 0);
28226
- }
28467
+ if (active >= cap) throw acpError("ACP_SESSION_LIMIT", `${active} delegated runs are already in flight (limit ${cap}).`);
28468
+ active += 1;
28469
+ let released = false;
28470
+ const release = () => {
28471
+ if (released) return;
28472
+ released = true;
28473
+ active = Math.max(0, active - 1);
28227
28474
  };
28475
+ try {
28476
+ const launch = await options.resolveLaunch();
28477
+ const task = promptText(request.prompt);
28478
+ let settled = false;
28479
+ const running = startRun(launch, request.cwd, task, settings.permissionPolicy, options, request);
28480
+ running.result.then(release, release);
28481
+ return {
28482
+ id: SUBAGENT_PROVIDER_NAME,
28483
+ result: running.result,
28484
+ dispose: async () => {
28485
+ if (settled) return;
28486
+ settled = true;
28487
+ running.settle({
28488
+ output: running.output(),
28489
+ stopReason: "aborted"
28490
+ });
28491
+ await running.client.dispose().catch(() => void 0);
28492
+ }
28493
+ };
28494
+ } catch (error) {
28495
+ release();
28496
+ throw error;
28497
+ }
28228
28498
  }
28229
28499
  };
28230
28500
  }
28231
- function startRun(launch, cwd, task, permissionPolicy, options, signal) {
28501
+ function startRun(launch, cwd, task, permissionPolicy, options, request) {
28502
+ const signal = request.signal;
28503
+ const model = textField(request.agentOptions?.model);
28504
+ const effort = textField(request.agentOptions?.reasoningEffort);
28232
28505
  let settle = () => void 0;
28233
28506
  const result = new Promise((resolve) => {
28234
28507
  settle = resolve;
@@ -28296,6 +28569,16 @@ function startRun(launch, cwd, task, permissionPolicy, options, signal) {
28296
28569
  }));
28297
28570
  const sessionId = typeof session?.sessionId === "string" ? session.sessionId : void 0;
28298
28571
  if (sessionId === void 0) throw new Error("Antigravity ACP did not return a session id.");
28572
+ if (model !== void 0) await client.request("session/set_config_option", {
28573
+ sessionId,
28574
+ configId: "model",
28575
+ value: model
28576
+ });
28577
+ if (effort !== void 0) await client.request("session/set_config_option", {
28578
+ sessionId,
28579
+ configId: "thought_level",
28580
+ value: effort
28581
+ }).catch(() => void 0);
28299
28582
  const answer = asRecord$16(await withTimeout$11(client.request("session/prompt", {
28300
28583
  sessionId,
28301
28584
  prompt: [{
@@ -28333,6 +28616,10 @@ function startRun(launch, cwd, task, permissionPolicy, options, signal) {
28333
28616
  output
28334
28617
  };
28335
28618
  }
28619
+ /** A non-empty string, or undefined; the host's own values are untrusted input here. */
28620
+ function textField(value) {
28621
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
28622
+ }
28336
28623
  /** Flatten the prompt blocks a caller supplied into the one text the agent gets. */
28337
28624
  function promptText(prompt) {
28338
28625
  const parts = [];
@@ -105594,8 +105881,11 @@ function apply(ctx, pluginConfig = {}) {
105594
105881
  attachments: ctx.attachments
105595
105882
  }, ollamaAccountPool);
105596
105883
  const antigravityAcpSettings = new AntigravityAcpSettingsStore();
105884
+ const antigravityAcpBinary = new AcpBinaryCache(async (options) => {
105885
+ return resolveAcpBinary((await antigravityAcpSettings.read()).binaryPath, { download: options.download !== false });
105886
+ });
105597
105887
  const resolveAntigravityLaunch = async () => {
105598
- const resolved = await resolveAcpBinary((await antigravityAcpSettings.read()).binaryPath);
105888
+ const resolved = await antigravityAcpBinary.read({ download: true });
105599
105889
  if (resolved.binary === void 0) throw new Error(resolved.diagnostics.error ?? "No usable Antigravity CLI (agy) was found.");
105600
105890
  return {
105601
105891
  command: resolved.binary.path,
@@ -105621,7 +105911,15 @@ function apply(ctx, pluginConfig = {}) {
105621
105911
  attachments: ctx.attachments
105622
105912
  });
105623
105913
  antigravityAcpCatalog.rehydrate().catch(() => void 0);
105624
- const antigravityAcpAuth = new AcpAuthCache(() => probeAuthWithLaunch(resolveAntigravityLaunch));
105914
+ const antigravityAcpAuth = new AcpAuthCache(() => probeAuthWithLaunch(async () => {
105915
+ const resolved = await antigravityAcpBinary.read({ download: false });
105916
+ if (resolved.binary === void 0) throw new Error(resolved.diagnostics.error ?? "No usable Antigravity CLI (agy) was found.");
105917
+ return {
105918
+ command: resolved.binary.path,
105919
+ args: ["acp", "--disable-telemetry"],
105920
+ version: resolved.binary.version
105921
+ };
105922
+ }));
105625
105923
  const kimiCodeClaim = claimProviderRoute(ctx, {
105626
105924
  providerId: PROVIDER_ID$9,
105627
105925
  label: PROVIDER_NAME$8,
@@ -105654,16 +105952,18 @@ function apply(ctx, pluginConfig = {}) {
105654
105952
  const disposeAntigravityAcpRoutes = registerAntigravityAcpRoutes(ctx, {
105655
105953
  settings: antigravityAcpSettings,
105656
105954
  catalog: antigravityAcpCatalog,
105657
- resolveBinary: async () => {
105658
- const resolved = await resolveAcpBinary((await antigravityAcpSettings.read()).binaryPath);
105955
+ resolveBinary: async (options) => {
105956
+ const resolved = await antigravityAcpBinary.read({ download: options?.fresh === true });
105659
105957
  return {
105660
105958
  binary: resolved.binary,
105661
- error: resolved.diagnostics.error
105959
+ error: resolved.diagnostics.error,
105960
+ deferred: resolved.diagnostics.deferred === true
105662
105961
  };
105663
105962
  },
105963
+ invalidateBinary: () => antigravityAcpBinary.invalidate(),
105664
105964
  login: async () => {
105665
105965
  try {
105666
- const started = startLogin(await resolveAntigravityLaunch());
105966
+ const started = await startLogin(await resolveAntigravityLaunch());
105667
105967
  antigravityAcpAuth.invalidate();
105668
105968
  return started;
105669
105969
  } catch (error) {
@@ -105678,7 +105978,7 @@ function apply(ctx, pluginConfig = {}) {
105678
105978
  occupancy: () => antigravityAcpAdapter.occupancy(),
105679
105979
  runDoctor: () => runDoctor({
105680
105980
  resolveBinary: async () => {
105681
- const resolved = await resolveAcpBinary((await antigravityAcpSettings.read()).binaryPath);
105981
+ const resolved = await antigravityAcpBinary.read({ download: true });
105682
105982
  return resolved.binary === void 0 ? { error: resolved.diagnostics.error } : {
105683
105983
  path: resolved.binary.path,
105684
105984
  version: resolved.binary.version,