@sparkelf/dsh-dataops-managed 0.3.51 → 0.3.52

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
@@ -1,10 +1,10 @@
1
1
  import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
2
+ import { basename, dirname, extname, join } from "node:path";
2
3
  import { fileURLToPath } from "node:url";
3
4
  import { credentialRef } from "@deepseek-ai/dsh-credentials";
4
5
  import * as McpClient from "@sparkelf/dsh-plugin-mcp-credentials";
5
6
  import { BUNDLED_SKILL_RANK } from "@deepseek-ai/dsh-skill";
6
7
  import z from "@deepseek-ai/schemastery";
7
- import { basename, dirname, extname, join } from "node:path";
8
8
  import { defineTool } from "@deepseek-ai/dsh-tools";
9
9
  import { randomUUID } from "node:crypto";
10
10
  //#region src/auth-state.ts
@@ -72,17 +72,17 @@ function modelIdOf(entry) {
72
72
  return typeof id === "string" && id.trim() !== "" ? id : null;
73
73
  }
74
74
  /** Narrow an unknown value to a plain object. */
75
- function asRecord$4(value) {
75
+ function asRecord$5(value) {
76
76
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
77
77
  }
78
78
  /** Read provider profiles out of a settings value. */
79
79
  function providersOf(value) {
80
- const root = asRecord$4(value);
81
- const providers = root === null ? null : asRecord$4(root[PROVIDERS_FIELD]);
80
+ const root = asRecord$5(value);
81
+ const providers = root === null ? null : asRecord$5(root[PROVIDERS_FIELD]);
82
82
  if (providers === null) return {};
83
83
  const result = {};
84
84
  for (const [providerId, profile] of Object.entries(providers)) {
85
- const narrowed = asRecord$4(profile);
85
+ const narrowed = asRecord$5(profile);
86
86
  if (narrowed !== null) result[providerId] = narrowed;
87
87
  }
88
88
  return result;
@@ -116,7 +116,7 @@ function modelIdsByProvider(providers) {
116
116
  for (const [providerId, profile] of Object.entries(providers)) {
117
117
  const models = profile[MODELS_FIELD];
118
118
  if (!Array.isArray(models)) continue;
119
- result[providerId] = models.map((entry) => asRecord$4(entry)).filter((entry) => entry !== null).map((entry) => modelIdOf(entry)).filter((id) => id !== null);
119
+ result[providerId] = models.map((entry) => asRecord$5(entry)).filter((entry) => entry !== null).map((entry) => modelIdOf(entry)).filter((id) => id !== null);
120
120
  }
121
121
  return result;
122
122
  }
@@ -137,7 +137,7 @@ function selectSharedModels(providers, sharedModelIds) {
137
137
  const models = profile[MODELS_FIELD];
138
138
  if (!Array.isArray(models)) continue;
139
139
  const kept = models.filter((entry) => {
140
- const narrowed = asRecord$4(entry);
140
+ const narrowed = asRecord$5(entry);
141
141
  const id = narrowed === null ? null : modelIdOf(narrowed);
142
142
  return id !== null && offered.has(id);
143
143
  });
@@ -171,9 +171,9 @@ function mergeProviders(local, adopted) {
171
171
  continue;
172
172
  }
173
173
  const localModels = Array.isArray(localProfile[MODELS_FIELD]) ? localProfile[MODELS_FIELD] : [];
174
- const localIds = new Set(localModels.map((entry) => asRecord$4(entry)).filter((entry) => entry !== null).map((entry) => modelIdOf(entry)).filter((id) => id !== null));
174
+ const localIds = new Set(localModels.map((entry) => asRecord$5(entry)).filter((entry) => entry !== null).map((entry) => modelIdOf(entry)).filter((id) => id !== null));
175
175
  const missing = adoptedModels.filter((entry) => {
176
- const narrowed = asRecord$4(entry);
176
+ const narrowed = asRecord$5(entry);
177
177
  const id = narrowed === null ? null : modelIdOf(narrowed);
178
178
  return id !== null && !localIds.has(id);
179
179
  });
@@ -205,7 +205,7 @@ async function writeModels(ctx, providers, revision) {
205
205
  //#endregion
206
206
  //#region src/model-sync.ts
207
207
  /** Narrow an unknown value to a plain object. */
208
- function asRecord$3(value) {
208
+ function asRecord$4(value) {
209
209
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
210
210
  }
211
211
  /**
@@ -252,10 +252,10 @@ var ModelSync = class {
252
252
  }
253
253
  noteAccepted();
254
254
  if (!response.ok) throw new Error(`Shared model read failed with HTTP ${String(response.status)}`);
255
- const body = asRecord$3(await response.json());
255
+ const body = asRecord$4(await response.json());
256
256
  if (body === null) return void 0;
257
- const payload = asRecord$3(body.payload);
258
- const providers = payload === null ? null : asRecord$3(payload.providers);
257
+ const payload = asRecord$4(body.payload);
258
+ const providers = payload === null ? null : asRecord$4(payload.providers);
259
259
  return {
260
260
  sharingEnabled: body.sharingEnabled === true,
261
261
  payload: {
@@ -323,7 +323,7 @@ var ModelSync = class {
323
323
  }
324
324
  noteAccepted();
325
325
  if (!response.ok) throw new Error(`Shared model status read failed with HTTP ${String(response.status)}`);
326
- const body = asRecord$3(await response.json());
326
+ const body = asRecord$4(await response.json());
327
327
  return {
328
328
  sharingEnabled: body?.sharingEnabled === true,
329
329
  canPublish: body?.canPublish === true
@@ -457,7 +457,7 @@ var ModelSync = class {
457
457
  /** Default state before this workspace stored anything. */
458
458
  const SECTION_SYNC_DEFAULT = { sections: {} };
459
459
  /** Narrow an unknown value to a plain object. */
460
- function asRecord$2(value) {
460
+ function asRecord$3(value) {
461
461
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
462
462
  }
463
463
  /**
@@ -496,7 +496,7 @@ var SettingsSync = class {
496
496
  readSection(ns) {
497
497
  const descriptor = this.ctx.settings.describe().find((entry) => entry.ns === ns);
498
498
  if (descriptor === void 0) return void 0;
499
- const value = asRecord$2(descriptor.value);
499
+ const value = asRecord$3(descriptor.value);
500
500
  if (value === null) return void 0;
501
501
  return {
502
502
  value,
@@ -600,7 +600,7 @@ var SettingsSync = class {
600
600
  //#endregion
601
601
  //#region src/skill-plaza.ts
602
602
  /** Narrow an unknown value to a plain object. */
603
- function asRecord$1(value) {
603
+ function asRecord$2(value) {
604
604
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
605
605
  }
606
606
  /**
@@ -694,9 +694,9 @@ var SkillPlaza = class {
694
694
  if (options.departmentCode !== void 0 && options.departmentCode !== "") params.set("departmentCode", options.departmentCode);
695
695
  const suffix = params.size === 0 ? "" : `?${params.toString()}`;
696
696
  const body = await this.call(`/api/ai/skill-plaza/skills${suffix}`);
697
- const record = asRecord$1(body);
697
+ const record = asRecord$2(body);
698
698
  const rows = Array.isArray(body) ? body : Array.isArray(record?.items) ? record.items : [];
699
- const rawCounts = asRecord$1(record?.counts);
699
+ const rawCounts = asRecord$2(record?.counts);
700
700
  return {
701
701
  skills: rows.flatMap((row) => this.toPlazaSkill(row)),
702
702
  ...rawCounts === null ? {} : { counts: {
@@ -745,7 +745,7 @@ var SkillPlaza = class {
745
745
  method: "POST",
746
746
  body: JSON.stringify({ skillId })
747
747
  });
748
- const record = body === void 0 ? null : asRecord$1(body);
748
+ const record = body === void 0 ? null : asRecord$2(body);
749
749
  if (record === null) return null;
750
750
  return {
751
751
  installed: record.installed === true,
@@ -755,7 +755,7 @@ var SkillPlaza = class {
755
755
  }
756
756
  /** Project one API row into the shape the browser reads. */
757
757
  toPlazaSkill(value) {
758
- const row = asRecord$1(value);
758
+ const row = asRecord$2(value);
759
759
  if (row === null || typeof row.id !== "number" || typeof row.name !== "string") return [];
760
760
  return [{
761
761
  id: row.id,
@@ -770,7 +770,7 @@ var SkillPlaza = class {
770
770
  departmentCode: typeof row.departmentCode === "string" ? row.departmentCode : null,
771
771
  departmentName: typeof row.departmentName === "string" ? row.departmentName : void 0,
772
772
  departmentPath: Array.isArray(row.departmentPath) ? row.departmentPath.flatMap((entry) => {
773
- const node = asRecord$1(entry);
773
+ const node = asRecord$2(entry);
774
774
  return node !== null && typeof node.name === "string" ? [{
775
775
  code: typeof node.code === "string" ? node.code : "",
776
776
  name: node.name
@@ -1147,6 +1147,12 @@ function normalizeScope(body) {
1147
1147
  const CONNECTORS_PATH = "/api/dsh-skill-center/connectors";
1148
1148
  /** Connector id shown in the skill center. */
1149
1149
  const DATAOPS_CONNECTOR_ID = "dataops-managed";
1150
+ /** Connector id for the local browser bridge companion. */
1151
+ const BROWSER_BRIDGE_CONNECTOR_ID = "browser-bridge";
1152
+ /** Same-origin route that serves the bridge installer file. */
1153
+ const BROWSER_BRIDGE_INSTALLER_PATH = "/api/dsh-skill-center/browser-bridge/installer";
1154
+ /** State file for the browser bridge connector, beside the DataOps connector state. */
1155
+ const BROWSER_BRIDGE_STATE_PATH = join(process.env.DSH_HOME?.trim() || "/workspace/.dataops/dsh", "dataops-managed", "browser-bridge-state.json");
1150
1156
  /** Resolve the persisted state file without depending on a global DSH path. */
1151
1157
  const CONNECTOR_STATE_PATH = join(process.env.DSH_HOME?.trim() || "/workspace/.dataops/dsh", "dataops-managed", "connector-state.json");
1152
1158
  /**
@@ -1241,6 +1247,69 @@ async function writeConnectorState(state, path = CONNECTOR_STATE_PATH) {
1241
1247
  await writeFile(temporary, JSON.stringify(payload, null, 2), "utf8");
1242
1248
  await rename(temporary, path);
1243
1249
  }
1250
+ /** Read browser-bridge state; a missing or corrupt file means disabled. */
1251
+ async function readBrowserBridgeState(path = BROWSER_BRIDGE_STATE_PATH) {
1252
+ try {
1253
+ const payload = JSON.parse(await readFile(path, "utf8"));
1254
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return { enabled: false };
1255
+ return { enabled: payload.enabled === true };
1256
+ } catch {
1257
+ return { enabled: false };
1258
+ }
1259
+ }
1260
+ /** Persist browser-bridge state atomically. */
1261
+ async function writeBrowserBridgeState(state, path = BROWSER_BRIDGE_STATE_PATH) {
1262
+ await mkdir(dirname(path), { recursive: true });
1263
+ const temporary = path + ".tmp-" + process.pid.toString();
1264
+ await writeFile(temporary, JSON.stringify({ enabled: state.enabled }, null, 2), "utf8");
1265
+ await rename(temporary, path);
1266
+ }
1267
+ /** Product-language description shared by every bridge row; the hint below appends to it. */
1268
+ const BROWSER_BRIDGE_DESCRIPTION = "把用户本地 Chrome/Edge 接入 AI 工作区,让 AI 通过 Playwright 操作本地浏览器;需要安装桥接程序。";
1269
+ /**
1270
+ * Explain the live bridge state without exposing an endpoint or a credential.
1271
+ *
1272
+ * The connector row is where a person discovers *why* `browser_*` is missing, so an offline
1273
+ * companion, an expired login, and a failed connection each get a different next step.
1274
+ */
1275
+ function browserBridgeDescription(runtime) {
1276
+ switch (runtime?.phase) {
1277
+ case "connected":
1278
+ case "idle":
1279
+ case "disabled":
1280
+ case void 0: return BROWSER_BRIDGE_DESCRIPTION;
1281
+ case "connecting": return BROWSER_BRIDGE_DESCRIPTION + " 正在建立桥接连接…";
1282
+ case "offline": return BROWSER_BRIDGE_DESCRIPTION + " 当前没有在线的 Companion:请在本机输入 8 位配对码完成配对并启动 Companion,插件会每 60 秒自动重试。";
1283
+ case "expired": return BROWSER_BRIDGE_DESCRIPTION + " DataOps 登录已过期,重新登录后会自动恢复,无需重启工作区。";
1284
+ case "closed": return BROWSER_BRIDGE_DESCRIPTION + " 桥接会话已关闭;重新登录或重新启用连接器后会重新建立。";
1285
+ case "error": return BROWSER_BRIDGE_DESCRIPTION + " 桥接连接暂时失败,插件正在自动重试。";
1286
+ }
1287
+ }
1288
+ /**
1289
+ * Build the browser-bridge connector row.
1290
+ *
1291
+ * `connected` is evidence, not intent: it is true only while the MCP client is loaded *and*
1292
+ * the gateway reports the session active. `enabled` remains the persisted switch.
1293
+ * @param state - Persisted connector switch.
1294
+ * @param runtime - Live session status; omit when no session manager is active.
1295
+ * @returns The connector row the skill center renders.
1296
+ */
1297
+ function buildBrowserBridgeConnectorView(state, runtime) {
1298
+ return {
1299
+ id: BROWSER_BRIDGE_CONNECTOR_ID,
1300
+ name: "浏览器桥接",
1301
+ vendor: "DataOps",
1302
+ description: browserBridgeDescription(runtime),
1303
+ enabled: state.enabled,
1304
+ connected: runtime?.connected === true,
1305
+ capabilities: [],
1306
+ installer: {
1307
+ fileName: "DSH-Browser-Bridge-Setup-Windows-x64-v0.1.0.exe",
1308
+ downloadUrl: BROWSER_BRIDGE_INSTALLER_PATH,
1309
+ description: "这是完整的离线 Windows 安装包,内含 Chromium、Node 和 Playwright,不会在安装时访问外网。安装后在本机启动受控浏览器窗口,AI 通过它执行网页操作;程序不会读取或上传用户日常浏览器的 Cookie。"
1310
+ }
1311
+ };
1312
+ }
1244
1313
  /** Build the connector row for one current scope. */
1245
1314
  function buildConnectorView(scope, state) {
1246
1315
  const capabilities = scope === void 0 ? [] : CAPABILITIES.filter((capability) => capability.visible(scope) && capability.allowed(scope)).map((capability) => ({
@@ -3671,7 +3740,7 @@ const resolveResourceTabConfig = (request, configuredWebBaseUrl) => {
3671
3740
  //#endregion
3672
3741
  //#region src/workspace-limits.ts
3673
3742
  /** Narrow a value to a plain object. */
3674
- function asRecord(value) {
3743
+ function asRecord$1(value) {
3675
3744
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
3676
3745
  }
3677
3746
  /** Narrow a value to a positive integer. */
@@ -3695,7 +3764,7 @@ var WorkspaceLimitsRejection = class extends Error {
3695
3764
  /** Read DataOps' own explanation from a failed response, falling back to the status line. */
3696
3765
  async function rejectionMessage(response, fallback) {
3697
3766
  try {
3698
- const message = asRecord(await response.json())?.message;
3767
+ const message = asRecord$1(await response.json())?.message;
3699
3768
  if (typeof message === "string" && message.trim() !== "") return message;
3700
3769
  if (Array.isArray(message) && typeof message[0] === "string") return message[0];
3701
3770
  } catch {}
@@ -3739,9 +3808,9 @@ var WorkspaceLimits = class {
3739
3808
  }
3740
3809
  noteAccepted();
3741
3810
  if (!response.ok) throw new WorkspaceLimitsRejection(response.status, await rejectionMessage(response, "Workspace limits read failed"));
3742
- const body = asRecord(await response.json());
3743
- const settings = body === null ? null : asRecord(body.settings);
3744
- const size = settings === null ? null : asRecord(settings.workspaceSize);
3811
+ const body = asRecord$1(await response.json());
3812
+ const settings = body === null ? null : asRecord$1(body.settings);
3813
+ const size = settings === null ? null : asRecord$1(settings.workspaceSize);
3745
3814
  const fileReadMaxBytes = size === null ? null : asByteCount(size.fileReadMaxBytes);
3746
3815
  const uploadMaxBytes = size === null ? null : asByteCount(size.uploadMaxBytes);
3747
3816
  if (fileReadMaxBytes === null || uploadMaxBytes === null) throw new Error("Workspace limits read returned an unrecognized document");
@@ -4086,6 +4155,802 @@ async function recoverWorkspaceUpgradeAfterBoot(upgrade) {
4086
4155
  if (lastState !== null) await upgrade.clearRecoveryState();
4087
4156
  }
4088
4157
  //#endregion
4158
+ //#region src/browser-bridge-session.ts
4159
+ /**
4160
+ * The DataOps browser bridge session: one MCP connection, many short-lived control tokens.
4161
+ *
4162
+ * A workspace reaches the user's local companion only through the DataOps gateway. The plugin
4163
+ * therefore asks DataOps for a session with the current user JWT, and the answer carries an
4164
+ * `mcpUrl` whose ticket is the connection capability plus a short-lived `bridgeToken` for the
4165
+ * control plane. The MCP client is created once from that URL; token expiry is refreshed in
4166
+ * memory, and only session closure (logout, device revoke, explicit close) releases the
4167
+ * connection.
4168
+ *
4169
+ * This module owns that lifecycle so `apply` only supplies callbacks. It never reads a bridge
4170
+ * address from the profile or the environment: the session API is the only production entry.
4171
+ *
4172
+ * @module browser-bridge-session
4173
+ */
4174
+ /** Control-plane request timeout. A container network can be slow, but not unbounded. */
4175
+ const REQUEST_TIMEOUT_MS = 15e3;
4176
+ /**
4177
+ * Close is best-effort on the shutdown path, so it gets a shorter budget than a request whose
4178
+ * answer the user is waiting for. A session left open is cleaned up by the gateway; a plugin
4179
+ * disposal that hangs is visible immediately.
4180
+ */
4181
+ const CLOSE_TIMEOUT_MS = 3e3;
4182
+ /** Retry delay after the companion is offline or a control-plane call failed. */
4183
+ const RETRY_DELAY_MS = 6e4;
4184
+ /** How often an expiring `bridgeToken` is checked. */
4185
+ const REFRESH_INTERVAL_MS = 6e4;
4186
+ /** Refresh ahead of expiry: a token with less than this left is rotated. */
4187
+ const REFRESH_AHEAD_MS = 3e5;
4188
+ /** How often the gateway is asked whether the session is still active. */
4189
+ const STATUS_INTERVAL_MS = 3e4;
4190
+ /**
4191
+ * Whether a control token is close enough to expiry to rotate.
4192
+ * @param expiresAt - Epoch milliseconds from the session answer.
4193
+ * @param now - Current epoch milliseconds.
4194
+ * @returns True when less than {@link REFRESH_AHEAD_MS} remains.
4195
+ */
4196
+ function expiresSoon(expiresAt, now) {
4197
+ return expiresAt - now < REFRESH_AHEAD_MS;
4198
+ }
4199
+ /**
4200
+ * Drop the query from an MCP URL before it can reach a log line.
4201
+ *
4202
+ * The `mcpUrl` carries the session ticket in its query string, so it is a credential and must
4203
+ * never be printed whole. The origin and path are enough to correlate a log entry.
4204
+ * @param url - Any URL, possibly already stripped of its query.
4205
+ * @returns Origin plus path, or a fixed marker when the value is not a URL.
4206
+ */
4207
+ function redactMcpUrl(url) {
4208
+ try {
4209
+ const parsed = new URL(url);
4210
+ return `${parsed.protocol}//${parsed.host}${parsed.pathname}`;
4211
+ } catch {
4212
+ return "(invalid url)";
4213
+ }
4214
+ }
4215
+ /**
4216
+ * Replace every URL in a diagnostic with its redacted form.
4217
+ *
4218
+ * MCP client failures often embed the endpoint they tried, and that endpoint carries a ticket.
4219
+ * Diagnostics pass through here so a log line cannot leak it.
4220
+ * @param text - Diagnostic text.
4221
+ * @returns The same text with each absolute URL reduced to origin plus path.
4222
+ */
4223
+ function redactUrls(text) {
4224
+ return text.replace(/https?:\/\/[^\s"'<>]+/gu, (match) => redactMcpUrl(match));
4225
+ }
4226
+ /**
4227
+ * Describe one thrown value without assuming it is an Error and without echoing a URL.
4228
+ * @param error - The value a failed call rejected with.
4229
+ * @returns A single-line diagnostic safe to log.
4230
+ */
4231
+ function describeError(error) {
4232
+ return redactUrls(error instanceof Error ? error.message : typeof error === "string" ? error : "unexpected failure");
4233
+ }
4234
+ /** Narrow an unknown JSON value to a plain object. */
4235
+ function asRecord(value) {
4236
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
4237
+ }
4238
+ /** Read an expiry that may be an ISO timestamp, or already epoch milliseconds. */
4239
+ function readExpiresAt(value) {
4240
+ if (typeof value === "number" && Number.isFinite(value)) return value;
4241
+ if (typeof value !== "string" || value === "") return void 0;
4242
+ const parsed = Date.parse(value);
4243
+ return Number.isNaN(parsed) ? void 0 : parsed;
4244
+ }
4245
+ /** Only an HTTP(S) URL is a usable MCP endpoint. */
4246
+ function isHttpUrl(value) {
4247
+ try {
4248
+ const parsed = new URL(value);
4249
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
4250
+ } catch {
4251
+ return false;
4252
+ }
4253
+ }
4254
+ /** The stable error code in a gateway refusal, when there is one. */
4255
+ function errorCode(record) {
4256
+ return typeof record?.code === "string" && record.code !== "" ? record.code : void 0;
4257
+ }
4258
+ /** Read the gateway process id; an older backend omits it and disables restart detection. */
4259
+ function readGatewayInstanceId(value) {
4260
+ return typeof value === "string" && value !== "" ? value : void 0;
4261
+ }
4262
+ /** Read the companion tunnel generation; an older backend omits it. */
4263
+ function readTunnelGeneration(value) {
4264
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
4265
+ }
4266
+ /**
4267
+ * Whether the gateway or the companion that serves this session changed.
4268
+ *
4269
+ * Only components present on both sides are compared: an older backend that omits a field
4270
+ * cannot produce a false rebuild, and a value that appears for the first time is adopted
4271
+ * without a rebuild.
4272
+ * @param previous - Identity recorded from the session create answer.
4273
+ * @param next - Identity read from a status poll.
4274
+ * @returns True when any comparable component differs.
4275
+ */
4276
+ function tunnelIdentityChanged(previous, next) {
4277
+ const instanceChanged = previous.gatewayInstanceId !== void 0 && next.gatewayInstanceId !== void 0 && previous.gatewayInstanceId !== next.gatewayInstanceId;
4278
+ const generationChanged = previous.tunnelGeneration !== void 0 && next.tunnelGeneration !== void 0 && previous.tunnelGeneration !== next.tunnelGeneration;
4279
+ return instanceChanged || generationChanged;
4280
+ }
4281
+ /**
4282
+ * Carry forward identity components the new answer did not repeat.
4283
+ *
4284
+ * A field that appears later is recorded so the *next* change is observable, without treating
4285
+ * its first appearance as a change.
4286
+ * @param previous - Recorded identity, when there is one.
4287
+ * @param next - Identity read from the session or status answer.
4288
+ * @returns The identity to remember.
4289
+ */
4290
+ function mergeTunnelIdentity(previous, next) {
4291
+ return {
4292
+ gatewayInstanceId: next.gatewayInstanceId ?? previous?.gatewayInstanceId,
4293
+ tunnelGeneration: next.tunnelGeneration ?? previous?.tunnelGeneration
4294
+ };
4295
+ }
4296
+ /** Read the JSON body of one control-plane answer, tolerating an empty or malformed one. */
4297
+ async function readJsonBody(response) {
4298
+ if (response.status === 204) return null;
4299
+ try {
4300
+ return await response.json();
4301
+ } catch {
4302
+ return null;
4303
+ }
4304
+ }
4305
+ /**
4306
+ * Classify `POST /session`.
4307
+ * @param status - HTTP status.
4308
+ * @param body - Parsed JSON body, if any.
4309
+ * @returns The answer the session state machine acts on.
4310
+ */
4311
+ function parseSessionAnswer(status, body) {
4312
+ const record = asRecord(body);
4313
+ if (status === 401) return { kind: "unauthorized" };
4314
+ const code = errorCode(record);
4315
+ if (status === 409) {
4316
+ if (code === "COMPANION_OFFLINE") return { kind: "offline" };
4317
+ if (code === "BRIDGE_SESSION_CLOSED") return { kind: "closed" };
4318
+ return {
4319
+ kind: "error",
4320
+ message: `session request refused (HTTP 409${code === void 0 ? "" : ` ${code}`})`
4321
+ };
4322
+ }
4323
+ if (status !== 200) return {
4324
+ kind: "error",
4325
+ message: `session request failed (HTTP ${String(status)}${code === void 0 ? "" : ` ${code}`})`
4326
+ };
4327
+ const sessionId = typeof record?.sessionId === "string" ? record.sessionId : "";
4328
+ const mcpUrl = typeof record?.mcpUrl === "string" ? record.mcpUrl : "";
4329
+ const bridgeToken = typeof record?.bridgeToken === "string" ? record.bridgeToken : "";
4330
+ const expiresAt = readExpiresAt(record?.expiresAt);
4331
+ if (sessionId === "" || mcpUrl === "" || bridgeToken === "" || expiresAt === void 0) return {
4332
+ kind: "error",
4333
+ message: "session response is missing sessionId, mcpUrl, bridgeToken, or expiresAt"
4334
+ };
4335
+ if (!isHttpUrl(mcpUrl)) return {
4336
+ kind: "error",
4337
+ message: "session response carried a non-HTTP mcpUrl"
4338
+ };
4339
+ return {
4340
+ kind: "active",
4341
+ session: {
4342
+ sessionId,
4343
+ deviceId: typeof record?.deviceId === "string" ? record.deviceId : "",
4344
+ mcpUrl,
4345
+ bridgeToken,
4346
+ expiresAt,
4347
+ ...readGatewayInstanceId(record?.gatewayInstanceId) === void 0 ? {} : { gatewayInstanceId: readGatewayInstanceId(record?.gatewayInstanceId) },
4348
+ ...readTunnelGeneration(record?.tunnelGeneration) === void 0 ? {} : { tunnelGeneration: readTunnelGeneration(record?.tunnelGeneration) }
4349
+ }
4350
+ };
4351
+ }
4352
+ /**
4353
+ * Classify `POST /session/:id/refresh`.
4354
+ * @param status - HTTP status.
4355
+ * @param body - Parsed JSON body, if any.
4356
+ * @returns The answer the session state machine acts on.
4357
+ */
4358
+ function parseRefreshAnswer(status, body) {
4359
+ const record = asRecord(body);
4360
+ if (status === 401) return { kind: "unauthorized" };
4361
+ const code = errorCode(record);
4362
+ if (status === 409 && code === "BRIDGE_SESSION_CLOSED") return { kind: "closed" };
4363
+ if (status !== 200) return {
4364
+ kind: "error",
4365
+ message: `bridge token refresh failed (HTTP ${String(status)}${code === void 0 ? "" : ` ${code}`})`
4366
+ };
4367
+ const bridgeToken = typeof record?.bridgeToken === "string" ? record.bridgeToken : "";
4368
+ const expiresAt = readExpiresAt(record?.expiresAt);
4369
+ if (bridgeToken === "" || expiresAt === void 0) return {
4370
+ kind: "error",
4371
+ message: "refresh response is missing bridgeToken or expiresAt"
4372
+ };
4373
+ return {
4374
+ kind: "refreshed",
4375
+ bridgeToken,
4376
+ expiresAt
4377
+ };
4378
+ }
4379
+ /**
4380
+ * Classify `GET /session/:id`.
4381
+ * @param status - HTTP status.
4382
+ * @param body - Parsed JSON body, if any.
4383
+ * @returns The answer the session state machine acts on.
4384
+ */
4385
+ function parseStatusAnswer(status, body) {
4386
+ if (status === 401) return { kind: "unauthorized" };
4387
+ if (status !== 200) {
4388
+ const code = errorCode(asRecord(body));
4389
+ return {
4390
+ kind: "error",
4391
+ message: `session status request failed (HTTP ${String(status)}${code === void 0 ? "" : ` ${code}`})`
4392
+ };
4393
+ }
4394
+ const record = asRecord(body);
4395
+ if (record?.status === "closed") return { kind: "closed" };
4396
+ if (record?.status === "active") return {
4397
+ kind: "active",
4398
+ gatewayInstanceId: readGatewayInstanceId(record.gatewayInstanceId),
4399
+ tunnelGeneration: readTunnelGeneration(record.tunnelGeneration),
4400
+ ...typeof record.deviceOnline === "boolean" ? { deviceOnline: record.deviceOnline } : {}
4401
+ };
4402
+ return {
4403
+ kind: "error",
4404
+ message: "session status response carried no known status"
4405
+ };
4406
+ }
4407
+ /** Call `unref` when the runtime's timer has it, so a retry never holds the process open. */
4408
+ function unrefTimer(timer) {
4409
+ timer.unref?.();
4410
+ }
4411
+ /**
4412
+ * The long-lived browser bridge connection for one workspace.
4413
+ *
4414
+ * Lifecycle:
4415
+ * 1. `start` reads the persisted connector switch; off means no call at all.
4416
+ * 2. `POST /session` with the current JWT. 200 opens the one MCP client, 409
4417
+ * `COMPANION_OFFLINE` retries in a minute, 401 records the expired credential and waits for
4418
+ * the next login.
4419
+ * 3. Every minute the control token is rotated in memory when it is close to expiry. The MCP
4420
+ * client is never recreated for a token refresh.
4421
+ * 4. Every thirty seconds the gateway is asked whether the session is still active. `closed`
4422
+ * is the one server state that disposes the MCP client.
4423
+ * 5. `dispose` closes the session best-effort and clears every timer.
4424
+ */
4425
+ var BrowserBridgeSession = class {
4426
+ deps;
4427
+ enabled = false;
4428
+ phase = "idle";
4429
+ session;
4430
+ mcp;
4431
+ /** The saved `mcpUrl` may have been rotated away; the next attempt reopens the session. */
4432
+ ticketStale = false;
4433
+ /** The gateway/companion pair the current MCP client was initialized against. */
4434
+ tunnelIdentity;
4435
+ detail;
4436
+ refreshTimer;
4437
+ statusTimer;
4438
+ connectPollTimer;
4439
+ retryTimer;
4440
+ ensuring;
4441
+ refreshing = false;
4442
+ checking = false;
4443
+ disposed = false;
4444
+ fetchImpl;
4445
+ now;
4446
+ constructor(deps) {
4447
+ this.deps = deps;
4448
+ this.fetchImpl = deps.fetch ?? fetch;
4449
+ this.now = deps.now ?? (() => Date.now());
4450
+ }
4451
+ /**
4452
+ * Read the connector switch and connect when it is on.
4453
+ *
4454
+ * Called once from plugin activation. It is fire-and-forget from `apply`'s point of view: an
4455
+ * offline companion is a normal state, not an activation failure.
4456
+ * @returns Readiness after the first attempt settles.
4457
+ */
4458
+ async start() {
4459
+ this.enabled = await this.deps.isEnabled();
4460
+ if (this.disposed) return;
4461
+ if (!this.enabled) {
4462
+ this.phase = "disabled";
4463
+ this.stopConnectPoll();
4464
+ return;
4465
+ }
4466
+ this.startConnectPoll();
4467
+ if (this.mcp !== void 0 && this.mcp.alive() && this.session !== void 0) return;
4468
+ await this.ensure();
4469
+ }
4470
+ /**
4471
+ * Apply a connector toggle without a restart.
4472
+ *
4473
+ * Enabling opens a session now; disabling closes the one this workspace holds so the tool
4474
+ * namespace goes away with the switch. The caller does not await the network attempt.
4475
+ * @param enabled - New persisted connector state.
4476
+ */
4477
+ async setEnabled(enabled) {
4478
+ if (this.disposed) return;
4479
+ this.enabled = enabled;
4480
+ if (!enabled) {
4481
+ this.phase = "disabled";
4482
+ this.detail = void 0;
4483
+ this.stopConnectPoll();
4484
+ await this.closeSession();
4485
+ return;
4486
+ }
4487
+ this.startConnectPoll();
4488
+ if (this.session === void 0) this.phase = "connecting";
4489
+ else if (this.mcp !== void 0 && this.mcp.alive()) this.phase = "connected";
4490
+ else this.phase = "connecting";
4491
+ await this.ensure();
4492
+ }
4493
+ /**
4494
+ * React to a newly stored DataOps JWT.
4495
+ *
4496
+ * A 401 pauses the session without disposing the MCP connection, because the ticket in
4497
+ * `mcpUrl` outlives the JWT. The next login is what lets the control plane resume; if no
4498
+ * session exists yet, it is also the moment to open one.
4499
+ * @returns Readiness after any resumed or new work settles.
4500
+ */
4501
+ async onCredentialRefresh() {
4502
+ if (this.disposed) return;
4503
+ this.enabled = await this.deps.isEnabled();
4504
+ if (this.disposed) return;
4505
+ if (!this.enabled) {
4506
+ this.phase = "disabled";
4507
+ this.stopConnectPoll();
4508
+ return;
4509
+ }
4510
+ this.startConnectPoll();
4511
+ if (this.session === void 0) {
4512
+ this.clearRetry();
4513
+ await this.ensure();
4514
+ return;
4515
+ }
4516
+ this.startSchedule();
4517
+ if (this.phase === "expired") this.phase = this.mcp !== void 0 && this.mcp.alive() ? "connected" : "idle";
4518
+ if (this.mcp === void 0 || !this.mcp.alive()) {
4519
+ await this.ensure();
4520
+ return;
4521
+ }
4522
+ if (this.session !== void 0 && expiresSoon(this.session.expiresAt, this.now())) this.checkRefresh();
4523
+ }
4524
+ /**
4525
+ * The live status the connector catalogue renders.
4526
+ * @returns Phase, connection truth, and a token-free hint.
4527
+ */
4528
+ status() {
4529
+ const handleAlive = this.mcp !== void 0 && this.mcp.alive();
4530
+ const sessionActive = this.session !== void 0;
4531
+ const phase = this.phase === "connected" && !(handleAlive && sessionActive) ? "error" : this.phase;
4532
+ return {
4533
+ phase,
4534
+ enabled: this.enabled,
4535
+ connected: this.enabled && phase === "connected" && handleAlive && sessionActive,
4536
+ ...this.session === void 0 ? {} : {
4537
+ sessionId: this.session.sessionId,
4538
+ deviceId: this.session.deviceId,
4539
+ expiresAt: new Date(this.session.expiresAt).toISOString()
4540
+ },
4541
+ ...this.detail === void 0 ? {} : { detail: this.detail }
4542
+ };
4543
+ }
4544
+ /**
4545
+ * Close the session best-effort, dispose the MCP client, and clear every timer.
4546
+ *
4547
+ * Called from the plugin's effect disposer. A failed close is ignored: the gateway prunes
4548
+ * stale sessions, and shutdown must not wait on a control-plane call.
4549
+ * @returns Readiness after cleanup settles.
4550
+ */
4551
+ async dispose() {
4552
+ if (this.disposed) return;
4553
+ this.disposed = true;
4554
+ await this.closeSession();
4555
+ this.phase = "disabled";
4556
+ }
4557
+ /** Serialize connection attempts; a retry, a toggle, and a new JWT must not race. */
4558
+ ensure() {
4559
+ if (this.disposed) return Promise.resolve();
4560
+ if (!this.enabled) {
4561
+ this.phase = "disabled";
4562
+ return Promise.resolve();
4563
+ }
4564
+ if (this.ensuring !== void 0) return this.ensuring;
4565
+ const task = this.ensureNow().finally(() => {
4566
+ if (this.ensuring === task) this.ensuring = void 0;
4567
+ });
4568
+ this.ensuring = task;
4569
+ return task;
4570
+ }
4571
+ /** One connection attempt: reuse the session when one exists, otherwise open one. */
4572
+ async ensureNow() {
4573
+ if (this.mcp !== void 0 && !this.mcp.alive()) {
4574
+ const dead = this.mcp;
4575
+ this.mcp = void 0;
4576
+ await dead.dispose().catch(() => void 0);
4577
+ }
4578
+ if (this.mcp !== void 0) return;
4579
+ if (this.session !== void 0 && !this.ticketStale) {
4580
+ await this.connectMcp();
4581
+ return;
4582
+ }
4583
+ await this.openSession();
4584
+ }
4585
+ /** Ask the gateway for a session, then connect the MCP client it names. */
4586
+ async openSession() {
4587
+ const token = await this.token();
4588
+ if (this.disposed || !this.enabled) return;
4589
+ if (token === void 0) {
4590
+ this.phase = "idle";
4591
+ this.detail = "工作区尚未登录 DataOps";
4592
+ return;
4593
+ }
4594
+ this.phase = "connecting";
4595
+ this.detail = void 0;
4596
+ let response;
4597
+ try {
4598
+ response = await this.fetchImpl(this.endpoint("/api/ai/browser-bridge/session"), {
4599
+ method: "POST",
4600
+ headers: {
4601
+ authorization: `Bearer ${token}`,
4602
+ "content-type": "application/json"
4603
+ },
4604
+ body: JSON.stringify({}),
4605
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
4606
+ });
4607
+ } catch (error) {
4608
+ this.warn("dataops-managed: browser bridge session request failed", error);
4609
+ this.phase = "error";
4610
+ this.detail = "无法连接 DataOps Browser Bridge";
4611
+ this.scheduleRetry();
4612
+ return;
4613
+ }
4614
+ const answer = parseSessionAnswer(response.status, await readJsonBody(response));
4615
+ if (this.disposed || !this.enabled) {
4616
+ if (answer.kind === "active") await this.closeRemote(answer.session.sessionId);
4617
+ return;
4618
+ }
4619
+ switch (answer.kind) {
4620
+ case "active":
4621
+ if (this.mcp !== void 0) {
4622
+ const stale = this.mcp;
4623
+ this.mcp = void 0;
4624
+ await stale.dispose().catch(() => void 0);
4625
+ }
4626
+ this.session = answer.session;
4627
+ this.tunnelIdentity = mergeTunnelIdentity(this.tunnelIdentity, {
4628
+ gatewayInstanceId: answer.session.gatewayInstanceId,
4629
+ tunnelGeneration: answer.session.tunnelGeneration
4630
+ });
4631
+ this.ticketStale = false;
4632
+ this.detail = void 0;
4633
+ this.clearRetry();
4634
+ this.startSchedule();
4635
+ await this.connectMcp();
4636
+ return;
4637
+ case "offline":
4638
+ this.phase = "offline";
4639
+ this.detail = "本机 Companion 未在线(未配对或未启动)";
4640
+ this.scheduleRetry();
4641
+ return;
4642
+ case "unauthorized":
4643
+ noteExpired();
4644
+ this.phase = "expired";
4645
+ this.detail = "DataOps 登录已过期";
4646
+ this.stopTimers();
4647
+ return;
4648
+ case "closed":
4649
+ await this.dropLocal("closed", "桥接会话已关闭");
4650
+ return;
4651
+ case "error":
4652
+ this.phase = "error";
4653
+ this.detail = "建立浏览器桥接会话失败";
4654
+ this.warn(`dataops-managed: ${answer.message}`);
4655
+ this.scheduleRetry();
4656
+ }
4657
+ }
4658
+ /** Create the one MCP client for the current session; failure reopens for a fresh ticket. */
4659
+ async connectMcp() {
4660
+ const session = this.session;
4661
+ if (session === void 0) return;
4662
+ this.phase = "connecting";
4663
+ let handle;
4664
+ try {
4665
+ handle = await this.deps.connectMcp(session.mcpUrl, session.bridgeToken);
4666
+ } catch (error) {
4667
+ this.warn("dataops-managed: browser bridge MCP could not connect", error);
4668
+ this.ticketStale = true;
4669
+ this.stopSchedule();
4670
+ this.phase = "error";
4671
+ this.detail = "浏览器桥接 MCP 连接失败,正在重试";
4672
+ this.scheduleRetry();
4673
+ return;
4674
+ }
4675
+ if (this.disposed || !this.enabled || this.session?.sessionId !== session.sessionId) {
4676
+ await handle.dispose().catch(() => void 0);
4677
+ return;
4678
+ }
4679
+ this.mcp = handle;
4680
+ this.phase = "connected";
4681
+ this.detail = void 0;
4682
+ this.clearRetry();
4683
+ }
4684
+ /** Rotate the control token in memory when it is close to expiry. Never touches the MCP. */
4685
+ async checkRefresh() {
4686
+ if (this.disposed || this.refreshing) return;
4687
+ const session = this.session;
4688
+ if (session === void 0 || !expiresSoon(session.expiresAt, this.now())) return;
4689
+ const token = await this.token();
4690
+ if (this.disposed || token === void 0 || this.session?.sessionId !== session.sessionId) return;
4691
+ this.refreshing = true;
4692
+ try {
4693
+ const response = await this.fetchImpl(this.endpoint(`/api/ai/browser-bridge/session/${encodeURIComponent(session.sessionId)}/refresh`), {
4694
+ method: "POST",
4695
+ headers: {
4696
+ authorization: `Bearer ${token}`,
4697
+ "content-type": "application/json"
4698
+ },
4699
+ body: JSON.stringify({}),
4700
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
4701
+ });
4702
+ const answer = parseRefreshAnswer(response.status, await readJsonBody(response));
4703
+ if (this.disposed || this.session?.sessionId !== session.sessionId) return;
4704
+ switch (answer.kind) {
4705
+ case "refreshed":
4706
+ this.session = {
4707
+ ...session,
4708
+ bridgeToken: answer.bridgeToken,
4709
+ expiresAt: answer.expiresAt
4710
+ };
4711
+ noteAccepted();
4712
+ return;
4713
+ case "unauthorized":
4714
+ noteExpired();
4715
+ this.phase = "expired";
4716
+ this.detail = "DataOps 登录已过期";
4717
+ this.stopSchedule();
4718
+ return;
4719
+ case "closed":
4720
+ await this.dropLocal("closed", "桥接会话已关闭");
4721
+ return;
4722
+ case "error": this.warn(`dataops-managed: ${answer.message}`);
4723
+ }
4724
+ } catch (error) {
4725
+ this.warn("dataops-managed: browser bridge token refresh failed", error);
4726
+ } finally {
4727
+ this.refreshing = false;
4728
+ }
4729
+ }
4730
+ /**
4731
+ * Rebuild the MCP client after the gateway restarted or the companion reconnected.
4732
+ *
4733
+ * Both events invalidate the local MCP `session-id` held by the client, and the client does
4734
+ * not re-initialize on its own. Disposing it and asking the gateway for a session again is
4735
+ * the recovery; the returned ticket is current even when the gateway reuses the row.
4736
+ * @param previous - Identity the current client was initialized against.
4737
+ * @param next - Identity read from the status poll.
4738
+ * @returns Readiness after the rebuild attempt settles.
4739
+ */
4740
+ async reconnectForTunnelChange(previous, next) {
4741
+ const gatewayRestarted = previous.gatewayInstanceId !== void 0 && next.gatewayInstanceId !== void 0 && previous.gatewayInstanceId !== next.gatewayInstanceId;
4742
+ this.phase = "connecting";
4743
+ this.detail = gatewayRestarted ? "Gateway 已重启,正在恢复浏览器通道" : "Companion 已重连,正在恢复浏览器通道";
4744
+ this.stopSchedule();
4745
+ const handle = this.mcp;
4746
+ this.mcp = void 0;
4747
+ if (handle !== void 0) await handle.dispose().catch(() => void 0);
4748
+ this.ticketStale = true;
4749
+ await this.ensure();
4750
+ if (this.status().connected) this.startSchedule();
4751
+ }
4752
+ /** Ask the gateway whether the session is still active; `closed` releases the MCP client. */
4753
+ async checkStatus() {
4754
+ if (this.disposed || this.checking) return;
4755
+ const session = this.session;
4756
+ if (session === void 0) return;
4757
+ const token = await this.token();
4758
+ if (this.disposed || token === void 0 || this.session?.sessionId !== session.sessionId) return;
4759
+ this.checking = true;
4760
+ try {
4761
+ const response = await this.fetchImpl(this.endpoint(`/api/ai/browser-bridge/session/${encodeURIComponent(session.sessionId)}`), {
4762
+ method: "GET",
4763
+ headers: { authorization: `Bearer ${token}` },
4764
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
4765
+ });
4766
+ const answer = parseStatusAnswer(response.status, await readJsonBody(response));
4767
+ if (this.disposed || this.session?.sessionId !== session.sessionId) return;
4768
+ switch (answer.kind) {
4769
+ case "active": {
4770
+ noteAccepted();
4771
+ const previous = this.tunnelIdentity;
4772
+ const next = {
4773
+ gatewayInstanceId: answer.gatewayInstanceId,
4774
+ tunnelGeneration: answer.tunnelGeneration
4775
+ };
4776
+ if (previous !== void 0 && tunnelIdentityChanged(previous, next)) {
4777
+ this.tunnelIdentity = mergeTunnelIdentity(previous, next);
4778
+ await this.reconnectForTunnelChange(previous, next);
4779
+ return;
4780
+ }
4781
+ this.tunnelIdentity = mergeTunnelIdentity(previous, next);
4782
+ if (answer.deviceOnline === false) {
4783
+ await this.closeRemote(session.sessionId);
4784
+ await this.dropLocal("offline", "Companion 离线,等待设备恢复");
4785
+ this.startConnectPoll();
4786
+ return;
4787
+ }
4788
+ if (this.phase === "expired") this.phase = this.mcp !== void 0 && this.mcp.alive() ? "connected" : "idle";
4789
+ if (this.mcp === void 0 || !this.mcp.alive()) this.ensure();
4790
+ return;
4791
+ }
4792
+ case "closed":
4793
+ await this.dropLocal("closed", "桥接会话已关闭");
4794
+ return;
4795
+ case "unauthorized":
4796
+ noteExpired();
4797
+ this.phase = "expired";
4798
+ this.detail = "DataOps 登录已过期";
4799
+ this.stopSchedule();
4800
+ return;
4801
+ case "error": this.warn(`dataops-managed: ${answer.message}`);
4802
+ }
4803
+ } catch (error) {
4804
+ this.warn("dataops-managed: browser bridge session status check failed", error);
4805
+ } finally {
4806
+ this.checking = false;
4807
+ }
4808
+ }
4809
+ /** Start the refresh and status clocks; idempotent so a resumed session cannot double them. */
4810
+ /**
4811
+ * 连接探测时钟:未连接时每 30 秒问一次网关「有在线设备/有人请求连接吗」。
4812
+ *
4813
+ * 这条路径不依赖已有 session:设备撤销、重新配对、Gateway 重启后插件都能自己恢复,
4814
+ * 不需要重启 DSH;已有健康会话时什么都不做,避免无谓请求。
4815
+ */
4816
+ startConnectPoll() {
4817
+ if (this.disposed || !this.enabled || this.connectPollTimer !== void 0) return;
4818
+ this.connectPollTimer = setInterval(() => {
4819
+ this.checkConnectionOffer();
4820
+ }, STATUS_INTERVAL_MS);
4821
+ unrefTimer(this.connectPollTimer);
4822
+ }
4823
+ stopConnectPoll() {
4824
+ if (this.connectPollTimer !== void 0) clearInterval(this.connectPollTimer);
4825
+ this.connectPollTimer = void 0;
4826
+ }
4827
+ /** 没有健康会话时读取网关连接摘要;有在线设备或 connectRequested 就重新建会话。 */
4828
+ async checkConnectionOffer() {
4829
+ if (this.disposed || !this.enabled) return;
4830
+ if (this.retryTimer !== void 0 || this.ensuring !== void 0) return;
4831
+ if (this.session !== void 0 && this.mcp !== void 0 && this.mcp.alive()) return;
4832
+ const token = await this.token();
4833
+ if (this.disposed || token === void 0 || !this.enabled) return;
4834
+ try {
4835
+ const response = await this.fetchImpl(this.endpoint("/api/ai/browser-bridge/status"), {
4836
+ method: "GET",
4837
+ headers: { authorization: `Bearer ${token}` },
4838
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
4839
+ });
4840
+ if (this.disposed || !this.enabled) return;
4841
+ if (response.status === 401) {
4842
+ noteExpired();
4843
+ this.phase = "expired";
4844
+ this.detail = "DataOps 登录已过期";
4845
+ return;
4846
+ }
4847
+ if (!response.ok) return;
4848
+ const body = await readJsonBody(response);
4849
+ const online = body?.activeSession?.deviceOnline === true || Array.isArray(body?.devices) && body.devices.some((device) => device?.online === true);
4850
+ if (body?.connectRequested === true || online) {
4851
+ this.clearRetry();
4852
+ await this.ensure();
4853
+ }
4854
+ } catch (error) {
4855
+ this.warn("dataops-managed: browser bridge connection probe failed (ignored)", error);
4856
+ }
4857
+ }
4858
+ startSchedule() {
4859
+ if (this.disposed || this.session === void 0) return;
4860
+ this.stopSchedule();
4861
+ this.refreshTimer = setInterval(() => {
4862
+ this.checkRefresh();
4863
+ }, REFRESH_INTERVAL_MS);
4864
+ this.statusTimer = setInterval(() => {
4865
+ this.checkStatus();
4866
+ }, STATUS_INTERVAL_MS);
4867
+ unrefTimer(this.refreshTimer);
4868
+ unrefTimer(this.statusTimer);
4869
+ }
4870
+ /** Stop both clocks; a paused session resumes them after the next JWT. */
4871
+ stopSchedule() {
4872
+ if (this.refreshTimer !== void 0) clearInterval(this.refreshTimer);
4873
+ this.refreshTimer = void 0;
4874
+ if (this.statusTimer !== void 0) clearInterval(this.statusTimer);
4875
+ this.statusTimer = void 0;
4876
+ }
4877
+ /** Ask for one retry after {@link RETRY_DELAY_MS}; only while the connector is on. */
4878
+ scheduleRetry() {
4879
+ if (this.disposed || !this.enabled) return;
4880
+ if (this.retryTimer !== void 0) return;
4881
+ this.retryTimer = setTimeout(() => {
4882
+ this.retryTimer = void 0;
4883
+ this.ensure();
4884
+ }, RETRY_DELAY_MS);
4885
+ unrefTimer(this.retryTimer);
4886
+ }
4887
+ /** Cancel a pending retry, including on the success path. */
4888
+ clearRetry() {
4889
+ if (this.retryTimer !== void 0) clearTimeout(this.retryTimer);
4890
+ this.retryTimer = void 0;
4891
+ }
4892
+ /** Stop every clock this session owns. */
4893
+ stopTimers() {
4894
+ this.stopSchedule();
4895
+ this.clearRetry();
4896
+ }
4897
+ /** Close the current session: best-effort remote close, then local disposal. */
4898
+ async closeSession() {
4899
+ const sessionId = this.session?.sessionId;
4900
+ this.session = void 0;
4901
+ this.ticketStale = false;
4902
+ this.tunnelIdentity = void 0;
4903
+ this.stopTimers();
4904
+ const handle = this.mcp;
4905
+ this.mcp = void 0;
4906
+ if (sessionId !== void 0) await this.closeRemote(sessionId);
4907
+ if (handle !== void 0) await handle.dispose().catch(() => void 0);
4908
+ }
4909
+ /** Release an MCP client and state the server already closed; no close call needed. */
4910
+ async dropLocal(phase, detail) {
4911
+ this.stopTimers();
4912
+ const handle = this.mcp;
4913
+ this.mcp = void 0;
4914
+ this.session = void 0;
4915
+ this.ticketStale = false;
4916
+ this.tunnelIdentity = void 0;
4917
+ this.phase = phase;
4918
+ this.detail = detail;
4919
+ if (handle !== void 0) await handle.dispose().catch(() => void 0);
4920
+ }
4921
+ /** Best-effort `POST /session/:id/close`; every failure is ignored by design. */
4922
+ async closeRemote(sessionId) {
4923
+ const token = await this.token();
4924
+ if (token === void 0) return;
4925
+ try {
4926
+ await this.fetchImpl(this.endpoint(`/api/ai/browser-bridge/session/${encodeURIComponent(sessionId)}/close`), {
4927
+ method: "POST",
4928
+ headers: { authorization: `Bearer ${token}` },
4929
+ signal: AbortSignal.timeout(CLOSE_TIMEOUT_MS)
4930
+ });
4931
+ } catch (error) {
4932
+ this.warn("dataops-managed: browser bridge close request failed (ignored)", error);
4933
+ }
4934
+ }
4935
+ /** Resolve the current JWT, tolerating a host that is already tearing down. */
4936
+ async token() {
4937
+ try {
4938
+ const value = await this.deps.resolveToken();
4939
+ return value === void 0 || value === "" ? void 0 : value;
4940
+ } catch {
4941
+ return;
4942
+ }
4943
+ }
4944
+ /** Absolute control-plane URL below the DataOps origin. */
4945
+ endpoint(path) {
4946
+ return new URL(path, this.deps.baseUrl);
4947
+ }
4948
+ /** Log one sanitized diagnostic. */
4949
+ warn(message, error) {
4950
+ this.deps.logger.warn(error === void 0 ? message : `${message}: ${describeError(error)}`);
4951
+ }
4952
+ };
4953
+ //#endregion
4089
4954
  //#region src/index.ts
4090
4955
  /** Cordis plugin name for the DataOps-managed integration. */
4091
4956
  const name = "dataops-managed";
@@ -4381,6 +5246,35 @@ const prefectScriptSkillProvider = {
4381
5246
  };
4382
5247
  }
4383
5248
  };
5249
+ /** The skill that teaches the model how to use the local browser companion. */
5250
+ const BROWSER_SKILL_NAME = "browser-bridge-companion";
5251
+ const BROWSER_SKILL_FILE = new URL("../skills/browser-bridge-companion/SKILL.md", import.meta.url);
5252
+ const BROWSER_SKILL = {
5253
+ name: BROWSER_SKILL_NAME,
5254
+ description: "用户要在自己的本地 Chrome/Edge 里打开内网系统、登录、点页面、填表、截图或做网页自动化时使用。先完成 8 位配对码配对、确认 Companion 在线且连接器显示已连接,再调用 browser_* 工具;登录/验证码必须让用户接管,不要索取密码,不要导出 Cookie。",
5255
+ invocation: {
5256
+ modelInvocable: true,
5257
+ userInvocable: true
5258
+ },
5259
+ provider: BROWSER_SKILL_NAME,
5260
+ source: "bundled",
5261
+ resourceBase: {
5262
+ kind: "directory",
5263
+ path: fileURLToPath(new URL("../", import.meta.url))
5264
+ },
5265
+ rank: BUNDLED_SKILL_RANK,
5266
+ locator: BROWSER_SKILL_FILE
5267
+ };
5268
+ const browserSkillProvider = {
5269
+ name: BROWSER_SKILL_NAME,
5270
+ list: () => Promise.resolve([BROWSER_SKILL]),
5271
+ async get() {
5272
+ return {
5273
+ ...BROWSER_SKILL,
5274
+ content: await readFile(BROWSER_SKILL_FILE, "utf8")
5275
+ };
5276
+ }
5277
+ };
4384
5278
  const PROVISIONING_SKILL_NAME = "skill-provisioning";
4385
5279
  const PROVISIONING_SKILL_FILE = new URL("../skills/skill-provisioning/SKILL.md", import.meta.url);
4386
5280
  /** 该技能只对持有 `skill:manage` 的身份展示:它驱动的分配工具使用同一能力。 */
@@ -4432,6 +5326,15 @@ const collectSkillProvider = {
4432
5326
  */
4433
5327
  async function apply(ctx, config) {
4434
5328
  const baseUrl = new URL(config.baseUrl).origin;
5329
+ /**
5330
+ * 门户 origin:本机 Companion 的配对 API 需要用它作为 serverUrl,才能经门户
5331
+ * 的同源代理(`/api` 与 `/browser-bridge-ws`)回到 backend。优先取配置的第一个
5332
+ * `webBaseUrl`,否则退回 backend origin。
5333
+ */
5334
+ const portalOrigin = () => {
5335
+ const configured = (config.webBaseUrl ?? "").split(",").map((value) => value.trim()).find((value) => value !== "" && URL.canParse(value));
5336
+ return configured === void 0 ? baseUrl : new URL(configured).origin;
5337
+ };
4435
5338
  const accessRef = credentialRef(config.credentialRef);
4436
5339
  let mcpFiber;
4437
5340
  ctx.skills.registerProvider(() => querySkillProvider);
@@ -4439,6 +5342,7 @@ async function apply(ctx, config) {
4439
5342
  ctx.skills.registerProvider(() => connectorSkillProvider);
4440
5343
  ctx.skills.registerProvider(() => prefectScriptSkillProvider);
4441
5344
  ctx.skills.registerProvider(() => provisioningSkillProvider);
5345
+ ctx.skills.registerProvider(() => browserSkillProvider);
4442
5346
  const ensureMcp = async () => {
4443
5347
  if (mcpFiber !== void 0 && mcpFiber.uid !== null) return;
4444
5348
  const fiber = ctx.plugin(McpClient, {
@@ -4452,16 +5356,54 @@ async function apply(ctx, config) {
4452
5356
  mcpFiber = fiber;
4453
5357
  try {
4454
5358
  await fiber.await();
5359
+ ctx.logger.warn("dataops-managed: browser bridge MCP connected");
4455
5360
  } catch (error) {
4456
5361
  if (mcpFiber === fiber) mcpFiber = void 0;
4457
5362
  await fiber.dispose();
4458
5363
  throw error;
4459
5364
  }
4460
5365
  };
5366
+ /**
5367
+ * The browser bridge, reached through the DataOps gateway.
5368
+ *
5369
+ * The gateway is the only entry. With the current DataOps JWT the plugin asks for a session
5370
+ * and receives an `mcpUrl` whose ticket is the connection capability; the profile and the
5371
+ * environment carry no bridge address, so a workspace cannot point itself at another user's
5372
+ * companion. `connectMcp` creates exactly one MCP client per session; the session module
5373
+ * owns token refresh and closure.
5374
+ */
5375
+ const browserBridge = new BrowserBridgeSession({
5376
+ baseUrl,
5377
+ resolveToken: async () => (await ctx.credentials.resolve(accessRef))?.value,
5378
+ isEnabled: async () => (await readBrowserBridgeState()).enabled,
5379
+ connectMcp: async (mcpUrl, bridgeToken) => {
5380
+ const fiber = ctx.plugin(McpClient, {
5381
+ transport: "streamable-http",
5382
+ serverName: "browser-bridge",
5383
+ url: mcpUrl,
5384
+ headers: { authorization: `Bearer ${bridgeToken}` },
5385
+ toolCallTimeoutMs: volatileValue(config.toolCallTimeoutMs, DEFAULT_TOOL_CALL_TIMEOUT_MS)
5386
+ });
5387
+ try {
5388
+ await fiber.await();
5389
+ } catch (error) {
5390
+ if (fiber.uid !== null) await fiber.dispose();
5391
+ throw error;
5392
+ }
5393
+ return {
5394
+ alive: () => fiber.uid !== null,
5395
+ dispose: async () => {
5396
+ if (fiber.uid !== null) await fiber.dispose();
5397
+ }
5398
+ };
5399
+ },
5400
+ logger: { warn: (message) => ctx.logger.warn(message) }
5401
+ });
4461
5402
  ctx.effect(() => async () => {
4462
5403
  const fiber = mcpFiber;
4463
5404
  mcpFiber = void 0;
4464
5405
  if (fiber !== void 0 && fiber.uid !== null) await fiber.dispose();
5406
+ await browserBridge.dispose();
4465
5407
  }, "dataops-managed: MCP lifecycle");
4466
5408
  /**
4467
5409
  * Connect the MCP client when a JWT is already stored.
@@ -4485,6 +5427,7 @@ async function apply(ctx, config) {
4485
5427
  ctx.logger.warn("dataops-managed: connecting the DataOps MCP server failed; the settings routes stay up so a new JWT can be connected");
4486
5428
  ctx.logger.warn(error);
4487
5429
  }
5430
+ browserBridge.start();
4488
5431
  };
4489
5432
  /**
4490
5433
  * The sync state lives in this plugin's own Config, so the settings service persists it in
@@ -4715,6 +5658,7 @@ async function apply(ctx, config) {
4715
5658
  ctx.effect(() => ctx.on("credentials/reference-updated", (ref) => {
4716
5659
  if (String(ref) !== config.credentialRef) return;
4717
5660
  aiTools.refresh(true);
5661
+ browserBridge.onCredentialRefresh();
4718
5662
  }), "dataops-managed: tool disclosure follows the DataOps credential");
4719
5663
  setWorkspaceLimits(new WorkspaceLimits(ctx, {
4720
5664
  baseUrl,
@@ -4778,6 +5722,7 @@ async function apply(ctx, config) {
4778
5722
  }
4779
5723
  resetAuthState();
4780
5724
  aiTools.refresh(true);
5725
+ browserBridge.onCredentialRefresh();
4781
5726
  await ensureMcp();
4782
5727
  await adoptNow();
4783
5728
  response.writeHead(204, { "cache-control": "no-store" });
@@ -5489,6 +6434,64 @@ async function apply(ctx, config) {
5489
6434
  }
5490
6435
  }), "dataops-managed: auth state route");
5491
6436
  /**
6437
+ * 本机一键配对的配对码来源。
6438
+ *
6439
+ * DSH 页面里的客户端脚本先探测 `127.0.0.1:8932/status`;未配对时调用本路由拿
6440
+ * 一次性配对码,再直接 POST 给本机 Companion。配对码不经过用户、不写日志。
6441
+ */
6442
+ ctx.effect(() => ctx.webServer.register({
6443
+ kind: "exact",
6444
+ path: "/integrations/dataops/browser-bridge/auto-pair",
6445
+ handler: async (request, response) => {
6446
+ if ((request.method ?? "GET").toUpperCase() !== "POST") {
6447
+ response.writeHead(405, {
6448
+ allow: "POST",
6449
+ "content-length": "0"
6450
+ });
6451
+ response.end();
6452
+ return;
6453
+ }
6454
+ try {
6455
+ if (!(await readBrowserBridgeState()).enabled) {
6456
+ writeJson(response, 409, { error: "浏览器桥接连接器未启用" });
6457
+ return;
6458
+ }
6459
+ const token = await ctx.credentials.resolve(accessRef);
6460
+ if (token === void 0 || token.value === "") {
6461
+ writeJson(response, 401, { error: "工作区尚未登录 DataOps" });
6462
+ return;
6463
+ }
6464
+ const upstream = await fetch(new URL("/api/ai/browser-bridge/pair/start", baseUrl), {
6465
+ method: "POST",
6466
+ headers: {
6467
+ authorization: `Bearer ${token.value}`,
6468
+ "content-type": "application/json"
6469
+ },
6470
+ body: "{}",
6471
+ signal: AbortSignal.timeout(15e3)
6472
+ });
6473
+ if (!upstream.ok) {
6474
+ writeJson(response, upstream.status === 401 ? 401 : 502, { error: upstream.status === 401 ? "DataOps 登录已过期" : "配对码生成失败" });
6475
+ return;
6476
+ }
6477
+ const payload = await upstream.json();
6478
+ if (typeof payload.code !== "string" || typeof payload.expiresAt !== "string") {
6479
+ writeJson(response, 502, { error: "配对码响应格式不正确" });
6480
+ return;
6481
+ }
6482
+ writeJson(response, 200, {
6483
+ code: payload.code,
6484
+ expiresAt: payload.expiresAt,
6485
+ serverUrl: portalOrigin()
6486
+ });
6487
+ } catch (error) {
6488
+ ctx.logger.warn("dataops-managed: browser bridge auto-pair failed");
6489
+ ctx.logger.warn(error);
6490
+ writeJson(response, 502, { error: "自动配对失败" });
6491
+ }
6492
+ }
6493
+ }), "dataops-managed: browser bridge auto pair");
6494
+ /**
5492
6495
  * The skill center's connector tab. The route is a same-origin presentation bridge: reads
5493
6496
  * return only capabilities the current scope can use, and writes persist the connector's own
5494
6497
  * enable state. It never substitutes for a DataOps authorization decision.
@@ -5501,7 +6504,8 @@ async function apply(ctx, config) {
5501
6504
  if (request.method === "GET") {
5502
6505
  if (aiTools.currentScope() === void 0) await aiTools.refresh();
5503
6506
  const state = await readConnectorState();
5504
- writeJson(response, 200, { connectors: [buildConnectorView(aiTools.currentScope(), state)] });
6507
+ const bridgeState = await readBrowserBridgeState();
6508
+ writeJson(response, 200, { connectors: [buildConnectorView(aiTools.currentScope(), state), buildBrowserBridgeConnectorView(bridgeState, browserBridge.status())] });
5505
6509
  return;
5506
6510
  }
5507
6511
  if (request.method === "POST") {
@@ -5510,6 +6514,19 @@ async function apply(ctx, config) {
5510
6514
  writeJson(response, 400, { error: "connector state requires a JSON body" });
5511
6515
  return;
5512
6516
  }
6517
+ if (body.connectorId === "browser-bridge") {
6518
+ if (typeof body.enabled !== "boolean") {
6519
+ writeJson(response, 400, { error: "connector state requires enabled:boolean" });
6520
+ return;
6521
+ }
6522
+ const bridgeState = await readBrowserBridgeState();
6523
+ bridgeState.enabled = body.enabled;
6524
+ await writeBrowserBridgeState(bridgeState);
6525
+ browserBridge.setEnabled(body.enabled);
6526
+ const state = await readConnectorState();
6527
+ writeJson(response, 200, { connectors: [buildConnectorView(aiTools.currentScope(), state), buildBrowserBridgeConnectorView(bridgeState, browserBridge.status())] });
6528
+ return;
6529
+ }
5513
6530
  if (body.connectorId !== "dataops-managed") {
5514
6531
  writeJson(response, 404, { error: "unknown connector" });
5515
6532
  return;
@@ -5539,7 +6556,8 @@ async function apply(ctx, config) {
5539
6556
  }
5540
6557
  await writeConnectorState(state);
5541
6558
  await aiTools.refreshCapabilities();
5542
- writeJson(response, 200, { connectors: [buildConnectorView(aiTools.currentScope(), state)] });
6559
+ const bridgeState = await readBrowserBridgeState();
6560
+ writeJson(response, 200, { connectors: [buildConnectorView(aiTools.currentScope(), state), buildBrowserBridgeConnectorView(bridgeState, browserBridge.status())] });
5543
6561
  return;
5544
6562
  }
5545
6563
  response.writeHead(405, {
@@ -5554,6 +6572,53 @@ async function apply(ctx, config) {
5554
6572
  }
5555
6573
  }
5556
6574
  }), "dataops-managed: skill-center connector catalogue");
6575
+ /**
6576
+ * Installer download for the browser-bridge connector.
6577
+ *
6578
+ * The file is local state, not a model tool and not an arbitrary proxy: an
6579
+ * operator places a signed installer at DSH_BROWSER_BRIDGE_INSTALLER_PATH
6580
+ * (default under DSH_HOME) and this route streams that exact file.
6581
+ */
6582
+ ctx.effect(() => ctx.webServer.register({
6583
+ kind: "exact",
6584
+ path: BROWSER_BRIDGE_INSTALLER_PATH,
6585
+ handler: async (request, response) => {
6586
+ if (request.method !== "GET") {
6587
+ response.writeHead(405, {
6588
+ allow: "GET",
6589
+ "content-length": "0"
6590
+ });
6591
+ response.end();
6592
+ return;
6593
+ }
6594
+ const artifactUrl = process.env.DSH_BROWSER_BRIDGE_INSTALLER_URL?.trim() ?? "";
6595
+ if (artifactUrl !== "") {
6596
+ response.writeHead(302, {
6597
+ location: artifactUrl,
6598
+ "cache-control": "no-store",
6599
+ "x-content-type-options": "nosniff"
6600
+ });
6601
+ response.end();
6602
+ return;
6603
+ }
6604
+ const configured = process.env.DSH_BROWSER_BRIDGE_INSTALLER_PATH?.trim() ?? "";
6605
+ const installerPath = configured !== "" ? configured : join(process.env.DSH_HOME?.trim() || "/workspace/.dataops/dsh", "runtime-connectors", "browser-bridge", "DSH-Browser-Bridge-Setup-Windows-x64-v0.1.0.exe");
6606
+ try {
6607
+ if (!(await stat(installerPath)).isFile()) throw new Error("installer is not a file");
6608
+ const bytes = await readFile(installerPath);
6609
+ response.writeHead(200, {
6610
+ "content-type": "application/octet-stream",
6611
+ "content-disposition": "attachment; filename=\"" + basename(installerPath).replace(/["\\]/gu, "") + "\"",
6612
+ "content-length": String(bytes.byteLength),
6613
+ "cache-control": "no-store",
6614
+ "x-content-type-options": "nosniff"
6615
+ });
6616
+ response.end(bytes);
6617
+ } catch {
6618
+ writeJson(response, 404, { error: "bridge installer is not available in this workspace" });
6619
+ }
6620
+ }
6621
+ }), "dataops-managed: browser bridge installer");
5557
6622
  await connectExisting();
5558
6623
  }
5559
6624
  /** Read and parse a JSON request body, tolerating an absent one. */