@linxin666/dsh-client-ui-browser-view 0.4.16 → 0.4.17

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
@@ -715,6 +715,33 @@ var TabManager = class {
715
715
  if (record === void 0) throw new Error(`unknown tab "${tabId}"; call browser_tabs to see the open tabs`);
716
716
  return this.view(record);
717
717
  }
718
+ /**
719
+ * Record that a tool call just worked on this tab.
720
+ *
721
+ * Only the host's own tool paths call this. A panel that keeps watching a
722
+ * page is not activity: a page nobody drives must still age out, or a viewer
723
+ * left open on one tab keeps the cleanup from ever running.
724
+ * @param tabId - the tab the call used; an id that closed meanwhile is ignored.
725
+ */
726
+ touch(tabId) {
727
+ const record = this.tabs.get(tabId);
728
+ if (record === void 0) return;
729
+ record.lastActiveAt = this.now();
730
+ }
731
+ /**
732
+ * Tabs DSH opened itself that no tool call has touched within `maxAgeMs`.
733
+ *
734
+ * Adopted real-browser pages are never candidates: they belong to the person
735
+ * using that browser, and the real-browser contract closes them only when a
736
+ * caller names the tab explicitly.
737
+ * @param maxAgeMs - idle window in milliseconds; zero or less selects nothing.
738
+ * @returns ids in creation order.
739
+ */
740
+ idleCandidates(maxAgeMs) {
741
+ if (!(maxAgeMs > 0)) return [];
742
+ const nowMs = this.now();
743
+ return [...this.tabs.values()].filter((record) => record.origin === "created" && nowMs - record.lastActiveAt >= maxAgeMs).map((record) => record.id);
744
+ }
718
745
  /** Internal record access for the layers that need the CDP session. */
