@eddyskywalker/dsh-chatgpt-subscription 0.74.0 → 0.75.0

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/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.74.0";
820
+ const PLUGIN_VERSION = "0.75.0";
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`;
@@ -25298,9 +25298,10 @@ function acpError(code, detail) {
25298
25298
  * that history is the only transcript the model may rely on.
25299
25299
  * - **An existing ACP session** is fed only the messages DSH added since the
25300
25300
  * last prompt, because the agent already has the rest.
25301
- * - A mismatch (compaction, an edited turn, a different model) means the ACP
25301
+ * - A mismatch (compaction, an edited turn, a rewritten prefix) means the ACP
25302
25302
  * transcript can no longer be trusted as a prefix of DSH's: the session is
25303
- * abandoned and replayed in full.
25303
+ * abandoned and replayed in full, behind a history boundary marker. A different
25304
+ * model is not a mismatch - it is a config option of the same conversation.
25304
25305
  *
25305
25306
  * The fingerprint is an HMAC-style digest rather than a stored transcript: it
25306
25307
  * costs one hash per message and never keeps a second copy of user content.
@@ -25310,6 +25311,28 @@ function acpError(code, detail) {
25310
25311
  /** ACP's own image ceiling per content block. */
25311
25312
  const ACP_MAX_INLINE_IMAGE_BYTES = 12 * 1024 * 1024;
25312
25313
  /**
25314
+ * The sentence every replayed transcript ends with.
25315
+ *
25316
+ * ACP has no notion of "this is the current task". A session created now and fed
25317
+ * a hundred messages is one long prompt, and a transcript that reads like a stack
25318
+ * of outstanding requests is exactly how a long session ends up redoing its first
25319
+ * request: the user writes "go with A" and the agent, reading a wall of earlier
25320
+ * instructions, starts over on the first one. The anchor marks where the history
25321
+ * ends and which line the turn is about.
25322
+ *
25323
+ * It is appended to a *replay* only. A fresh session's first prompt already ends
25324
+ * with the request it is answering, and a boundary sentence there would be noise
25325
+ * on every cold start.
25326
+ */
25327
+ const REPLAY_ANCHOR_INSTRUCTION = [
25328
+ "[history boundary]",
25329
+ "Everything above this line is earlier conversation, replayed to you for context only.",
25330
+ "The current request is the LAST user message in that history.",
25331
+ "Do not re-run, re-answer or re-dispatch work an earlier message already asked for; completed requests are completed.",
25332
+ "A short reference such as \"do that\" or \"go with A\" points at the assistant message immediately before it.",
25333
+ "Model names, providers and routing mentioned in older turns describe the turn they ran on, not the one you are answering now."
25334
+ ].join(" ");
25335
+ /**
25313
25336
  * Build the prompt for one generation.
25314
25337
  *
25315
25338
  * @param options - Normalized request options.
@@ -25330,6 +25353,10 @@ function buildPrompt(options, images, fromMessage) {
25330
25353
  return inlineBytes <= ACP_MAX_INLINE_IMAGE_BYTES;
25331
25354
  });
25332
25355
  }
25356
+ if (start === 0 && messages.some((message) => message.role === "assistant")) blocks.push({
25357
+ type: "text",
25358
+ text: REPLAY_ANCHOR_INSTRUCTION
25359
+ });
25333
25360
  return {
25334
25361
  blocks,
25335
25362
  coveredMessages: messages.length,
@@ -25362,6 +25389,35 @@ function fingerprintMessages(messages, from, to) {
25362
25389
  return hash.digest("hex");
25363
25390
  }
25364
25391
  /**
25392
+ * Digest over the tool catalogue an ACP session's bridge exposes.
25393
+ *
25394
+ * The catalogue is fixed when the session is created: the agent listed it once,
25395
+ * and the bridge answers `listChanged: false`, so a session resumed after the
25396
+ * harness's tool set changed would keep offering the old schemas to the agent. The
25397
+ * digest is therefore part of "may this session be reused", and a changed
25398
+ * catalogue forces a fresh session.
25399
+ *
25400
+ * @param tools - The tool schemas of one request.
25401
+ * @returns Hex digest; one catalogue always produces one value.
25402
+ */
25403
+ function fingerprintTools(tools) {
25404
+ const hash = createHash("sha256");
25405
+ const entries = (tools ?? []).map((tool) => ({
25406
+ name: tool.name,
25407
+ description: tool.description ?? "",
25408
+ parameters: JSON.stringify(tool.parameters ?? {})
25409
+ })).sort((left, right) => left.name === right.name ? 0 : left.name < right.name ? -1 : 1);
25410
+ for (const entry of entries) {
25411
+ hash.update(entry.name);
25412
+ hash.update("\0");
25413
+ hash.update(entry.description);
25414
+ hash.update("\0");
25415
+ hash.update(entry.parameters);
25416
+ hash.update("");
25417
+ }
25418
+ return hash.digest("hex");
25419
+ }
25420
+ /**
25365
25421
  * Whether `messages` still begins with everything a live ACP session has seen.
25366
25422
  *
25367
25423
  * @param messages - The history about to be sent.
@@ -25602,12 +25658,22 @@ function missingBinaryMessage(detail) {
25602
25658
  * This class therefore keeps a *live turn* per DSH session: the ACP session, the
25603
25659
  * bridge, and how much history that turn has already been told about.
25604
25660
  *
25605
- * Every other generation starts a fresh ACP session fed the complete DSH
25606
- * history. That is deliberately conservative: ACP sessions are stateful and
25607
- * resuming one would save a prefill, but the harness may compact or rewrite
25608
- * history at any point, and a resumed session whose transcript no longer matches
25609
- * the harness's would be a conversation the user cannot audit. The history module
25610
- * can tell the two apart; a fresh session is the honest default.
25661
+ * A turn that ends without a tool round does not lose its ACP session: it is
25662
+ * parked *dormant* together with the process it runs on, and the next user
25663
+ * message on the same DSH session is sent as an increment on that same
25664
+ * conversation. That is worth more than the prefill it saves. A session created
25665
+ * per message hands a thinking model a hundred-message transcript and hopes it
25666
+ * picks out the newest line; the observed failure was a model re-running the
25667
+ * conversation's *first* request when the user wrote "go with option A".
25668
+ *
25669
+ * Reuse is never assumed. The prefix the agent was told about must still match
25670
+ * the harness's history (the history module's fingerprint), the tool catalogue
25671
+ * the bridge exposed must be unchanged, and a different model or effort is
25672
+ * applied with `session/set_config_option` on the same conversation. A
25673
+ * compaction, an edited turn, a new tool set, a dead process, or a refused
25674
+ * reconfiguration all fall back to a fresh session fed the complete history - and
25675
+ * that replay ends with a history boundary marker, so it is read as a transcript
25676
+ * rather than as a task list.
25611
25677
  *
25612
25678
  * Where the tool calls come from
25613
25679
  * ------------------------------
@@ -25687,6 +25753,8 @@ var UpdateQueue = class {
25687
25753
  var AntigravityAcpAdapter = class extends LlmAdapter {
25688
25754
  options;
25689
25755
  live = /* @__PURE__ */ new Map();
25756
+ /** Finished sessions, keyed by DSH session, waiting for the next user message. */
25757
+ dormant = /* @__PURE__ */ new Map();
25690
25758
  idle = [];
25691
25759
  activeTurns = 0;
25692
25760
  lastUsage;
@@ -25720,9 +25788,9 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
25720
25788
  return this.lastOccupancy;
25721
25789
  }
25722
25790
  async listModels(provider) {
25723
- const view = await this.options.loadCatalog().catch(() => void 0);
25724
25791
  const settings = await this.options.settings.read();
25725
25792
  if (!settings.enabled) return [];
25793
+ const view = await this.options.loadCatalog().catch(() => void 0);
25726
25794
  return this.visibleModels(view?.models ?? [], settings).map((model) => toModelInfo(provider, model));
25727
25795
  }
25728
25796
  async resolveModel(provider, model, signal) {
@@ -25739,12 +25807,20 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
25739
25807
  }
25740
25808
  /** Close every process this adapter owns. */
25741
25809
  async dispose() {
25810
+ for (const entry of [...this.dormant.values()]) await this.closeDormant(entry);
25811
+ for (const turn of [...this.live.values()]) {
25812
+ if (this.live.get(turn.dshSessionId) === turn) this.live.delete(turn.dshSessionId);
25813
+ this.activeTurns = Math.max(0, this.activeTurns - 1);
25814
+ turn.queue.close();
25815
+ this.cancelTurn(turn);
25816
+ await turn.bridge.close().catch(() => void 0);
25817
+ await turn.client.dispose().catch(() => void 0);
25818
+ }
25819
+ this.live.clear();
25742
25820
  for (const entry of this.idle.splice(0)) {
25743
25821
  clearTimeout(entry.timer);
25744
25822
  await entry.client.dispose().catch(() => void 0);
25745
25823
  }
25746
- for (const turn of [...this.live.values()]) await this.closeTurn(turn);
25747
- this.live.clear();
25748
25824
  }
25749
25825
  /**
25750
25826
  * Resolve which turn this generation belongs to, then hand back its stream.
@@ -25766,10 +25842,16 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
25766
25842
  const live = this.live.get(dshSessionId);
25767
25843
  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);
25768
25844
  if (live !== void 0) await this.closeTurn(live);
25769
- return this.startTurn(dshSessionId, options, settings, images, effort, signal, activity);
25845
+ const auxiliary = options.purpose !== void 0;
25846
+ const dormant = auxiliary ? void 0 : this.dormant.get(dshSessionId);
25847
+ if (dormant !== void 0) if (this.usableDormant(dormant, options)) {
25848
+ const resumed = await this.resumeDormant(dormant, options, settings, effort, images, signal, activity);
25849
+ if (resumed !== void 0) return resumed;
25850
+ } else await this.closeDormant(dormant);
25851
+ return this.startTurn(dshSessionId, options, settings, images, effort, signal, activity, !auxiliary);
25770
25852
  }
25771
25853
  /** Start a fresh ACP session for one generation and stream its answer. */
25772
- async startTurn(dshSessionId, options, settings, images, effort, signal, activity) {
25854
+ async startTurn(dshSessionId, options, settings, images, effort, signal, activity, parkable) {
25773
25855
  const limit = this.options.maxActiveTurns ?? 4;
25774
25856
  if (this.activeTurns >= limit) throw new LlmError(`${PROVIDER_NAME$9} already has ${this.activeTurns} turns in flight; wait for one to finish before starting another.`, "RATE_LIMIT");
25775
25857
  this.activeTurns += 1;
@@ -25809,7 +25891,9 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
25809
25891
  nativeToolPolicy: settings.nativeToolPolicy,
25810
25892
  startedAt: this.now(),
25811
25893
  awaitingHarness: false,
25812
- sessionsUsed: reusedSessions + 1
25894
+ sessionsUsed: reusedSessions + 1,
25895
+ tools: fingerprintTools(options.tools),
25896
+ parkable
25813
25897
  };
25814
25898
  this.live.set(dshSessionId, turn);
25815
25899
  this.sendPrompt(turn, prompt.blocks);
@@ -26034,13 +26118,12 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26034
26118
  ]);
26035
26119
  }
26036
26120
  } finally {
26037
- if (!finished) {
26038
- if (turn.awaitingHarness) {}
26039
- await this.closeTurn(turn);
26040
- } else if (!turn.awaitingHarness && this.live.get(turn.dshSessionId) === turn) {
26121
+ if (!finished) await this.closeTurn(turn);
26122
+ else if (!turn.awaitingHarness && this.live.get(turn.dshSessionId) === turn) {
26041
26123
  this.live.delete(turn.dshSessionId);
26042
26124
  this.activeTurns = Math.max(0, this.activeTurns - 1);
26043
- await this.release(turn);
26125
+ if (turn.parkable) await this.park(turn);
26126
+ else await this.release(turn);
26044
26127
  }
26045
26128
  }
26046
26129
  }
@@ -26196,12 +26279,164 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26196
26279
  turn.queue.push({ sessionUpdate: "prompt_settled" });
26197
26280
  }
26198
26281
  }
26282
+ /**
26283
+ * Abandon one live turn.
26284
+ *
26285
+ * The turn cannot be resumed by the harness any more, so its prompt is cancelled
26286
+ * and its process is handed back to the pool. Disposing the process instead -
26287
+ * what this used to do - made every cancellation pay a fresh spawn and the
26288
+ * agent's own start-up wait on the next message.
26289
+ */
26199
26290
  async closeTurn(turn) {
26200
26291
  if (this.live.get(turn.dshSessionId) === turn) this.live.delete(turn.dshSessionId);
26201
26292
  this.activeTurns = Math.max(0, this.activeTurns - 1);
26202
26293
  turn.queue.close();
26203
- await turn.bridge.close().catch(() => void 0);
26204
- await turn.client.dispose().catch(() => void 0);
26294
+ this.cancelTurn(turn);
26295
+ await this.release(turn);
26296
+ }
26297
+ /**
26298
+ * Ask the agent to stop the prompt this turn left running.
26299
+ *
26300
+ * `session/cancel` is an ACP notification, not a request, so it is written
26301
+ * without waiting for an answer: a prompt that already settled ignores it, and a
26302
+ * client that waited would hang on a server that never replies.
26303
+ */
26304
+ cancelTurn(turn) {
26305
+ if (!turn.client.alive) return;
26306
+ turn.client.notify("session/cancel", { sessionId: turn.acpSessionId });
26307
+ }
26308
+ /**
26309
+ * Whether the parked session is still a prefix of the history about to be sent.
26310
+ *
26311
+ * Three questions, and every one of them must answer yes: the process is alive,
26312
+ * the bridge still exposes the tool catalogue the agent listed (the bridge
26313
+ * publishes no change feed, so a different set cannot reach a resumed session),
26314
+ * and the harness history still begins with exactly what the agent was told.
26315
+ *
26316
+ * @param entry - The parked session.
26317
+ * @param options - The generation about to run.
26318
+ */
26319
+ usableDormant(entry, options) {
26320
+ if (!entry.client.alive) return false;
26321
+ if (entry.tools !== fingerprintTools(options.tools)) return false;
26322
+ return canContinue(options.messages, entry.covered, entry.fingerprint);
26323
+ }
26324
+ /**
26325
+ * Continue a parked session with only what the harness added since.
26326
+ *
26327
+ * @param entry - The parked session to reuse.
26328
+ * @param options - The generation about to run.
26329
+ * @param settings - This line's own preferences, read for the native-tool policy.
26330
+ * @param effort - The thinking level this generation asked for.
26331
+ * @param images - Images resolved for this request.
26332
+ * @param signal - Caller cancellation.
26333
+ * @param activity - Watchdog pulse.
26334
+ * @returns the stream, or undefined when the session could not be reused. On
26335
+ * that path the process has already been handed back, so the caller starts a
26336
+ * cold turn rather than failing the generation.
26337
+ */
26338
+ async resumeDormant(entry, options, settings, effort, images, signal, activity) {
26339
+ const limit = this.options.maxActiveTurns ?? 4;
26340
+ if (this.activeTurns >= limit) return void 0;
26341
+ this.dormant.delete(entry.dshSessionId);
26342
+ if (entry.timer !== void 0) clearTimeout(entry.timer);
26343
+ const queue = new UpdateQueue();
26344
+ try {
26345
+ if (entry.model !== options.model || entry.effort !== effort) await this.applyModelAndEffort(entry.client, entry.acpSessionId, options.model, effort);
26346
+ this.attachHandlers(entry.client, queue, activity);
26347
+ const prompt = buildPrompt(options, images, entry.covered);
26348
+ const turn = {
26349
+ dshSessionId: entry.dshSessionId,
26350
+ client: entry.client,
26351
+ bridge: entry.bridge,
26352
+ acpSessionId: entry.acpSessionId,
26353
+ covered: prompt.coveredMessages,
26354
+ fingerprint: prompt.fingerprint,
26355
+ model: options.model,
26356
+ effort,
26357
+ queue,
26358
+ settled: void 0,
26359
+ surfaced: /* @__PURE__ */ new Set(),
26360
+ notedNative: /* @__PURE__ */ new Set(),
26361
+ nativeToolPolicy: settings.nativeToolPolicy,
26362
+ startedAt: this.now(),
26363
+ awaitingHarness: false,
26364
+ sessionsUsed: entry.sessionsUsed,
26365
+ tools: entry.tools,
26366
+ parkable: true
26367
+ };
26368
+ this.live.set(turn.dshSessionId, turn);
26369
+ this.activeTurns += 1;
26370
+ this.sendPrompt(turn, prompt.blocks);
26371
+ return this.pump(turn, signal, activity);
26372
+ } catch {
26373
+ queue.close();
26374
+ await this.release({
26375
+ client: entry.client,
26376
+ bridge: entry.bridge,
26377
+ sessionsUsed: entry.sessionsUsed
26378
+ });
26379
+ return;
26380
+ }
26381
+ }
26382
+ /**
26383
+ * Keep a finished turn's session ready for the next user message.
26384
+ *
26385
+ * The bridge stays open on purpose: its endpoint is what the parked session's
26386
+ * tool list points at, and closing it would leave the agent calling a port
26387
+ * nobody answers.
26388
+ */
26389
+ async park(turn) {
26390
+ turn.queue.close();
26391
+ const limit = this.options.dormantSessionLimit ?? 2;
26392
+ if (limit <= 0 || !turn.client.alive) {
26393
+ await this.release(turn);
26394
+ return;
26395
+ }
26396
+ const previous = this.dormant.get(turn.dshSessionId);
26397
+ if (previous !== void 0) await this.closeDormant(previous);
26398
+ const entry = {
26399
+ dshSessionId: turn.dshSessionId,
26400
+ client: turn.client,
26401
+ bridge: turn.bridge,
26402
+ acpSessionId: turn.acpSessionId,
26403
+ covered: turn.covered,
26404
+ fingerprint: turn.fingerprint,
26405
+ tools: turn.tools,
26406
+ model: turn.model,
26407
+ effort: turn.effort,
26408
+ sessionsUsed: turn.sessionsUsed,
26409
+ timer: void 0
26410
+ };
26411
+ const timer = setTimeout(() => {
26412
+ this.closeDormant(entry);
26413
+ }, this.options.dormantSessionTimeoutMs ?? 3e5);
26414
+ timer.unref?.();
26415
+ entry.timer = timer;
26416
+ this.dormant.set(turn.dshSessionId, entry);
26417
+ while (this.dormant.size > limit) {
26418
+ const oldest = this.dormant.values().next().value;
26419
+ if (oldest === void 0) break;
26420
+ await this.closeDormant(oldest);
26421
+ }
26422
+ }
26423
+ /**
26424
+ * Drop a parked session and hand its process back to the pool.
26425
+ *
26426
+ * The conversation itself is abandoned rather than closed with `session/close`:
26427
+ * not every agent version this line supports answers that request, and a request
26428
+ * that never settles would occupy one of the client's protocol slots for the
26429
+ * life of the process. The next turn opens a fresh conversation on the same warm
26430
+ * process.
26431
+ */
26432
+ async closeDormant(entry) {
26433
+ if (this.dormant.get(entry.dshSessionId) === entry) this.dormant.delete(entry.dshSessionId);
26434
+ if (entry.timer !== void 0) clearTimeout(entry.timer);
26435
+ await this.release({
26436
+ client: entry.client,
26437
+ bridge: entry.bridge,
26438
+ sessionsUsed: entry.sessionsUsed
26439
+ });
26205
26440
  }
26206
26441
  /**
26207
26442
  * Take one warm process out of the pool.
@@ -26248,12 +26483,14 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26248
26483
  onActivity: () => activity.pulse()
26249
26484
  });
26250
26485
  }
26486
+ /** Hand one turn's process back to the idle pool, disposing it when it is spent. */
26251
26487
  async release(turn) {
26252
- turn.queue.close();
26488
+ turn.queue?.close();
26253
26489
  await turn.bridge.close().catch(() => void 0);
26254
26490
  const limit = this.options.idleProcessLimit ?? 2;
26255
26491
  const cap = this.options.maxSessionsPerProcess ?? 100;
26256
- if (limit <= 0 || !turn.client.alive || turn.sessionsUsed >= cap) {
26492
+ const sessionsUsed = turn.sessionsUsed ?? 1;
26493
+ if (limit <= 0 || !turn.client.alive || sessionsUsed >= cap) {
26257
26494
  await turn.client.dispose().catch(() => void 0);
26258
26495
  return;
26259
26496
  }
@@ -26267,7 +26504,7 @@ var AntigravityAcpAdapter = class extends LlmAdapter {
26267
26504
  this.idle.push({
26268
26505
  client,
26269
26506
  timer,
26270
- sessions: turn.sessionsUsed ?? 1
26507
+ sessions: sessionsUsed
26271
26508
  });
26272
26509
  while (this.idle.length > limit) {
26273
26510
  const oldest = this.idle.shift();
@@ -26727,7 +26964,7 @@ var AcpCatalog = class {
26727
26964
  */
26728
26965
  async read(options = {}) {
26729
26966
  const current = this.cached ?? await this.rehydrate();
26730
- if (!options.force && current !== void 0 && this.now() - current.fetchedAt < 6e4) return current;
26967
+ if (!options.force && current !== void 0 && this.now() - current.fetchedAt < 9e5) return current;
26731
26968
  if (this.inflight !== void 0) return this.inflight;
26732
26969
  this.inflight = this.refresh(options.signal).catch(() => current).finally(() => {
26733
26970
  this.inflight = void 0;
@@ -27306,6 +27543,7 @@ const CATALOG_FRESHNESS_MS = 1440 * 60 * 1e3;
27306
27543
  /** Build the status payload the card renders. */
27307
27544
  async function readStatus(options) {
27308
27545
  const settings = await options.settings.read();
27546
+ if (!settings.enabled) return disabledStatus(settings);
27309
27547
  const resolved = await options.resolveBinary().catch(() => ({ error: "The executable could not be resolved." }));
27310
27548
  const catalog = await options.catalog.rehydrate();
27311
27549
  const auth = resolved.binary === void 0 ? { authenticated: false } : await options.auth().catch(() => ({ authenticated: false }));
@@ -27334,6 +27572,32 @@ async function readStatus(options) {
27334
27572
  };
27335
27573
  }
27336
27574
  /**
27575
+ * The whole status payload for a line the user switched off.
27576
+ *
27577
+ * Deliberately answered without touching the agent: the executable is not
27578
+ * resolved, the sign-in is not probed and the catalogue snapshot is not read, so
27579
+ * a disabled line costs nothing but one file read. The model rows are kept as an
27580
+ * empty list rather than the cached catalogue on purpose - a card that still
27581
+ * lists models while the line is off reads as "available but hidden", which is
27582
+ * exactly the claim the switch is meant to make false.
27583
+ *
27584
+ * @param settings - The line's stored preferences.
27585
+ * @returns A status with nothing running and the switch reported as off.
27586
+ */
27587
+ function disabledStatus(settings) {
27588
+ return {
27589
+ enabled: false,
27590
+ binary: { kind: "missing" },
27591
+ auth: { authenticated: false },
27592
+ models: [],
27593
+ enabledModelIds: settings.enabledModelIds,
27594
+ defaultReasoningEffort: settings.defaultReasoningEffort,
27595
+ permissionPolicy: settings.permissionPolicy,
27596
+ nativeToolPolicy: settings.nativeToolPolicy,
27597
+ catalogSynced: false
27598
+ };
27599
+ }
27600
+ /**
27337
27601
  * Mount every route of this line.
27338
27602
  *
27339
27603
  * @param ctx - Plugin context owning the web server.
@@ -27733,8 +27997,9 @@ function createProvider(options) {
27733
27997
  },
27734
27998
  inheritsParentContext: false,
27735
27999
  async start(request) {
27736
- const launch = await options.resolveLaunch();
27737
28000
  const settings = await options.settings.read();
28001
+ 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");
28002
+ const launch = await options.resolveLaunch();
27738
28003
  const task = promptText(request.prompt);
27739
28004
  let settled = false;
27740
28005
  const running = startRun(launch, request.cwd, task, settings.permissionPolicy, options, request.signal);
@@ -36541,6 +36806,7 @@ function prefixFingerprints(options) {
36541
36806
  */
36542
36807
  function trackPrefixStability(options) {
36543
36808
  if (isSideChannelTitleRequest(options)) return "stable";
36809
+ if (isAuxiliaryRequest(options)) return "stable";
36544
36810
  const { systemPromptHash, toolsHash } = prefixFingerprints(options);
36545
36811
  const cacheKey = promptCacheKey(options) ?? null;
36546
36812
  const scope = cacheScopeKey(options.sessionId);
@@ -36567,7 +36833,7 @@ const driftCauses = /* @__PURE__ */ new Map();
36567
36833
  * prompt or on its (absent) tool list.
36568
36834
  */
36569
36835
  function recordDriftCause(cause, sessionId, options) {
36570
- if (options !== void 0 && isSideChannelTitleRequest(options)) return;
36836
+ if (options !== void 0 && (isSideChannelTitleRequest(options) || isAuxiliaryRequest(options))) return;
36571
36837
  rememberScoped(driftCauses, cacheScopeKey(sessionId), cause);
36572
36838
  }
36573
36839
  /**
@@ -38903,7 +39169,8 @@ var KimiCodeAdapter = class extends LlmAdapter {
38903
39169
  async *requestStream(options, signal, activity) {
38904
39170
  const fetchFn = this.options.fetchFn ?? fetch;
38905
39171
  const normalized = normalizeGenerateOptions(options);
38906
- const sideChannel = isAuxiliaryRequest(normalized) || isSideChannelTitleRequest(normalized);
39172
+ const titleSideChannel = isSideChannelTitleRequest(normalized);
39173
+ const sideChannel = titleSideChannel || isAuxiliaryRequest(normalized);
38907
39174
  const sessionKey = typeof options.sessionId === "string" ? options.sessionId.trim() : "";
38908
39175
  const retrySignal = options.signal;
38909
39176
  const sameAccountRetryId = sideChannel || retrySignal === void 0 ? void 0 : sameAccountRetryBySignal.get(retrySignal);
@@ -39059,7 +39326,7 @@ var KimiCodeAdapter = class extends LlmAdapter {
39059
39326
  let sentImageReferenceKeys;
39060
39327
  const pool = this.accountPool;
39061
39328
  const tried = /* @__PURE__ */ new Set();
39062
- const cacheAffinity = sideChannel ? void 0 : await this.cacheAffinityHint(pool, requestOptions);
39329
+ const cacheAffinity = titleSideChannel ? void 0 : await this.cacheAffinityHint(pool, requestOptions);
39063
39330
  const affinity = sameAccountRetryId === void 0 ? cacheAffinity : { preferAccountIds: [.../* @__PURE__ */ new Set([sameAccountRetryId, ...cacheAffinity?.preferAccountIds ?? []])] };
39064
39331
  let servedByAccountId;
39065
39332
  let response;
@@ -39246,7 +39513,7 @@ var KimiCodeAdapter = class extends LlmAdapter {
39246
39513
  state.accountId = servedByAccountId;
39247
39514
  diagnosticState = state;
39248
39515
  applyCacheWriteTiers(state, response.headers);
39249
- if (!sideChannel) markSessionActive(requestOptions.sessionId);
39516
+ if (!titleSideChannel) markSessionActive(requestOptions.sessionId);
39250
39517
  let buffer = "";
39251
39518
  /**
39252
39519
  * Set the moment ANY chunk reaches the caller, and never cleared.
@@ -87697,6 +87964,13 @@ function installCompactionPrompt(ctx) {
87697
87964
  *
87698
87965
  * @module @eddyskywalker/dsh-chatgpt-subscription/host/tool-result-pruner-guard
87699
87966
  */
87967
+ /**
87968
+ * 扫过多少次事件之后仍然一个修剪器都没包上,就点名一次。
87969
+ *
87970
+ * 只数「有事件、但一次都没成功」的轮次:装得太早的部署会在第一两步里补上,
87971
+ * 连着几步还包不上就不是时序问题,而是实例真的不在守卫看得见的位置。
87972
+ */
87973
+ const INERT_WARN_AFTER_EVENTS = 3;
87700
87974
  /** 会先跑一遍扫描的宿主事件(全部是 Cordis 瀑布事件,监听器必须转交 `next()`)。 */
87701
87975
  const GUARDED_EVENTS$1 = [
87702
87976
  "agent/pre-step",
@@ -87725,6 +87999,27 @@ function installToolResultPrunerGuard(ctx, options = {}) {
87725
87999
  /** 事件监听的 disposer。 */
87726
88000
  const disposers = [];
87727
88001
  let disposed = false;
88002
+ /** 已经包上的实例数(含直接调用 `wrapPruner` 的外部调用)。 */
88003
+ let wrappedCount = 0;
88004
+ /** 已经跑过的事件轮次。 */
88005
+ let eventRounds = 0;
88006
+ /** 空转点名只报一次。 */
88007
+ let inertWarned = false;
88008
+ /**
88009
+ * 连跑几轮事件仍然一个实例都没包上时,点名一次。
88010
+ *
88011
+ * 这个守卫是纯旁路:包不上时它什么都不做、也不报错,于是部署里「修剪器在
88012
+ * 另一层 realm、守卫根本看不见」会静默退化成「kimi-code 的历史工具结果被修剪,
88013
+ * 前缀缓存每轮重建」。一条 warn 是唯一能把这种静默退化变成可诊断事实的通道。
88014
+ */
88015
+ const warnIfInert = () => {
88016
+ if (inertWarned || wrappedCount > 0) return;
88017
+ if (eventRounds < INERT_WARN_AFTER_EVENTS) return;
88018
+ inertWarned = true;
88019
+ try {
88020
+ host?.logger?.warn?.("[dsh-chatgpt-subscription] tool result pruner guard has wrapped no pruner after " + eventRounds + " agent events; prefix-cache pruning skip is inert on this deployment");
88021
+ } catch {}
88022
+ };
87728
88023
  /**
87729
88024
  * 把一个修剪器实例的 `pruneSession` 包上 provider 短路。
87730
88025
  *
@@ -87751,6 +88046,7 @@ function installToolResultPrunerGuard(ctx, options = {}) {
87751
88046
  if (!installMethod$4(target, replacement)) return false;
87752
88047
  markPatched$4(patchedMethods, target.holder, target.name);
87753
88048
  alreadyWrapped.add(pruner);
88049
+ wrappedCount += 1;
87754
88050
  restores.push(() => {
87755
88051
  restoreMethod$4(target);
87756
88052
  });
@@ -87836,6 +88132,7 @@ function installToolResultPrunerGuard(ctx, options = {}) {
87836
88132
  */
87837
88133
  const handleAgentEvent = (...args) => {
87838
88134
  const next = args.length > 0 && typeof args[args.length - 1] === "function" ? args[args.length - 1] : void 0;
88135
+ eventRounds += 1;
87839
88136
  try {
87840
88137
  scanAndWrap();
87841
88138
  const agentCtx = findAgentContext$1(args);
@@ -87844,10 +88141,11 @@ function installToolResultPrunerGuard(ctx, options = {}) {
87844
88141
  wrapServiceFrom(agentCtx, PRUNER_SERVICE_NAME);
87845
88142
  }
87846
88143
  } catch {}
88144
+ warnIfInert();
87847
88145
  return next === void 0 ? void 0 : next();
87848
88146
  };
87849
88147
  for (const event of GUARDED_EVENTS$1) {
87850
- const disposer = subscribe$4(host, event, handleAgentEvent);
88148
+ const disposer = subscribe$5(host, event, handleAgentEvent);
87851
88149
  if (disposer !== void 0) disposers.push(disposer);
87852
88150
  }
87853
88151
  scanAndWrap();
@@ -87877,7 +88175,7 @@ function installToolResultPrunerGuard(ctx, options = {}) {
87877
88175
  * @param listener - 回调。
87878
88176
  * @returns 移除监听器的 disposer;宿主不支持事件时为 `undefined`。
87879
88177
  */
87880
- function subscribe$4(host, event, listener) {
88178
+ function subscribe$5(host, event, listener) {
87881
88179
  const on = host?.on;
87882
88180
  if (typeof on !== "function") return void 0;
87883
88181
  for (const options of [
@@ -88054,7 +88352,7 @@ function markPatched$4(patched, holder, name) {
88054
88352
  //#endregion
88055
88353
  //#region src/host/plan-mode-cache-guard.ts
88056
88354
  /** 没有 scope 的装配(会话标题之类)用的桶键。 */
88057
- const GLOBAL_KEY$2 = Object.freeze({});
88355
+ const GLOBAL_KEY$3 = Object.freeze({});
88058
88356
  /**
88059
88357
  * 读一个可选服务。
88060
88358
  * @param ctx - 宿主上下文。
@@ -88075,8 +88373,8 @@ function serviceOf$2(ctx, service) {
88075
88373
  * @param value - scope / agent。
88076
88374
  * @returns WeakMap 键。
88077
88375
  */
88078
- function bucketOf$1(value) {
88079
- return typeof value === "object" && value !== null ? value : GLOBAL_KEY$2;
88376
+ function bucketOf$2(value) {
88377
+ return typeof value === "object" && value !== null ? value : GLOBAL_KEY$3;
88080
88378
  }
88081
88379
  /**
88082
88380
  * 订阅一个事件。
@@ -88086,7 +88384,7 @@ function bucketOf$1(value) {
88086
88384
  * @param options - cordis 订阅选项;省略时按两参数订阅。
88087
88385
  * @returns 解绑函数或 undefined。
88088
88386
  */
88089
- function subscribe$3(ctx, event, listener, options) {
88387
+ function subscribe$4(ctx, event, listener, options) {
88090
88388
  const on = ctx?.on;
88091
88389
  if (typeof on !== "function") return void 0;
88092
88390
  if (options !== void 0) try {
@@ -88142,7 +88440,7 @@ function installPlanModeCacheGuard(ctx) {
88142
88440
  }
88143
88441
  kept.push(section);
88144
88442
  }
88145
- const state = stateOf(bucketOf$1(context?.scope ?? context?.agent));
88443
+ const state = stateOf(bucketOf$2(context?.scope ?? context?.agent));
88146
88444
  if (policy !== void 0) if (policy.trim() === "") {
88147
88445
  state.pending = void 0;
88148
88446
  state.delivered = false;
@@ -88161,7 +88459,7 @@ function installPlanModeCacheGuard(ctx) {
88161
88459
  if (decision === void 0 || decision.kind === "reject") return decision;
88162
88460
  if (payload?.signal?.aborted === true) return decision;
88163
88461
  const agent = payload?.agent;
88164
- const key = bucketOf$1(agent ?? void 0);
88462
+ const key = bucketOf$2(agent ?? void 0);
88165
88463
  const state = states.get(key);
88166
88464
  if (state === void 0) return decision;
88167
88465
  if (state.delivered) if (planActiveOf(ctx, agent?.session) === false) state.delivered = false;
@@ -88176,8 +88474,8 @@ function installPlanModeCacheGuard(ctx) {
88176
88474
  messages: [...messages, createPlanNotice(text, void 0, "Plan mode guidance")]
88177
88475
  };
88178
88476
  };
88179
- const offAssemble = subscribe$3(ctx, "system-prompt/assemble", onAssemble);
88180
- const offPreStep = subscribe$3(ctx, "agent/pre-step", onPreStep);
88477
+ const offAssemble = subscribe$4(ctx, "system-prompt/assemble", onAssemble);
88478
+ const offPreStep = subscribe$4(ctx, "agent/pre-step", onPreStep);
88181
88479
  if (offAssemble !== void 0) restores.push(() => {
88182
88480
  offAssemble();
88183
88481
  });
@@ -88210,7 +88508,7 @@ function installPlanModeCacheGuard(ctx) {
88210
88508
  restoreMethod$3(target);
88211
88509
  });
88212
88510
  if (typeof tools.get === "function") try {
88213
- if (tools.get("exit_plan_mode") !== void 0) logWarn$1(ctx, "[dsh-chatgpt-subscription] plan-mode cache guard was installed after exit_plan_mode was already registered; this session keeps the conditional admission");
88511
+ if (tools.get("exit_plan_mode") !== void 0) logWarn$2(ctx, "[dsh-chatgpt-subscription] plan-mode cache guard was installed after exit_plan_mode was already registered; this session keeps the conditional admission");
88214
88512
  } catch {}
88215
88513
  };
88216
88514
  const tools = serviceOf$2(ctx, "tools");
@@ -88286,7 +88584,7 @@ function planActiveOfAgent(ctx, agent) {
88286
88584
  * @param ctx - 宿主上下文。
88287
88585
  * @param message - 正文。
88288
88586
  */
88289
- function logWarn$1(ctx, message) {
88587
+ function logWarn$2(ctx, message) {
88290
88588
  const logger = ctx?.logger;
88291
88589
  try {
88292
88590
  logger?.warn(message);
@@ -88389,17 +88687,56 @@ function markPatched$3(patched, holder, name) {
88389
88687
  if (names === void 0) patched.set(holder, /* @__PURE__ */ new Set([name]));
88390
88688
  else names.add(name);
88391
88689
  }
88690
+ //#endregion
88691
+ //#region src/host/ptc-sdk-cache-guard.ts
88692
+ /**
88693
+ * 「PTC SDK 段前缀缓存守卫」——把 `tools:sdk` 段按会话冻结下来。
88694
+ *
88695
+ * ## 为什么需要它
88696
+ *
88697
+ * PTC 模式下模型看到的不是逐个工具 schema,而是 system prompt 里的一段
88698
+ * `tools:sdk`(TypeScript / Python 的 SDK 声明)。这段正文由工具注册表在
88699
+ * **装配那一刻**现算:`tools.definitions(scope, toolSet)`。
88700
+ *
88701
+ * 带 `when` 条件的工具(按步骤准入)会让 `toolSet` 逐步变化:这一步准入了
88702
+ * `exit_plan_mode`,下一步又没准入,于是 `tools:sdk` 段逐步重写。system prompt
88703
+ * 一旦被改写,前缀缓存从改写处起全部作废——在 Kimi Code、MiniMax Code 这种按
88704
+ * 前缀缓存计费的线路上,一次抖动就是几万 token 的全价重建。
88705
+ *
88706
+ * ## 做什么、不做什么
88707
+ *
88708
+ * 1. 包住 `tools.definitions(scope, toolSet)`:受保护 provider 下忽略步骤级
88709
+ * `toolSet`,一律取未过滤的 `definitions(scope, undefined)`。
88710
+ * 2. **不碰** `tools.executable(name, scope, toolSet)`:执行期的步骤准入闸门
88711
+ * 原样保留,`when` 为假时调用该工具照样失败(`UNKNOWN_TOOL`)。工具「看得见」
88712
+ * 与「叫得动」被刻意拆开:看得见是为了缓存稳定,叫得动仍由步骤准入说话。
88713
+ * 3. 监听 `system-prompt/assemble` 瀑布,把首个非空 `tools:sdk` 正文按会话缓存;
88714
+ * 只要未过滤工具集的名字与数量没变(工具注册/注销是唯一的合法变更来源),
88715
+ * 后续每一步都复用同一份字节。
88716
+ *
88717
+ * ## 跨代兼容
88718
+ *
88719
+ * `definitions(scope, toolSet)` 只在较新的工具层里存在。没有它的那一代
88720
+ * (`schemas(scope)` 形态)本守卫什么也不包:那一代的工具表本来就是逐步稳定的,
88721
+ * 缓存不会抖动,守卫无事可做。因此这里全程结构探测,不 import 任何工具层类型。
88722
+ *
88723
+ * @module @eddyskywalker/dsh-chatgpt-subscription/host/ptc-sdk-cache-guard
88724
+ */
88725
+ /** 受保护的 provider:Kimi Code 线路。 */
88726
+ const KIMI_CODE_PROVIDER = "kimi-code";
88727
+ /** 受保护的 provider:MiniMax Code 线路。 */
88728
+ const MINIMAX_CODE_PROVIDER = "minimax-code";
88392
88729
  /**
88393
88730
  * 默认受保护的 provider 名单。
88394
88731
  *
88395
88732
  * `kimi-code` 与 `minimax-code` 都按前缀缓存计费:`tools:sdk` 段一旦被改写,
88396
88733
  * 前缀缓存从改写处起全部作废,所以这两条线路默认都要冻结 SDK 段。
88397
88734
  */
88398
- const DEFAULT_PTC_SDK_CACHE_PROVIDERS = Object.freeze(["kimi-code", "minimax-code"]);
88735
+ const DEFAULT_PTC_SDK_CACHE_PROVIDERS = Object.freeze([KIMI_CODE_PROVIDER, MINIMAX_CODE_PROVIDER]);
88399
88736
  /** PTC 生成的 SDK 段名。 */
88400
88737
  const PTC_SDK_SECTION_NAME = "tools:sdk";
88401
88738
  /** 没有 scope 的装配(会话标题之类)用的桶键。 */
88402
- const GLOBAL_KEY$1 = Object.freeze({});
88739
+ const GLOBAL_KEY$2 = Object.freeze({});
88403
88740
  /**
88404
88741
  * 读一个装配 scope 的 provider。
88405
88742
  *
@@ -88493,7 +88830,7 @@ function installPtcSdkCacheGuard(ctx, options = {}) {
88493
88830
  * @param scope - 装配 scope。
88494
88831
  * @returns WeakMap 键。
88495
88832
  */
88496
- const bucketOf = (scope) => typeof scope === "object" && scope !== null ? scope : GLOBAL_KEY$1;
88833
+ const bucketOf = (scope) => typeof scope === "object" && scope !== null ? scope : GLOBAL_KEY$2;
88497
88834
  /**
88498
88835
  * 算未过滤工具集的名字指纹。
88499
88836
  *
@@ -88583,7 +88920,7 @@ function installPtcSdkCacheGuard(ctx, options = {}) {
88583
88920
  });
88584
88921
  return result;
88585
88922
  };
88586
- const offAssemble = subscribe$2(host, "system-prompt/assemble", onAssemble);
88923
+ const offAssemble = subscribe$3(host, "system-prompt/assemble", onAssemble);
88587
88924
  if (offAssemble !== void 0) disposers.push(offAssemble);
88588
88925
  const initialTools = serviceOf$1(host, "tools");
88589
88926
  if (initialTools !== void 0) {
@@ -88640,7 +88977,7 @@ function serviceOf$1(ctx, service) {
88640
88977
  * @param listener - 回调。
88641
88978
  * @returns 移除监听器的 disposer;宿主不支持事件时为 `undefined`。
88642
88979
  */
88643
- function subscribe$2(host, event, listener) {
88980
+ function subscribe$3(host, event, listener) {
88644
88981
  const on = host?.["on"];
88645
88982
  if (typeof on !== "function") return void 0;
88646
88983
  for (const options of [
@@ -89057,14 +89394,14 @@ function resolveTeamPolicyCacheGuardEnabled(config) {
89057
89394
  return config?.teamPolicyCacheGuard !== false;
89058
89395
  }
89059
89396
  /** 没有 scope 的装配(会话标题之类)用的桶键。 */
89060
- const GLOBAL_KEY = Object.freeze({});
89397
+ const GLOBAL_KEY$1 = Object.freeze({});
89061
89398
  /**
89062
89399
  * 桶键:agent 对象本身,或全局桶。
89063
89400
  * @param value - scope / agent。
89064
89401
  * @returns WeakMap 键。
89065
89402
  */
89066
- function bucketOf(value) {
89067
- return typeof value === "object" && value !== null ? value : GLOBAL_KEY;
89403
+ function bucketOf$1(value) {
89404
+ return typeof value === "object" && value !== null ? value : GLOBAL_KEY$1;
89068
89405
  }
89069
89406
  /**
89070
89407
  * 订阅一个事件。
@@ -89073,7 +89410,7 @@ function bucketOf(value) {
89073
89410
  * @param listener - 监听器。
89074
89411
  * @returns 解绑函数或 undefined。
89075
89412
  */
89076
- function subscribe$1(ctx, event, listener) {
89413
+ function subscribe$2(ctx, event, listener) {
89077
89414
  const on = ctx?.on;
89078
89415
  if (typeof on !== "function") return void 0;
89079
89416
  try {
@@ -89087,7 +89424,7 @@ function subscribe$1(ctx, event, listener) {
89087
89424
  * @param ctx - 宿主上下文。
89088
89425
  * @param message - 正文。
89089
89426
  */
89090
- function logWarn(ctx, message) {
89427
+ function logWarn$1(ctx, message) {
89091
89428
  try {
89092
89429
  ctx?.logger?.warn(message);
89093
89430
  } catch {}
@@ -89165,11 +89502,11 @@ function installTeamPolicyCacheGuard(ctx, options = {}) {
89165
89502
  if (policy === void 0) {
89166
89503
  if (!stats.seen && !stats.warned) {
89167
89504
  stats.warned = true;
89168
- logWarn(ctx, `[dsh-chatgpt-subscription] team policy cache guard is enabled but no "${TEAM_POLICY_SECTION}" section has appeared; the guard is inert on this deployment`);
89505
+ logWarn$1(ctx, `[dsh-chatgpt-subscription] team policy cache guard is enabled but no "${TEAM_POLICY_SECTION}" section has appeared; the guard is inert on this deployment`);
89169
89506
  }
89170
89507
  return result;
89171
89508
  }
89172
- const state = stateOf(bucketOf(context?.scope ?? context?.agent));
89509
+ const state = stateOf(bucketOf$1(context?.scope ?? context?.agent));
89173
89510
  if (policy.trim() === "") {
89174
89511
  if (state.delivered) state.revoked = true;
89175
89512
  state.delivered = false;
@@ -89190,7 +89527,7 @@ function installTeamPolicyCacheGuard(ctx, options = {}) {
89190
89527
  if (closed || decision === void 0 || decision.kind === "reject") return decision;
89191
89528
  if (payload?.signal?.aborted === true) return decision;
89192
89529
  if (!enabled()) return decision;
89193
- const state = states.get(bucketOf(payload?.agent ?? void 0));
89530
+ const state = states.get(bucketOf$1(payload?.agent ?? void 0));
89194
89531
  if (state === void 0) return decision;
89195
89532
  const messages = Array.isArray(decision.messages) ? decision.messages : [];
89196
89533
  if (!state.delivered) {
@@ -89214,8 +89551,8 @@ function installTeamPolicyCacheGuard(ctx, options = {}) {
89214
89551
  }
89215
89552
  return decision;
89216
89553
  };
89217
- const offAssemble = subscribe$1(ctx, "system-prompt/assemble", onAssemble);
89218
- const offPreStep = subscribe$1(ctx, "agent/pre-step", onPreStep);
89554
+ const offAssemble = subscribe$2(ctx, "system-prompt/assemble", onAssemble);
89555
+ const offPreStep = subscribe$2(ctx, "agent/pre-step", onPreStep);
89219
89556
  if (offAssemble !== void 0) restores.push(() => {
89220
89557
  offAssemble();
89221
89558
  });
@@ -89699,7 +90036,7 @@ function installCompactionPolicyGuard(ctx, options = {}) {
89699
90036
  return next === void 0 ? void 0 : next();
89700
90037
  };
89701
90038
  for (const event of GUARDED_EVENTS) {
89702
- const disposer = subscribe(host, event, handleAgentEvent);
90039
+ const disposer = subscribe$1(host, event, handleAgentEvent);
89703
90040
  if (disposer !== void 0) disposers.push(disposer);
89704
90041
  }
89705
90042
  scanAndPatch();
@@ -89766,7 +90103,7 @@ function readContext(value) {
89766
90103
  * @param listener - 回调。
89767
90104
  * @returns 移除监听器的 disposer;宿主不支持事件时为 `undefined`。
89768
90105
  */
89769
- function subscribe(host, event, listener) {
90106
+ function subscribe$1(host, event, listener) {
89770
90107
  const on = host?.["on"];
89771
90108
  if (typeof on !== "function") return void 0;
89772
90109
  for (const options of [
@@ -89896,6 +90233,391 @@ function markPatched(patched, holder, name) {
89896
90233
  if (names === void 0) patched.set(holder, /* @__PURE__ */ new Set([name]));
89897
90234
  else names.add(name);
89898
90235
  }
90236
+ //#endregion
90237
+ //#region src/host/timeline-cache-guard.ts
90238
+ /**
90239
+ * 「Timeline 规划段前缀缓存守卫」—— 把实验性 Timeline 插件随 volatile 设置变化的
90240
+ * 那段 system prompt 冻结下来,变更改为尾部投递一次。
90241
+ *
90242
+ * ## 为什么需要它
90243
+ *
90244
+ * `@deepseek-ai/dsh-timeline` 用 `systemPrompt.section()` 注册 `timeline:planning`
90245
+ * 段,而那段正文的来源里包含**会话中途会变的值**:
90246
+ *
90247
+ * - `taskLanguageInstruction(config.language, config.uiLanguage)` —— 显示语言由
90248
+ * Host 读 `settings` 的 locale 偏好,并且会被**任意已认证浏览器**通过 RPC
90249
+ * `timeline/locale` 改写(timeline 的 `index.ts` 把 `browserLanguage` 记下来后
90250
+ * 交给 `liveConfig` 的读取器)。同一场对话换个语言的浏览器打开,系统提示就变。
90251
+ *
90252
+ * 本仓库的 Kimi Code 线路按内容前缀计费,而它**没有**声明
90253
+ * `systemPromptUpdate: 'in-history'`(system prompt 只能作为请求头送出)。因此
90254
+ * `SystemPromptProjection` 一旦看到渲染文本变化,走的就是 `replace` 节点 0——
90255
+ * 整段前缀作废,一次全价重建。参见 `packages/core/agent-loop/src/runtime-context.ts`。
90256
+ *
90257
+ * `timeline_tasks` 的工具描述同理:timeline 用 `Object.defineProperty` 把
90258
+ * `config.taskPrompt` 挂在 description 的 getter 上,改一次写作提示词就等于改工具
90259
+ * 表,`tools` 数组随之变化。这条线路虽然有 `toolUpdate: 'in-history'`,但那个模式
90260
+ * 只覆盖工具的**增删**,不覆盖既有工具的描述改写。
90261
+ *
90262
+ * ## 三条动作(与 `team-policy-cache-guard` / `plan-mode-cache-guard` 同一套)
90263
+ *
90264
+ * 1. `system-prompt/assemble` 瀑布:把首次出现的 `timeline:planning` 正文按 scope
90265
+ * 记下来,之后一律返回这份冻结副本。system 段从此逐字节恒定。
90266
+ * 2. 冻结值与当次装配到的正文不一致时,记一份「待投递」;下一步 `agent/pre-step`
90267
+ * 把它作为**尾部用户消息**投一次。末尾追加不改变已发前缀,指引没有丢,只是从
90268
+ * 最前面的 system 段搬到了末尾。
90269
+ * 3. `tools.definitions` 包装:把 `timeline_tasks` 的定义替换成首次见到的那份描述,
90270
+ * 工具表不随写作提示词变化。
90271
+ *
90272
+ * ## 冻结的是「首次见到的那一份」,不是抄来的副本
90273
+ *
90274
+ * 投递的正文永远是装配时从官方段里捕获到的原文,本包不落任何 timeline 的文案副
90275
+ * 本。harness 改措辞不会让这里过期。代价是它依赖段名 `timeline:planning`:启用后
90276
+ * 若从未观察到该段(没装 timeline、或 timeline 改了段名),守卫记一条 warn 点名,
90277
+ * 而不是安静地什么都不做。
90278
+ *
90279
+ * ## 默认开启,且只对按前缀计费的线路生效
90280
+ *
90281
+ * 与会话状态无关的纯旁路:不增加任何工具声明面,只在真正出现该段时才动手。开关由
90282
+ * `timelineCacheGuard` 控制,每次装配/每步重读活引用。
90283
+ *
90284
+ * @module @eddyskywalker/dsh-chatgpt-subscription/host/timeline-cache-guard
90285
+ */
90286
+ /** Timeline 的规划指引段名。 */
90287
+ const TIMELINE_SECTION = "timeline:planning";
90288
+ /** Timeline 的任务更新工具名;它的描述随 `taskPrompt` 变。 */
90289
+ const TIMELINE_TASK_TOOL = "timeline_tasks";
90290
+ /**
90291
+ * 默认受保护的 provider 名单。
90292
+ *
90293
+ * `kimi-code` 与 `minimax-code` 都按前缀缓存计费,而且都没有声明
90294
+ * `systemPromptUpdate: 'in-history'`:系统段一改就是整段重建。
90295
+ */
90296
+ const DEFAULT_TIMELINE_CACHE_PROVIDERS = Object.freeze([KIMI_CODE_PROVIDER, MINIMAX_CODE_PROVIDER]);
90297
+ /** 尾部通知的来源 kind(本包自有)。 */
90298
+ const TIMELINE_NOTICE_SOURCE_KIND = "timeline-cache-notice";
90299
+ /**
90300
+ * 从插件配置里读开关。
90301
+ * @param config - 插件配置(结构化:只读一个键)。
90302
+ * @returns 是否启用本守卫;未声明时按开启处理(宿主 schema 的默认值)。
90303
+ */
90304
+ function resolveTimelineCacheGuardEnabled(config) {
90305
+ return config?.timelineCacheGuard !== false;
90306
+ }
90307
+ /** 没有 scope 的装配(会话标题之类)用的桶键。 */
90308
+ const GLOBAL_KEY = Object.freeze({});
90309
+ /**
90310
+ * 桶键:agent 对象本身,或全局桶。
90311
+ * @param value - scope / agent。
90312
+ * @returns WeakMap 键。
90313
+ */
90314
+ function bucketOf(value) {
90315
+ return typeof value === "object" && value !== null ? value : GLOBAL_KEY;
90316
+ }
90317
+ /**
90318
+ * 订阅一个事件。
90319
+ * @param ctx - 宿主上下文。
90320
+ * @param event - 事件名。
90321
+ * @param listener - 监听器。
90322
+ * @returns 解绑函数或 undefined。
90323
+ */
90324
+ function subscribe(ctx, event, listener) {
90325
+ const on = ctx?.on;
90326
+ if (typeof on !== "function") return void 0;
90327
+ try {
90328
+ return on.call(ctx, event, listener);
90329
+ } catch {
90330
+ return;
90331
+ }
90332
+ }
90333
+ /**
90334
+ * 记一条警告。
90335
+ * @param ctx - 宿主上下文。
90336
+ * @param message - 正文。
90337
+ */
90338
+ function logWarn(ctx, message) {
90339
+ try {
90340
+ ctx?.logger?.warn(message);
90341
+ } catch {}
90342
+ }
90343
+ /**
90344
+ * 造一条尾部通知消息。
90345
+ * @param text - 正文。
90346
+ * @param summary - 卡片上显示的一句摘要。
90347
+ * @returns 用户角色的通知消息。
90348
+ */
90349
+ function createNotice(text, summary) {
90350
+ return createUserMessage({
90351
+ content: [{
90352
+ type: "text",
90353
+ text
90354
+ }],
90355
+ source: {
90356
+ kind: TIMELINE_NOTICE_SOURCE_KIND,
90357
+ form: "notice",
90358
+ summary
90359
+ }
90360
+ });
90361
+ }
90362
+ /**
90363
+ * 新正文的尾部投递正文。
90364
+ *
90365
+ * 完整重放一遍段文本,而不是只投一条「语言变了」:模型需要的是新的写作要求本身,
90366
+ * 而它已经在**旧**要求下工作了很久,只说一句「变了」等于让它自己猜变了什么。
90367
+ * @param text - 冻结之后出现的新段文本。
90368
+ * @returns 通知正文。
90369
+ */
90370
+ function timelineGuidanceUpdateText(text) {
90371
+ return "Timeline planning guidance was updated. It replaces any earlier Timeline planning instruction you were given; follow this version from now on.\n\n" + text;
90372
+ }
90373
+ /**
90374
+ * 装一台「Timeline 规划段前缀缓存守卫」。
90375
+ *
90376
+ * 幂等性留给调用方:同一个 ctx 装两次会得到两条监听器,宿主入口应当只装一次。
90377
+ * @param ctx - 宿主上下文(结构化:老代 ctx 也认)。
90378
+ * @param options - 开关与线路名单。
90379
+ * @returns 句柄,dispose 摘掉全部挂载。
90380
+ */
90381
+ function installTimelineCacheGuard(ctx, options = {}) {
90382
+ const providers = new Set(options.providers ?? DEFAULT_TIMELINE_CACHE_PROVIDERS);
90383
+ const states = /* @__PURE__ */ new WeakMap();
90384
+ const stats = {
90385
+ seen: false,
90386
+ warned: false,
90387
+ warnedTools: false
90388
+ };
90389
+ const restores = [];
90390
+ const alreadyWrapped = /* @__PURE__ */ new WeakSet();
90391
+ const patchedMethods = /* @__PURE__ */ new WeakMap();
90392
+ let disposed = false;
90393
+ const enabled = () => {
90394
+ const read = options.enabled;
90395
+ if (read === void 0) return true;
90396
+ try {
90397
+ return read() === true;
90398
+ } catch {
90399
+ return false;
90400
+ }
90401
+ };
90402
+ const stateOf = (key) => {
90403
+ let state = states.get(key);
90404
+ if (state === void 0) {
90405
+ state = {
90406
+ frozen: "",
90407
+ pending: void 0
90408
+ };
90409
+ states.set(key, state);
90410
+ }
90411
+ return state;
90412
+ };
90413
+ const onAssemble = async (_assembly, context, next) => {
90414
+ const result = await next();
90415
+ if (disposed || !enabled()) return result;
90416
+ const scope = context?.scope ?? context?.agent;
90417
+ const provider = readScopeProvider(scope);
90418
+ if (provider === void 0 || !providers.has(provider)) return result;
90419
+ const sections = Array.isArray(result?.sections) ? result.sections : void 0;
90420
+ if (sections === void 0) return result;
90421
+ const index = sections.findIndex((section) => section?.name === TIMELINE_SECTION);
90422
+ if (index < 0) {
90423
+ if (!stats.seen && !stats.warned) {
90424
+ stats.warned = true;
90425
+ logWarn(ctx, "[dsh-chatgpt-subscription] timeline cache guard is enabled but no \"timeline:planning\" section has appeared; the guard is inert on this deployment");
90426
+ }
90427
+ return result;
90428
+ }
90429
+ stats.seen = true;
90430
+ const current = sections[index];
90431
+ const text = typeof current?.text === "string" ? current.text : "";
90432
+ if (text === "") return result;
90433
+ const state = stateOf(bucketOf(scope));
90434
+ if (state.frozen === "") {
90435
+ state.frozen = text;
90436
+ state.pending = void 0;
90437
+ return result;
90438
+ }
90439
+ if (text !== state.frozen) state.pending = text;
90440
+ if (text === state.frozen) return result;
90441
+ const frozenSections = sections.map((section, position) => position === index ? {
90442
+ ...section,
90443
+ text: state.frozen
90444
+ } : section);
90445
+ return {
90446
+ ...result,
90447
+ sections: frozenSections
90448
+ };
90449
+ };
90450
+ const onPreStep = async (payload, next) => {
90451
+ const decision = await next();
90452
+ if (disposed || decision === void 0 || decision.kind === "reject") return decision;
90453
+ if (payload?.signal?.aborted === true) return decision;
90454
+ if (!enabled()) return decision;
90455
+ const state = states.get(bucketOf(payload?.agent));
90456
+ const text = state?.pending;
90457
+ if (state === void 0 || text === void 0) return decision;
90458
+ state.pending = void 0;
90459
+ const messages = Array.isArray(decision.messages) ? decision.messages : [];
90460
+ return {
90461
+ ...decision,
90462
+ messages: [...messages, createNotice(timelineGuidanceUpdateText(text), "Timeline guidance updated")]
90463
+ };
90464
+ };
90465
+ /**
90466
+ * 冻结下来的工具描述,**按装配 scope 分桶**。
90467
+ *
90468
+ * 只记「每个 scope 第一次见到的那个值」:timeline 的 description 是 getter,每次
90469
+ * 读都反映当时的 `taskPrompt`,所以比较基准必须是字符串快照,不能是函数引用。
90470
+ *
90471
+ * 按 scope 而不是按进程:同一个宿主可以同时跑两个部署(npm 拷贝与仓库 link),
90472
+ * 两者的 taskPrompt 合法地不同;进程级单例会让后一个部署拿到前一个的文案,
90473
+ * 表现成「换了提示词却没生效」而不是任何可诊断的错误。
90474
+ */
90475
+ const frozenToolDescriptions = /* @__PURE__ */ new WeakMap();
90476
+ /** 取一个 scope 的描述快照表,按需创建。 */
90477
+ const descriptionsOf = (scope) => {
90478
+ const bucket = bucketOf(scope);
90479
+ let table = frozenToolDescriptions.get(bucket);
90480
+ if (table === void 0) {
90481
+ table = /* @__PURE__ */ new Map();
90482
+ frozenToolDescriptions.set(bucket, table);
90483
+ }
90484
+ return table;
90485
+ };
90486
+ const freezeDefinitions = (scope, list) => {
90487
+ const table = descriptionsOf(scope);
90488
+ let changed = false;
90489
+ const frozen = list.map((entry) => {
90490
+ if (typeof entry !== "object" || entry === null) return entry;
90491
+ const definition = entry;
90492
+ if (definition.name !== "timeline_tasks") return entry;
90493
+ const description = definition.description;
90494
+ if (typeof description !== "string") return entry;
90495
+ const seen = table.get(TIMELINE_TASK_TOOL);
90496
+ if (seen === void 0) {
90497
+ table.set(TIMELINE_TASK_TOOL, description);
90498
+ return entry;
90499
+ }
90500
+ if (seen === description) return entry;
90501
+ changed = true;
90502
+ return {
90503
+ ...entry,
90504
+ description: seen
90505
+ };
90506
+ });
90507
+ return changed ? frozen : list;
90508
+ };
90509
+ /**
90510
+ * 方法的真实宿主:Cordis 的 `Service` 代理读属性时会把方法**绑定到读取它的那一层
90511
+ * 作用域**,所以 `const original = tools.definitions` 拿到的是已经绑好的函数,
90512
+ * 再 `original.call(tools, …)` 会把根作用域塞回每一个子作用域。真正要包的是原型上
90513
+ * 那份未绑定的实现(与 `ptc-sdk-cache-guard.ts` 同一套处理)。
90514
+ * @param service - 候选服务实例。
90515
+ * @returns 目标;方法不存在时 undefined。
90516
+ */
90517
+ const resolveMethodTarget = (service) => {
90518
+ if (typeof service !== "object" || service === null) return void 0;
90519
+ const own = service;
90520
+ if (Object.prototype.hasOwnProperty.call(own, "definitions")) {
90521
+ const original = own["definitions"];
90522
+ if (typeof original !== "function") return void 0;
90523
+ return {
90524
+ holder: own,
90525
+ name: "definitions",
90526
+ original,
90527
+ descriptor: Object.getOwnPropertyDescriptor(own, "definitions")
90528
+ };
90529
+ }
90530
+ const proto = Object.getPrototypeOf(service);
90531
+ if (proto === null || proto === Object.prototype || proto === Function.prototype) return;
90532
+ const original = proto["definitions"];
90533
+ if (typeof original !== "function") return void 0;
90534
+ return {
90535
+ holder: proto,
90536
+ name: "definitions",
90537
+ original,
90538
+ descriptor: Object.getOwnPropertyDescriptor(proto, "definitions")
90539
+ };
90540
+ };
90541
+ const wrapToolsService = (tools) => {
90542
+ if (disposed || typeof tools !== "object" || tools === null) return false;
90543
+ if (alreadyWrapped.has(tools)) return false;
90544
+ const target = resolveMethodTarget(tools);
90545
+ if (target === void 0) {
90546
+ if (!stats.warnedTools) {
90547
+ stats.warnedTools = true;
90548
+ logWarn(ctx, "[dsh-chatgpt-subscription] timeline cache guard cannot freeze the task tool description: this tool registry exposes no definitions()");
90549
+ }
90550
+ return false;
90551
+ }
90552
+ if (patchedMethods.get(target.holder)?.has(target.name) === true) {
90553
+ alreadyWrapped.add(tools);
90554
+ return false;
90555
+ }
90556
+ const original = target.original;
90557
+ const replacement = function(scope, toolSet) {
90558
+ const receiver = this ?? tools;
90559
+ const list = original.call(receiver, scope, toolSet);
90560
+ if (!Array.isArray(list) || disposed || !enabled()) return list;
90561
+ const provider = readScopeProvider(scope);
90562
+ if (provider === void 0 || !providers.has(provider)) return list;
90563
+ return freezeDefinitions(scope, list);
90564
+ };
90565
+ try {
90566
+ Object.defineProperty(target.holder, target.name, {
90567
+ value: replacement,
90568
+ configurable: true,
90569
+ writable: true,
90570
+ enumerable: target.descriptor?.enumerable ?? false
90571
+ });
90572
+ } catch {
90573
+ return false;
90574
+ }
90575
+ const names = patchedMethods.get(target.holder) ?? /* @__PURE__ */ new Set();
90576
+ names.add(target.name);
90577
+ patchedMethods.set(target.holder, names);
90578
+ alreadyWrapped.add(tools);
90579
+ restores.push(() => {
90580
+ try {
90581
+ if (target.descriptor === void 0) Reflect.deleteProperty(target.holder, target.name);
90582
+ else Object.defineProperty(target.holder, target.name, target.descriptor);
90583
+ } catch {}
90584
+ });
90585
+ return true;
90586
+ };
90587
+ const wrapServiceFrom = (target) => {
90588
+ if (typeof target !== "object" || target === null) return false;
90589
+ const get = target.get;
90590
+ if (typeof get !== "function") return false;
90591
+ try {
90592
+ return wrapToolsService(get.call(target, "tools"));
90593
+ } catch {
90594
+ return false;
90595
+ }
90596
+ };
90597
+ wrapServiceFrom(ctx);
90598
+ const inject = ctx?.inject;
90599
+ if (typeof inject === "function") try {
90600
+ inject.call(ctx, ["tools"], (scope) => {
90601
+ if (disposed) return;
90602
+ wrapServiceFrom(scope);
90603
+ });
90604
+ } catch {}
90605
+ const offAssemble = subscribe(ctx, "system-prompt/assemble", onAssemble);
90606
+ const offPreStep = subscribe(ctx, "agent/pre-step", onPreStep);
90607
+ if (offAssemble !== void 0) restores.push(() => {
90608
+ offAssemble();
90609
+ });
90610
+ if (offPreStep !== void 0) restores.push(() => {
90611
+ offPreStep();
90612
+ });
90613
+ return { dispose() {
90614
+ if (disposed) return;
90615
+ disposed = true;
90616
+ for (const restore of restores.splice(0)) try {
90617
+ restore();
90618
+ } catch {}
90619
+ } };
90620
+ }
89899
90621
  const ID_SCHEMA = z.string().min(1).max(64).regex(/^[A-Za-z0-9._:-]+$/);
89900
90622
  const TASK_REFERENCE_SCHEMA = z.string().min(1).max(160);
89901
90623
  const BOUNDARY_SCHEMA = z.string().min(1).max(120);
@@ -104385,6 +105107,7 @@ const Config = z$1.object({
104385
105107
  toolRunawayGuard: z$1.boolean().default(true).volatile().description("启用工具失控治理:对零增量病态信号(同名同参重复、同一工具连续同族报错、后台任务无变化轮询)分级提醒;Kimi 保留第 12 次同参强停,其他线路只提醒。"),
104386
105108
  mediaTools: z$1.boolean().default(true).volatile().description("注册图片/视频工具:Codex 生图、Kimi 视频挂载、MiniMax 视频生成与理解;默认开启。修改后重载插件或重启 DSH,Kimi 既有会话在工具表变化后会重建一次前缀缓存。"),
104387
105109
  teamPolicyCacheGuard: z$1.boolean().default(true).volatile().description("把内置 Agent Teams 的 team:policy 段从 system prompt 摘掉,改为开关切换时以尾部用户消息投递一次,避免中途开团队协作时刷掉整段前缀缓存;默认开启。"),
105110
+ timelineCacheGuard: z$1.boolean().default(true).volatile().description("冻结实验性 Timeline 插件的规划段与任务工具描述,变更改为尾部用户消息投递,避免中途改语言/写作提示词时刷掉 Kimi/MiniMax 的整段前缀缓存;默认开启。"),
104388
105111
  cacheWarmup: z$1.boolean().default(true).volatile().description(CACHE_WARMUP_SETTING_DESCRIPTION),
104389
105112
  cacheWarmupProviders: z$1.array(z$1.string()).default(CONTROLLED_PROVIDERS).volatile().description("允许产生新结果预览的线路;默认覆盖全部受控线路,空数组表示关闭所有新投影。"),
104390
105113
  cacheWarmupRetrieval: z$1.boolean().default(true).volatile().description(CACHE_WARMUP_RETRIEVAL_SETTING_DESCRIPTION),
@@ -104465,6 +105188,10 @@ function apply(ctx, pluginConfig = {}) {
104465
105188
  const guard = installTeamPolicyCacheGuard(ctx, { enabled: () => resolveTeamPolicyCacheGuardEnabled(pluginConfig) });
104466
105189
  return () => guard.dispose();
104467
105190
  }, "dsh-chatgpt-subscription: team policy cache guard");
105191
+ ctx.effect(() => {
105192
+ const guard = installTimelineCacheGuard(ctx, { enabled: () => resolveTimelineCacheGuardEnabled(pluginConfig) });
105193
+ return () => guard.dispose();
105194
+ }, "dsh-chatgpt-subscription: timeline cache guard");
104468
105195
  ctx.effect(() => {
104469
105196
  const guard = installCompactionPolicyGuard(ctx);
104470
105197
  return () => guard.dispose();
@@ -105149,12 +105876,19 @@ function apply(ctx, pluginConfig = {}) {
105149
105876
  canToggle: true,
105150
105877
  read: async () => {
105151
105878
  const current = await antigravityAcpSettings.read();
105879
+ if (!current.enabled) return {
105880
+ enabled: false,
105881
+ accountCount: 0,
105882
+ authenticated: false,
105883
+ enabledModelCount: null,
105884
+ totalModelCount: null
105885
+ };
105152
105886
  const catalog = await antigravityAcpCatalog.rehydrate();
105153
105887
  const total = catalog === void 0 ? null : catalogTotal(catalog.models.length);
105154
105888
  const selected = current.enabledModelIds === null ? total : current.enabledModelIds.length;
105155
105889
  const auth = await antigravityAcpAuth.read();
105156
105890
  return {
105157
- enabled: current.enabled !== false,
105891
+ enabled: true,
105158
105892
  accountCount: auth.authenticated ? 1 : 0,
105159
105893
  authenticated: auth.authenticated,
105160
105894
  enabledModelCount: total === null || selected === null ? null : Math.min(selected, total),