719
746
  sessionOf(tabId) {
720
747
  const record = this.tabs.get(tabId);
@@ -800,6 +827,7 @@ var TabManager = class {
800
827
  loaderId: void 0,
801
828
  ownerSessionId: void 0,
802
829
  origin,
830
+ lastActiveAt: this.now(),
803
831
  console: [],
804
832
  network: [],
805
833
  pendingRequests: /* @__PURE__ */ new Map(),
@@ -2107,6 +2135,8 @@ async function openIsolatedSession(options) {
2107
2135
  * `CDP_COMMAND_TIMEOUT_MS`, exactly as in the isolated mode.
2108
2136
  */
2109
2137
  const REAL_BROWSER_HANDSHAKE_TIMEOUT_MS = 5e3;
2138
+ /** One day in milliseconds: the unit the idle-close window is configured in. */
2139
+ const DAY_MS = 1440 * 60 * 1e3;
2110
2140
  /** Connect to an existing real browser without owning its process or tabs. */
2111
2141
  async function openExternalSession(options, seams = {}) {
2112
2142
  const endpoint = parseCdpEndpoint(options.cdpEndpoint ?? "");
@@ -2155,6 +2185,9 @@ var BrowserViewService = class {
2155
2185
  openSession;
2156
2186
  resolveConfig;
2157
2187
  authenticatedUrl;
2188
+ idleCloseDays;
2189
+ sweepIntervalMs;
2190
+ idleTimer;
2158
2191
  sinks = /* @__PURE__ */ new Set();
2159
2192
  bindings = /* @__PURE__ */ new Map();
2160
2193
  /**
@@ -2195,6 +2228,16 @@ var BrowserViewService = class {
2195
2228
  this.openSession = options.openSession ?? openConfiguredSession;
2196
2229
  this.resolveConfig = options.resolveConfig ?? (() => ({ mode: "isolated" }));
2197
2230
  this.authenticatedUrl = options.authenticatedUrl;
2231
+ this.idleCloseDays = options.idleCloseDays ?? (() => 0);
2232
+ this.sweepIntervalMs = options.sweepIntervalMs ?? 6e5;
2233
+ if (this.sweepIntervalMs > 0) {
2234
+ const timer = setInterval(() => {
2235
+ this.sweepIdle().catch(() => void 0);
2236
+ }, this.sweepIntervalMs);
2237
+ const unref = timer.unref;
2238
+ if (typeof unref === "function") unref.call(timer);
2239
+ this.idleTimer = timer;
2240
+ }
2198
2241
  }
2199
2242
  /** Whether a browser is currently running. */
2200
2243
  get running() {
@@ -2342,6 +2385,31 @@ var BrowserViewService = class {
2342
2385
  return closed;
2343
2386
  }
2344
2387
  /**
2388
+ * Close the tabs no browser tool has touched for the configured idle window.
2389
+ *
2390
+ * Scope is what the real-browser contract allows: only tabs DSH created are
2391
+ * candidates, and a page adopted from the person's own browser is never closed
2392
+ * by a timer — that contract keeps adopted pages closable only through an
2393
+ * explicit `tab_id`. The window is read per sweep, so a settings edit applies
2394
+ * to the next one, and a host with no browser running closes nothing and
2395
+ * starts none: cleanup must never cost a process.
2396
+ * @returns ids of the tabs actually closed, in close order.
2397
+ */
2398
+ async sweepIdle() {
2399
+ if (this.disposed) return [];
2400
+ const days = this.idleCloseDays();
2401
+ if (!(days > 0)) return [];
2402
+ const session = this.session;
2403
+ if (session === void 0 || session.transport.closed) return [];
2404
+ const closed = [];
2405
+ for (const tabId of session.tabs.idleCandidates(days * DAY_MS)) {
2406
+ if (!session.tabs.has(tabId)) continue;
2407
+ await this.closeTab(tabId).catch(() => void 0);
2408
+ if (!session.tabs.has(tabId)) closed.push(tabId);
2409
+ }
2410
+ return closed;
2411
+ }
2412
+ /**
2345
2413
  * Resolve the tab a tool call from `sessionId` should act on.
2346
2414
  *
2347
2415
  * The order is a safety property, not a preference. An agent that lands on
@@ -2363,6 +2431,18 @@ var BrowserViewService = class {
2363
2431
  */
2364
2432
  async tabFor(sessionId, tabId) {
2365
2433
  const tabs = await this.requireTabs();
2434
+ const tab = await this.resolveTabFor(tabs, sessionId, tabId);
2435
+ tabs.touch(tab.id);
2436
+ return tab;
2437
+ }
2438
+ /**
2439
+ * Apply {@link tabFor}'s resolution order against an already open manager.
2440
+ * @param tabs - the live tab manager.
2441
+ * @param sessionId - calling agent session, when the host provides one.
2442
+ * @param tabId - explicit tab from the tool arguments.
2443
+ * @returns the tab the call should act on.
2444
+ */
2445
+ async resolveTabFor(tabs, sessionId, tabId) {
2366
2446
  if (tabId !== void 0 && tabId !== "") {
2367
2447
  const found = tabs.list().find((tab) => tab.id === tabId);
2368
2448
  if (found === void 0) throw new Error(`unknown tab "${tabId}"; call browser_tabs to see the open tabs`);
@@ -2712,6 +2792,10 @@ var BrowserViewService = class {
2712
2792
  async dispose() {
2713
2793
  if (this.disposed) return;
2714
2794
  this.disposed = true;
2795
+ if (this.idleTimer !== void 0) {
2796
+ clearInterval(this.idleTimer);
2797
+ this.idleTimer = void 0;
2798
+ }
2715
2799
  this.generation += 1;
2716
2800
  this.opening = void 0;
2717
2801
  const sinks = [...this.sinks];
@@ -3130,7 +3214,7 @@ function writeJson(res, status, body) {
3130
3214
  res.end(text);
3131
3215
  }
3132
3216
  //#endregion
3133
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-typert-protocol@0.2.2-rc.1_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-typert-protocol/lib/index.js
3217
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-typert-protocol@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-typert-protocol/lib/index.js
3134
3218
  /** The one Remote failure class shared by owners, the Gateway, and consumers. */
3135
3219
  /**
3136
3220
  * One Remote call failure: a real Error carrying its stable code and typed
@@ -3312,7 +3396,7 @@ function validateName(subject, value) {
3312
3396
  if (!isTypertRemoteSegment(value)) throw new TypeError(`typert-protocol: ${subject} must contain only RPC endpoint segment characters`);
3313
3397
  }
3314
3398
  //#endregion
3315
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-util-values@0.2.2-rc.1_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-util-values/lib/index.js
3399
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-util-values@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-util-values/lib/index.js
3316
3400
  /**
3317
3401
  * Lazily scanned view of one JSON object's top-level fields, built from text
3318
3402
  * that may still be streaming or from an already parsed object. Nothing is
@@ -5018,23 +5102,15 @@ defineMethod("transform", [
5018
5102
  "preserve"
5019
5103
  ], ({ inner }, isInner) => inner.toString(isInner));
5020
5104
  //#endregion
5021
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-timeout@0.2.2-rc.1_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-timeout/lib/index.js
5105
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-timeout@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-timeout/lib/index.js
5022
5106
  /** Largest delay Node schedules without clamping it to one millisecond. */
5023
5107
  const MAX_TIMER_DELAY_MS = 2147483647;
5024
5108
  //#endregion
5025
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.2-rc.1_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-llm/lib/index.js
5026
- /**
5027
- * Detach and deep-freeze a message whose identity already exists.
5028
- * @param message - complete message, including its stable identity.
5029
- * @returns an immutable snapshot that preserves the identity.
5030
- */
5031
- function freezeMessage(message) {
5032
- return deepFreeze(structuredClone(message));
5033
- }
5109
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-error@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-error/lib/index.js
5034
5110
  /**
5035
5111
  * Harness error base with a stable machine-routable code and chained cause.
5036
5112
  * Package errors extend it so tool results and replay can retain failure class.
5037
- * @module @deepseek-ai/dsh-llm/error
5113
+ * @module @deepseek-ai/dsh-error
5038
5114
  */
5039
5115
  /**
5040
5116
  * Base class for all harness errors. Carries a `code` (stable, programmatic —
@@ -5051,6 +5127,83 @@ var HarnessError = class extends Error {
5051
5127
  this.name = new.target.name;
5052
5128
  }
5053
5129
  };
5130
+ //#endregion
5131
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0_@deepseek-ai+dsh-error@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0_/node_modules/@deepseek-ai/dsh-llm/lib/index.js
5132
+ /**
5133
+ * Detach and deep-freeze a message whose identity already exists.
5134
+ * @param message - complete message, including its stable identity.
5135
+ * @returns an immutable snapshot that preserves the identity.
5136
+ */
5137
+ function freezeMessage(message) {
5138
+ return deepFreeze(structuredClone(message));
5139
+ }
5140
+ /**
5141
+ * LLM failure codes and helpers over the shared Harness error base. The base
5142
+ * class lives in `@deepseek-ai/dsh-error` and is re-exported here, so both
5143
+ * import paths name the same class.
5144
+ * @module @deepseek-ai/dsh-llm/error
5145
+ */
5146
+ /**
5147
+ * Every failure code the built-in providers and the LLM runtime raise. An entry
5148
+ * marked `retryChoice` is offered as a choice for a provider retry policy's
5149
+ * `retryableCodes`; being a choice does not make a code retried by default.
5150
+ */
5151
+ const LLM_FAILURE_CODES = {
5152
+ ABORTED: {},
5153
+ ACCOUNT_QUOTA: {},
5154
+ ACCOUNT_SIGN_IN_REQUIRED: {},
5155
+ ACCOUNT_TOKEN_INVALID: {},
5156
+ AUTH: {},
5157
+ CLIENT_UPGRADE_REQUIRED: {},
5158
+ CONTEXT_WINDOW_EXCEEDED: {},
5159
+ DISCOVERY_FAILED: {},
5160
+ DISCOVERY_UNSUPPORTED: {},
5161
+ DUPLICATE_ADAPTER: {},
5162
+ DUPLICATE_DIRECTORY: {},
5163
+ DUPLICATE_DISCOVERY: {},
5164
+ EMPTY_RESPONSE: { retryChoice: true },
5165
+ FILES_API: {},
5166
+ IMAGE_OFFLOAD_REQUIRED: {},
5167
+ INVALID_ADAPTER: {},
5168
+ INVALID_CATALOG: {},
5169
+ INVALID_CONFIG: {},
5170
+ INVALID_CREDENTIAL: {},
5171
+ INVALID_DIRECTORY: {},
5172
+ INVALID_DISCOVERY: {},
5173
+ INVALID_MODEL_CONTEXT: {},
5174
+ INVALID_MODEL_INFO: {},
5175
+ INVALID_MODEL_MAX_TOKENS: {},
5176
+ INVALID_MODEL_REASONING: {},
5177
+ INVALID_PREPARED_CALL: {},
5178
+ INVALID_REPLAY_STATE: {},
5179
+ INVALID_REQUEST: {},
5180
+ INVALID_RESPONSE: {},
5181
+ MALFORMED_RESPONSE: { retryChoice: true },
5182
+ MISSING_CREDENTIAL: {},
5183
+ MODEL_SWITCH_COMPACTION_FAILED: {},
5184
+ MODEL_UNSUPPORTED: {},
5185
+ NO_ADAPTER: {},
5186
+ NO_CREDENTIAL_STORE: {},
5187
+ NO_DISCOVERY: {},
5188
+ PI_AI_ERROR: {},
5189
+ QUOTA: { retryChoice: true },
5190
+ RATE_LIMIT: { retryChoice: true },
5191
+ REGISTRATION_DISPOSED: {},
5192
+ REQUEST_EXTENSION: {},
5193
+ REQUEST_HEADERS: {},
5194
+ SERVER: { retryChoice: true },
5195
+ STREAM_CLOSED: { retryChoice: true },
5196
+ TIMEOUT: { retryChoice: true },
5197
+ TRANSPORT: { retryChoice: true },
5198
+ UNKNOWN: {},
5199
+ UNKNOWN_MODEL: {},
5200
+ UNSTORABLE_PROVIDER_ID: {},
5201
+ UNSUPPORTED_CONTENT: {},
5202
+ UNSUPPORTED_OPTION: {},
5203
+ UNSUPPORTED_REASONING_EFFORT: {}
5204
+ };
5205
+ /** The {@link LLM_FAILURE_CODES} entries marked as retry-policy choices, in definition order. */
5206
+ const RETRY_CODE_CHOICES = Object.freeze(Object.keys(LLM_FAILURE_CODES).filter((code) => "retryChoice" in LLM_FAILURE_CODES[code]));
5054
5207
  /**
5055
5208
  * Canonical provider-neutral code for a response that completed normally but
5056
5209
  * carried no content blocks at all. Providers occasionally emit a degenerate
@@ -5084,14 +5237,14 @@ const DEFAULT_RETRYABLE_CODES = Object.freeze([
5084
5237
  "TRANSPORT"
5085
5238
  ]);
5086
5239
  const backoffSchema = Schema.object({
5087
- initialDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
5088
- maxDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
5240
+ initialDelayMs: Schema.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
5241
+ maxDelayMs: Schema.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
5089
5242
  jitterRatio: Schema.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
5090
5243
  });
5091
5244
  const normalPolicySchema = Schema.object({
5092
5245
  mode: Schema.const("normal").required(),
5093
5246
  maxRetries: Schema.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
5094
- retryableCodes: Schema.array(Schema.string()).default([...DEFAULT_RETRYABLE_CODES]),
5247
+ retryableCodes: Schema.array(Schema.union([...RETRY_CODE_CHOICES.map((code) => Schema.const(code)), Schema.string().min(1)])).min(1).default([...DEFAULT_RETRYABLE_CODES]),
5095
5248
  backoff: backoffSchema
5096
5249
  });
5097
5250
  const alwaysPolicySchema = Schema.object({
@@ -5369,27 +5522,47 @@ function withoutDeveloperMessages(messages) {
5369
5522
  const retained = messages.filter((message) => message.role !== "developer");
5370
5523
  return retained.length === messages.length ? messages : retained;
5371
5524
  }
5372
- function toolDeclarations(tools, mode, history) {
5525
+ function toolDeclarations(history) {
5373
5526
  const declarations = new Map(history.tools.map((tool) => [tool.name, tool]));
5374
5527
  for (const update of history.updates) for (const tool of update.additions) if (!declarations.has(tool.name)) declarations.set(tool.name, {
5375
5528
  ...tool,
5376
5529
  deferLoading: true
5377
5530
  });
5378
- switch (mode) {
5379
- case "in-history": return declarations;
5380
- case "addition-only": {
5381
- const activeNames = new Set(tools?.map((tool) => tool.name));
5382
- for (const name of declarations.keys()) if (!activeNames.has(name)) declarations.delete(name);
5383
- return declarations;
5384
- }
5385
- /* v8 ignore next 2 -- closed-union exhaustiveness guard */
5386
- default: return assertNever(mode);
5387
- }
5531
+ return declarations;
5532
+ }
5533
+ /** Rebuild declarations on removals or additions to an empty set, where the request prefix changes. */
5534
+ function rebaseAdditionOnlyHistory(history, messages) {
5535
+ const available = new Map(history.tools.map((tool) => [tool.name, tool]));
5536
+ let baseline = history.tools;
5537
+ let retainedFrom = 0;
5538
+ for (const [index, update] of history.updates.entries()) {
5539
+ const additions = new Map(update.additions.map((tool) => [tool.name, tool]));
5540
+ let reset = available.size === 0 && additions.size > 0;
5541
+ for (const block of messages.get(update.messageId)) if (block.type === "tool-addition") {
5542
+ const { deferLoading: _loading, ...tool } = additions.get(block.toolName);
5543
+ available.set(tool.name, tool);
5544
+ } else if (block.type === "tool-removal") {
5545
+ reset = true;
5546
+ available.delete(block.toolName);
5547
+ }
5548
+ if (reset) {
5549
+ baseline = [...available.values()];
5550
+ retainedFrom = index + 1;
5551
+ }
5552
+ }
5553
+ return retainedFrom === 0 ? history : {
5554
+ tools: baseline,
5555
+ updates: history.updates.slice(retainedFrom)
5556
+ };
5388
5557
  }
5389
5558
  /**
5390
5559
  * Construct provider declarations from session-folded history without changing logged active tools.
5391
5560
  * Unsupported routes and incomplete history use current declarations without developer updates.
5392
- * Explicitly deferred baseline tools become available only after their first retained addition.
5561
+ * Explicitly deferred declarations require an addition to activate them.
5562
+ * A rebuild makes previously activated declarations immediate; unactivated declarations stay deferred.
5563
+ * Addition-only routes rebuild when a tool is removed or tools are added to an empty set;
5564
+ * deferred declarations count as existing tools.
5565
+ * Later additions remain deferred and superseded tool blocks are omitted without dropping other content.
5393
5566
  * @param messages - complete request inputs, or the prefix selected for an auxiliary call.
5394
5567
  * @param tools - currently active tool schemas.
5395
5568
  * @param toolUpdate - the resolved route's update mode.
@@ -5409,14 +5582,16 @@ function projectToolUpdates(messages, tools, toolUpdate, history) {
5409
5582
  messages: withoutDeveloperMessages(messages),
5410
5583
  tools
5411
5584
  };
5412
- const messageIds = new Set(messages.flatMap((message) => message.role === "developer" ? [message.id] : []));
5413
- if (history.updates.some((update) => !messageIds.has(update.messageId))) return {
5585
+ const updates = new Map(messages.flatMap((message) => message.role === "developer" ? [[message.id, message.content]] : []));
5586
+ if (history.updates.some((update) => !updates.has(update.messageId))) return {
5414
5587
  messages: withoutDeveloperMessages(messages),
5415
5588
  tools
5416
5589
  };
5417
- const declarations = toolDeclarations(tools, toolUpdate, history);
5590
+ const projectedHistory = toolUpdate === "addition-only" ? rebaseAdditionOnlyHistory(history, updates) : history;
5591
+ const declarations = toolDeclarations(projectedHistory);
5418
5592
  const updateIds = new Set(history.updates.map((update) => update.messageId));
5419
- const offered = new Set(history.tools.filter((tool) => !tool.deferLoading).map((tool) => tool.name));
5593
+ const retainedUpdateIds = new Set(projectedHistory.updates.map((update) => update.messageId));
5594
+ const offered = new Set(projectedHistory.tools.filter((tool) => !tool.deferLoading).map((tool) => tool.name));
5420
5595
  const projectedMessages = [];
5421
5596
  for (const message of messages) {
5422
5597
  if (message.role !== "developer") {
@@ -5427,6 +5602,7 @@ function projectToolUpdates(messages, tools, toolUpdate, history) {
5427
5602
  const content = message.content.filter((block) => {
5428
5603
  switch (block.type) {
5429
5604
  case "tool-addition":
5605
+ if (!retainedUpdateIds.has(message.id)) return false;
5430
5606
  if (!declarations.has(block.toolName) || offered.has(block.toolName)) return false;
5431
5607
  offered.add(block.toolName);
5432
5608
  return true;
@@ -5505,13 +5681,16 @@ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializ
5505
5681
  /**
5506
5682
  * Typed error for LLM-related failures. Extends {@link HarnessError}, so the
5507
5683
  * `code` string (e.g. `AUTH`, `RATE_LIMIT`, `NO_ADAPTER`) is shared taxonomy.
5684
+ * The constructor takes only a {@link BuiltinLlmFailureCode}; a failure from
5685
+ * another provider, whose code may be any string, is re-raised through
5686
+ * {@link LlmError.fromFailure}.
5508
5687
  */
5509
- var LlmError = class extends HarnessError {
5688
+ var LlmError = class LlmError extends HarnessError {
5510
5689
  /** Serializable facts retained beside this live Error. */
5511
5690
  failure;
5512
5691
  /**
5513
5692
  * @param message - non-empty human-readable failure summary.
5514
- * @param code - non-empty stable provider-neutral machine code.
5693
+ * @param code - built-in stable provider-neutral machine code.
5515
5694
  * @param options - optional cause and validated serializable provider facts.
5516
5695
  */
5517
5696
  constructor(message, code, options) {
@@ -5531,6 +5710,18 @@ var LlmError = class extends HarnessError {
5531
5710
  ...options?.offloadImages === void 0 ? {} : { offloadImages: options.offloadImages }
5532
5711
  });
5533
5712
  }
5713
+ /**
5714
+ * Raise an observed failure again with its own code, which any provider may have chosen.
5715
+ * @param failure - the serializable failure, typically from a stream's terminal chunk.
5716
+ * @param options - optional cause.
5717
+ * @returns an error carrying the failure's message, code, and provider facts.
5718
+ */
5719
+ static fromFailure(failure, options) {
5720
+ return new LlmError(failure.message, failure.code, {
5721
+ ...failure,
5722
+ ...options
5723
+ });
5724
+ }
5534
5725
  };
5535
5726
  (() => {
5536
5727
  let _classSuper = TypertRemoteService;
@@ -6206,7 +6397,7 @@ function detachDirectoryEntry(entry) {
6206
6397
  };
6207
6398
  }
6208
6399
  //#endregion
6209
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.2-rc.1_ae856b2e556350e94bf8d8f84b2f857e/node_modules/@deepseek-ai/dsh-tools/lib/shared-DTdn5dXO.js
6400
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0_@deepseek-ai+dsh-agent@0.2._d54d331d737d4347e4d7b0f13cb396ba/node_modules/@deepseek-ai/dsh-tools/lib/shared-DGx6D7zk.js
6210
6401
  /** The selected provider is missing or unloaded; another provider must not take its calls. */
6211
6402
  var ToolExecutorUnavailableError = class extends HarnessError {
6212
6403
  constructor() {
@@ -6743,7 +6934,7 @@ var ToolActivationError = class extends HarnessError {
6743
6934
  }
6744
6935
  };
6745
6936
  //#endregion
6746
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-scope@0.2.2-rc.1_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-scope/lib/index.js
6937
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-scope@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-scope/lib/index.js
6747
6938
  /**
6748
6939
  * Shared insertion-ordered storage and effect ownership for scope-aware registries.
6749
6940
  *
@@ -6996,7 +7187,7 @@ function scopeOf(ctx) {
6996
7187
  return ctx[kScope];
6997
7188
  }
6998
7189
  //#endregion
6999
- //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.2-rc.1_ae856b2e556350e94bf8d8f84b2f857e/node_modules/@deepseek-ai/dsh-tools/lib/index.js
7190
+ //#region ../../node_modules/.pnpm/@deepseek-ai+dsh-tools@0.2.2-rc.2_@deepseek-ai+cordis@4.1.0_@deepseek-ai+dsh-agent@0.2._d54d331d737d4347e4d7b0f13cb396ba/node_modules/@deepseek-ai/dsh-tools/lib/index.js
7000
7191
  /** Unified JSON-value schema DSL, inference, compilation, and tool definition helpers. @module dsh-tools/schema */
7001
7192
  const ANNOTATION_KEYS = [
7002
7193
  "description",
@@ -7632,12 +7823,12 @@ var GuardLayer = class {
7632
7823
  /**
7633
7824
  * Check global and inherited guards after pre-execute policy and approval resolve.
7634
7825
  * @param exec - invocation whose guards are checked before dispatch.
7635
- * @returns the first denial reason, or undefined when no guard denies.
7826
+ * @returns the first denial with its optional structured identity, or undefined when no guard denies.
7636
7827
  */
7637
7828
  checkGuards(exec) {
7638
7829
  for (const layer of [this.guards.global, ...this.guards.chainLayers(exec.agent)]) for (const guard of layer.guards.values()) {
7639
- const reason = guard(exec);
7640
- if (reason !== void 0) return reason;
7830
+ const denial = guard(exec);
7831
+ if (denial !== void 0) return typeof denial === "string" ? { reason: denial } : denial;
7641
7832
  }
7642
7833
  }
7643
7834
  });
@@ -8348,13 +8539,15 @@ title: ${value.title}
8348
8539
  /** Settings schema exported through the host loader entry. */
8349
8540
  const Config = Schema.object({
8350
8541
  realBrowserEnabled: Schema.boolean().default(false).volatile().description("Connect the browser tools to a real Chrome/Edge over CDP instead of launching an isolated temporary browser. Off by default."),
8351
- cdpEndpoint: Schema.string().default("http://127.0.0.1:9222").volatile().description("Loopback CDP endpoint only. Chrome 136+ ignores remote debugging on its default data directory; use a browser profile explicitly started with remote debugging and a non-default --user-data-dir.")
8542
+ cdpEndpoint: Schema.string().default("http://127.0.0.1:9222").volatile().description("Loopback CDP endpoint only. Chrome 136+ ignores remote debugging on its default data directory; use a browser profile explicitly started with remote debugging and a non-default --user-data-dir."),
8543
+ idleCloseDays: Schema.number().min(0).default(3).volatile().description("Close tabs DSH opened itself once no browser tool has touched them for this many days. Adopted real-browser tabs are never closed; 0 disables the sweep.")
8352
8544
  });
8353
8545
  /** Read the current values, including edits committed without a plugin remount. */
8354
8546
  function effectiveConfig(config) {
8355
8547
  return {
8356
8548
  realBrowserEnabled: config?.realBrowserEnabled?.get() ?? false,
8357
- cdpEndpoint: config?.cdpEndpoint?.get() ?? "http://127.0.0.1:9222"
8549
+ cdpEndpoint: config?.cdpEndpoint?.get() ?? "http://127.0.0.1:9222",
8550
+ idleCloseDays: config?.idleCloseDays?.get() ?? 3
8358
8551
  };
8359
8552
  }
8360
8553
  //#endregion
@@ -8376,6 +8569,7 @@ function apply(ctx, config) {
8376
8569
  cdpEndpoint: value.cdpEndpoint
8377
8570
  } : { mode: "isolated" };
8378
8571
  },
8572
+ idleCloseDays: () => effectiveConfig(config).idleCloseDays,
8379
8573
  authenticatedUrl: (url) => {
8380
8574
  const connection = ctx.get("connection");
8381
8575
  if (connection === void 0 || typeof connection.authenticatedUrl !== "function") return void 0;
@@ -11,11 +11,13 @@ import { type CardActions, type CardShell, type FieldState } from './settings-fo
11
11
  export interface BrowserViewSettings {
12
12
  realBrowserEnabled?: boolean;
13
13
  cdpEndpoint?: string;
14
+ idleCloseDays?: number;
14
15
  }
15
16
  /** Card projection bound by the renderer. */
16
17
  export interface BrowserViewSettingsCardState extends CardShell {
17
18
  realBrowserEnabled: FieldState;
18
19
  cdpEndpoint: FieldState;
20
+ idleCloseDays: FieldState;
19
21
  }
20
22
  /** Registration-side snapshot and write actions. */
21
23
  export interface BrowserViewSettingsCardFace extends CardActions {
@@ -37,6 +37,8 @@ export declare const zh: {
37
37
  'config.realBrowserEnabled.hint': string;
38
38
  'config.cdpEndpoint': string;
39
39
  'config.cdpEndpoint.hint': string;
40
+ 'config.idleCloseDays': string;
41
+ 'config.idleCloseDays.hint': string;
40
42
  'config.unavailable': string;
41
43
  'config.failed': string;
42
44
  'settings.title': string;
@@ -45,6 +47,8 @@ export declare const zh: {
45
47
  'settings.enabledHint': string;
46
48
  'settings.cdpEndpoint': string;
47
49
  'settings.cdpEndpointHint': string;
50
+ 'settings.idleCloseDays': string;
51
+ 'settings.idleCloseDaysHint': string;
48
52
  'settings.inherit': string;
49
53
  'settings.on': string;
50
54
  'settings.off': string;
@@ -72,6 +72,11 @@ interface TabRecord {
72
72
  loaderId: string | undefined;
73
73
  ownerSessionId: string | undefined;
74
74
  origin: 'created' | 'adopted';
75
+ /**
76
+ * Clock reading of the last tool call that worked on this tab. Seeded at
77
+ * attach, so a page DSH just opened counts as active; nothing else writes it.
78
+ */
79
+ lastActiveAt: number;
75
80
  console: BrowserConsoleEntry[];
76
81
  network: BrowserNetworkEntry[];
77
82
  /** Pending requests keyed by network request id, so response frames update in place. */
@@ -127,6 +132,25 @@ export declare class TabManager {
127
132
  * @returns the tab record.
128
133
  */
129
134
  tab(tabId: string): BrowserTabView;
135
+ /**
136
+ * Record that a tool call just worked on this tab.
137
+ *
138
+ * Only the host's own tool paths call this. A panel that keeps watching a
139
+ * page is not activity: a page nobody drives must still age out, or a viewer
140
+ * left open on one tab keeps the cleanup from ever running.
141
+ * @param tabId - the tab the call used; an id that closed meanwhile is ignored.
142
+ */
143
+ touch(tabId: string): void;
144
+ /**
145
+ * Tabs DSH opened itself that no tool call has touched within `maxAgeMs`.
146
+ *
147
+ * Adopted real-browser pages are never candidates: they belong to the person
148
+ * using that browser, and the real-browser contract closes them only when a
149
+ * caller names the tab explicitly.
150
+ * @param maxAgeMs - idle window in milliseconds; zero or less selects nothing.
151
+ * @returns ids in creation order.
152
+ */
153
+ idleCandidates(maxAgeMs: number): string[];
130
154
  /** Internal record access for the layers that need the CDP session. */
131
155
  sessionOf(tabId: string): string;
132
156
  /**
@@ -9,16 +9,19 @@ import z from '@deepseek-ai/schemastery';
9
9
  export interface Config {
10
10
  realBrowserEnabled: Volatile<boolean>;
11
11
  cdpEndpoint: Volatile<string>;
12
+ idleCloseDays: Volatile<number>;
12
13
  }
13
14
  /** Profile-patch shape before the schema adds defaults and live references. */
14
15
  export interface ConfigInput {
15
16
  realBrowserEnabled?: boolean;
16
17
  cdpEndpoint?: string;
18
+ idleCloseDays?: number;
17
19
  }
18
20
  /** Values after defaults and live references have been resolved. */
19
21
  export interface ResolvedConfig {
20
22
  realBrowserEnabled: boolean;
21
23
  cdpEndpoint: string;
24
+ idleCloseDays: number;
22
25
  }
23
26
  /** Settings schema exported through the host loader entry. */
24
27
  export declare const Config: z<ConfigInput, Config>;
@@ -97,6 +97,13 @@ export interface BrowserViewServiceOptions {
97
97
  authenticatedUrl?: (url: string) => string | undefined;
98
98
  /** Live browser source; called for state and every new connection. */
99
99
  resolveConfig?: () => BrowserConnectionConfig;
100
+ /**
101
+ * Idle window in days for the tab sweep, read per sweep so a settings edit
102
+ * applies on the next one. Zero or less disables the sweep. @default () => 0
103
+ */
104
+ idleCloseDays?: () => number;
105
+ /** How often the idle sweep runs; zero disables it. @default IDLE_SWEEP_INTERVAL_MS */
106
+ sweepIntervalMs?: number;
100
107
  /** Browser factory, replaced by tests. */
101
108
  openSession?: (options: OpenSessionOptions) => Promise<BrowserSession>;
102
109
  }
@@ -107,6 +114,14 @@ export interface BrowserViewServiceOptions {
107
114
  * `CDP_COMMAND_TIMEOUT_MS`, exactly as in the isolated mode.
108
115
  */
109
116
  export declare const REAL_BROWSER_HANDSHAKE_TIMEOUT_MS = 5000;
117
+ /**
118
+ * How often the service looks for tabs that went idle.
119
+ *
120
+ * Ten minutes is a compromise between two costs that both land on the host:
121
+ * a shorter period wakes the process for nothing on a window measured in days,
122
+ * and a longer one leaves a page running well past its window.
123
+ */
124
+ export declare const IDLE_SWEEP_INTERVAL_MS: number;
110
125
  /**
111
126
  * Seams the external session factory resolves when it connects. The defaults
112
127
  * are the production transport; a test injects one to observe what a
@@ -128,6 +143,9 @@ export declare class BrowserViewService implements BrowserViewBackend {
128
143
  private readonly openSession;
129
144
  private readonly resolveConfig;
130
145
  private readonly authenticatedUrl;
146
+ private readonly idleCloseDays;
147
+ private readonly sweepIntervalMs;
148
+ private idleTimer;
131
149
  private readonly sinks;
132
150
  private readonly bindings;
133
151
  /**
@@ -201,6 +219,18 @@ export declare class BrowserViewService implements BrowserViewBackend {
201
219
  * @returns ids of the tabs actually closed, in close order.
202
220
  */
203
221
  closeOwnTabs(sessionId: string | undefined, tabId?: string): Promise<string[]>;
222
+ /**
223
+ * Close the tabs no browser tool has touched for the configured idle window.
224
+ *
225
+ * Scope is what the real-browser contract allows: only tabs DSH created are
226
+ * candidates, and a page adopted from the person's own browser is never closed
227
+ * by a timer — that contract keeps adopted pages closable only through an
228
+ * explicit `tab_id`. The window is read per sweep, so a settings edit applies
229
+ * to the next one, and a host with no browser running closes nothing and
230
+ * starts none: cleanup must never cost a process.
231
+ * @returns ids of the tabs actually closed, in close order.
232
+ */
233
+ sweepIdle(): Promise<string[]>;
204
234
  /**
205
235
  * Resolve the tab a tool call from `sessionId` should act on.
206
236
  *
@@ -222,6 +252,14 @@ export declare class BrowserViewService implements BrowserViewBackend {
222
252
  * @returns the tab view.
223
253
  */
224
254
  tabFor(sessionId: string | undefined, tabId?: string): Promise<BrowserTabView>;
255
+ /**
256
+ * Apply {@link tabFor}'s resolution order against an already open manager.
257
+ * @param tabs - the live tab manager.
258
+ * @param sessionId - calling agent session, when the host provides one.
259
+ * @param tabId - explicit tab from the tool arguments.
260
+ * @returns the tab the call should act on.
261
+ */
262
+ private resolveTabFor;
225
263
  /**
226
264
  * Whether a tab is bound to some other session.
227
265
  * @param tabId - the tab being considered.