@modootoday/datalab-extension-mcp 1.17.1 → 1.18.1

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.
@@ -2,7 +2,27 @@ import {
2
2
  __export
3
3
  } from "./chunk-MLKGABMK.js";
4
4
 
5
- // ../mcp-server/dist/chunk-4WAZJ5ZG.js
5
+ // ../mcp-server/dist/chunk-VW3KJGSK.js
6
+ import {
7
+ appendFileSync,
8
+ mkdirSync,
9
+ openSync,
10
+ renameSync,
11
+ statSync
12
+ } from "fs";
13
+ import { homedir } from "os";
14
+ import { join } from "path";
15
+ import { readFileSync, rmSync } from "fs";
16
+ import { homedir as homedir2 } from "os";
17
+ import { join as join3 } from "path";
18
+ import { chmodSync, mkdirSync as mkdirSync2, writeFileSync } from "fs";
19
+ import { dirname } from "path";
20
+ import { spawnSync } from "child_process";
21
+ import { userInfo } from "os";
22
+ import { join as join2 } from "path";
23
+ import { readFileSync as readFileSync2 } from "fs";
24
+ import { homedir as homedir3 } from "os";
25
+ import { join as join4 } from "path";
6
26
  import { createHash } from "crypto";
7
27
  import { createHash as createHash2, randomUUID } from "crypto";
8
28
  import { createReadStream, createWriteStream } from "fs";
@@ -16,39 +36,28 @@ import {
16
36
  stat,
17
37
  writeFile
18
38
  } from "fs/promises";
19
- import { join } from "path";
39
+ import { join as join5 } from "path";
20
40
  import { Transform } from "stream";
21
41
  import { pipeline } from "stream/promises";
22
- import {
23
- createServer
24
- } from "http";
42
+ import { createServer } from "http";
25
43
  import { pipeline as pipeline2 } from "stream/promises";
26
44
  import { constants } from "fs";
27
45
  import { lstat, open as open3 } from "fs/promises";
28
46
  import { basename, isAbsolute } from "path";
29
47
  import { Readable } from "stream";
30
- import {
31
- appendFileSync,
32
- mkdirSync,
33
- openSync,
34
- renameSync,
35
- statSync
36
- } from "fs";
37
- import { homedir } from "os";
38
- import { join as join2 } from "path";
39
48
  import { createConnection } from "net";
40
49
  import { spawn } from "child_process";
41
50
  import { closeSync } from "fs";
42
51
  import { randomBytes } from "crypto";
43
- import { chmodSync, mkdirSync as mkdirSync2, readFileSync, writeFileSync } from "fs";
44
- import { homedir as homedir2 } from "os";
45
- import { join as join3 } from "path";
52
+ import { readFileSync as readFileSync3 } from "fs";
53
+ import { homedir as homedir4 } from "os";
54
+ import { join as join6 } from "path";
46
55
  import { timingSafeEqual as timingSafeEqual2 } from "crypto";
47
56
  import { createRequire } from "module";
48
- import { join as join5 } from "path";
57
+ import { join as join8 } from "path";
49
58
  import { createHash as createHash3, randomUUID as randomUUID2 } from "crypto";
50
59
  import { appendFile, mkdir as mkdir2, rename as rename2, rm as rm2, stat as stat2 } from "fs/promises";
51
- import { join as join4 } from "path";
60
+ import { join as join7 } from "path";
52
61
  var __defProp = Object.defineProperty;
53
62
  var __export2 = (target, all) => {
54
63
  for (var name in all)
@@ -19822,6 +19831,7 @@ function timingSafeEqual(a, b) {
19822
19831
  return equal(left, right);
19823
19832
  }
19824
19833
  var MIN_TOKEN_LENGTH = 32;
19834
+ var PUBLISHED_EXTENSION_ID = "ldoknfkedngbdfgdkeicojmhnojgpdcb";
19825
19835
  function checkToken(presented, expected) {
19826
19836
  const fail = {
19827
19837
  ok: false,
@@ -19881,6 +19891,70 @@ function resolveCredential(presented, known) {
19881
19891
  if (browserId === void 0 || browserId.length === 0) return REFUSED;
19882
19892
  return { kind: "claimed", browserId };
19883
19893
  }
19894
+ var PAIRING_ROUTE = "/bridge/pairing";
19895
+ var APP_NAME_MAX = 64;
19896
+ function normalizeAppName(raw) {
19897
+ if (typeof raw !== "string") return null;
19898
+ const printable = Array.from(raw, (ch) => {
19899
+ const code = ch.charCodeAt(0);
19900
+ return code < 32 || code === 127 ? " " : ch;
19901
+ });
19902
+ const cleaned = printable.join("").trim();
19903
+ if (cleaned.length === 0) return null;
19904
+ return cleaned.slice(0, APP_NAME_MAX);
19905
+ }
19906
+ var PairingActionSchema = external_exports.enum([
19907
+ "status",
19908
+ "approve",
19909
+ "refuse",
19910
+ "revoke"
19911
+ ]);
19912
+ var PairingRequestSchema = external_exports.object({
19913
+ action: PairingActionSchema,
19914
+ /** The panel's pairing token. Approving while unpaired pairs with it. */
19915
+ token: external_exports.string(),
19916
+ /** The extension's own id; the panel's service worker sends no Origin. */
19917
+ extensionId: external_exports.string().optional(),
19918
+ /** The app an approve, refuse or revoke is about. */
19919
+ app: external_exports.string().max(APP_NAME_MAX).optional()
19920
+ });
19921
+ var PendingAppSchema = external_exports.object({
19922
+ name: external_exports.string(),
19923
+ /** Epoch ms of the first call that asked. */
19924
+ askedAt: external_exports.number().int().nonnegative()
19925
+ });
19926
+ var ApprovedAppSchema = external_exports.object({
19927
+ name: external_exports.string(),
19928
+ /** ISO time of the user's approval. */
19929
+ approvedAt: external_exports.string()
19930
+ });
19931
+ var PairingStatusSchema = external_exports.object({
19932
+ /** A pairing record or a configured token exists on this computer. */
19933
+ paired: external_exports.boolean(),
19934
+ /** The presented token is the paired one. False for another browser profile. */
19935
+ yours: external_exports.boolean(),
19936
+ /** An unpaired connector still accepts a claim. */
19937
+ windowOpen: external_exports.boolean(),
19938
+ /** Epoch ms when the claim window ends; null once paired. */
19939
+ windowEndsAt: external_exports.number().int().nonnegative().nullable(),
19940
+ /** Empty unless the presented token is the paired one, or nothing is paired yet. */
19941
+ pending: external_exports.array(PendingAppSchema),
19942
+ /** Empty unless the presented token is the paired one. */
19943
+ apps: external_exports.array(ApprovedAppSchema)
19944
+ });
19945
+ var PairingRefusalSchema = external_exports.enum([
19946
+ "forbidden_origin",
19947
+ "unauthorized",
19948
+ "paired_elsewhere",
19949
+ "window_closed",
19950
+ "unknown_app",
19951
+ "bad_request"
19952
+ ]);
19953
+ var PairingAnswerSchema = external_exports.discriminatedUnion("ok", [
19954
+ external_exports.object({ ok: external_exports.literal(true), status: PairingStatusSchema }),
19955
+ external_exports.object({ ok: external_exports.literal(false), reason: PairingRefusalSchema })
19956
+ ]);
19957
+ var MCP_APP_HEADER = "x-datalab-mcp-app";
19884
19958
  var READ_ONLY_TOOLS = [
19885
19959
  "datalab_browsers",
19886
19960
  // --- Search-ad estimates. Uses the user's own advertiser API credentials. ---
@@ -20118,6 +20192,7 @@ var TOOL_TIERS = Object.freeze({
20118
20192
  photo_inpaint: "write",
20119
20193
  photo_group: "write",
20120
20194
  photo_ungroup: "write",
20195
+ photo_redact_add: "write",
20121
20196
  // ── Gallery: the free way in ────────────────────────────────────
20122
20197
  //
20123
20198
  // Destructive because it reads a path off the user's disk, the same
@@ -20173,11 +20248,13 @@ var TOOL_TIERS = Object.freeze({
20173
20248
  video_marker_add: "write",
20174
20249
  video_marker_remove: "destructive",
20175
20250
  video_lane_set: "write",
20251
+ video_subtitle_style_set: "write",
20176
20252
  video_auto_edit: "write",
20177
20253
  video_template_list: "read",
20178
20254
  video_template_apply: "destructive",
20179
20255
  video_post_import: "write",
20180
20256
  video_source_add: "write",
20257
+ video_redact_add: "write",
20181
20258
  // ── Post editor: reads ──────────────────────────────────────────
20182
20259
  editor_read: "read",
20183
20260
  editor_read_structure: "read",
@@ -20249,6 +20326,8 @@ var TOOL_TIERS = Object.freeze({
20249
20326
  tab_open: "write",
20250
20327
  tab_focus: "write",
20251
20328
  tab_close: "destructive",
20329
+ // Runs the caller's own code in one open tab, so it can do anything that page can.
20330
+ tab_debug: "destructive",
20252
20331
  // Insertion appends, so it never passes through the overwrite prompt; the
20253
20332
  // tier is the only barrier, and the user approves each image's source.
20254
20333
  editor_insert_image: "destructive",
@@ -20283,6 +20362,9 @@ var TOOL_TIERS = Object.freeze({
20283
20362
  editor_insert_component: "write",
20284
20363
  editor_replace: "destructive"
20285
20364
  });
20365
+ var ADMITTED_TOOLS = Object.freeze([
20366
+ .../* @__PURE__ */ new Set([...READ_ONLY_TOOLS, ...Object.keys(TOOL_TIERS)])
20367
+ ]);
20286
20368
  var PAID_TOOL_COSTS = Object.freeze({
20287
20369
  video_narration_generate: Object.freeze({
20288
20370
  basis: "\uBAA9\uC18C\uB9AC\uAC00 \uC5C6\uB294 \uC7A5\uBA74 \uC218\uB9CC\uD07C \uC74C\uC131 \uC0DD\uC131",
@@ -20642,6 +20724,307 @@ function splitResultImages(result) {
20642
20724
  return { result: rest, images };
20643
20725
  }
20644
20726
  var MCP_SERVER_HEALTH_NAME = "datalab-extension-mcp-server";
20727
+ var LOG_MAX_BYTES = 1024 * 1024;
20728
+ var DIR_NAME = ".datalab-mcp";
20729
+ var FILE_NAME = "connector.log";
20730
+ function logDir(home = homedir()) {
20731
+ return join(home, DIR_NAME);
20732
+ }
20733
+ function logPath(home = homedir()) {
20734
+ return join(logDir(home), FILE_NAME);
20735
+ }
20736
+ function rolledLogPath(home = homedir()) {
20737
+ return `${logPath(home)}.1`;
20738
+ }
20739
+ function rollIfLarge(home = homedir(), maxBytes = LOG_MAX_BYTES) {
20740
+ try {
20741
+ const size = statSync(logPath(home)).size;
20742
+ if (size < maxBytes) return false;
20743
+ renameSync(logPath(home), rolledLogPath(home));
20744
+ return true;
20745
+ } catch {
20746
+ return false;
20747
+ }
20748
+ }
20749
+ function openLogFd(home = homedir()) {
20750
+ try {
20751
+ mkdirSync(logDir(home), { recursive: true });
20752
+ rollIfLarge(home);
20753
+ return openSync(logPath(home), "a");
20754
+ } catch {
20755
+ return null;
20756
+ }
20757
+ }
20758
+ function currentAccount(env = process.env, username = userInfo().username) {
20759
+ const domain22 = env["USERDOMAIN"]?.trim();
20760
+ if (!domain22) return username;
20761
+ return `${domain22}\\${username}`;
20762
+ }
20763
+ function ownerOnlyArgs(path, account) {
20764
+ return [path, "/inheritance:r", "/grant:r", `${account}:F`];
20765
+ }
20766
+ function defaultRunIcacls(args) {
20767
+ const root = process.env["SystemRoot"] ?? "C:\\Windows";
20768
+ const result = spawnSync(join2(root, "System32", "icacls.exe"), [...args], {
20769
+ stdio: "ignore",
20770
+ windowsHide: true,
20771
+ timeout: 1e4
20772
+ });
20773
+ return result.status === 0;
20774
+ }
20775
+ function restrictToOwner(path, run = defaultRunIcacls, account = currentAccount()) {
20776
+ return run(ownerOnlyArgs(path, account));
20777
+ }
20778
+ var OWNER_ONLY = 384;
20779
+ function writeOwnerOnly(path, body, deps = {}) {
20780
+ mkdirSync2(dirname(path), { recursive: true });
20781
+ writeFileSync(path, body, { encoding: "utf8", mode: OWNER_ONLY });
20782
+ if ((deps.platform ?? process.platform) === "win32") {
20783
+ restrictToOwner(path, deps.runIcacls);
20784
+ return;
20785
+ }
20786
+ try {
20787
+ chmodSync(path, OWNER_ONLY);
20788
+ } catch {
20789
+ }
20790
+ }
20791
+ var FILE_NAME2 = "pairing.json";
20792
+ function pairingPath(home = homedir2()) {
20793
+ return join3(logDir(home), FILE_NAME2);
20794
+ }
20795
+ function readPairingRecord(home = homedir2()) {
20796
+ let raw;
20797
+ try {
20798
+ raw = readFileSync(pairingPath(home), "utf8");
20799
+ } catch {
20800
+ return null;
20801
+ }
20802
+ let parsed;
20803
+ try {
20804
+ parsed = JSON.parse(raw);
20805
+ } catch {
20806
+ return null;
20807
+ }
20808
+ if (typeof parsed !== "object" || parsed === null) return null;
20809
+ const { token, pairedAt } = parsed;
20810
+ if (typeof token !== "string" || token.length < MIN_TOKEN_LENGTH) return null;
20811
+ if (typeof pairedAt !== "string") return null;
20812
+ return { token, pairedAt };
20813
+ }
20814
+ function writePairingRecord(record22, home = homedir2()) {
20815
+ try {
20816
+ writeOwnerOnly(pairingPath(home), `${JSON.stringify(record22)}
20817
+ `);
20818
+ return true;
20819
+ } catch {
20820
+ return false;
20821
+ }
20822
+ }
20823
+ function deletePairingRecord(home = homedir2()) {
20824
+ const path = pairingPath(home);
20825
+ try {
20826
+ readFileSync(path);
20827
+ } catch {
20828
+ return false;
20829
+ }
20830
+ rmSync(path, { force: true });
20831
+ return true;
20832
+ }
20833
+ var CLAIM_WINDOW_MS = 10 * 60 * 1e3;
20834
+ function fixedRoot(token) {
20835
+ return {
20836
+ current: () => token,
20837
+ claim: () => "already_paired",
20838
+ windowEndsAt: () => null,
20839
+ acceptsClaim: () => false
20840
+ };
20841
+ }
20842
+ function pairingRoot(options = {}) {
20843
+ const now = options.now ?? Date.now;
20844
+ const windowMs = options.windowMs ?? CLAIM_WINDOW_MS;
20845
+ const startedAt = now();
20846
+ let token = readPairingRecord(options.home)?.token ?? null;
20847
+ return {
20848
+ current: () => token,
20849
+ windowEndsAt: () => token === null ? startedAt + windowMs : null,
20850
+ acceptsClaim: () => token === null && now() - startedAt <= windowMs,
20851
+ claim(presented) {
20852
+ if (token !== null) return "already_paired";
20853
+ if (now() - startedAt > windowMs) return "window_closed";
20854
+ if (presented.length < MIN_TOKEN_LENGTH) return "invalid_token";
20855
+ const pairedAt = new Date(now()).toISOString();
20856
+ if (!writePairingRecord({ token: presented, pairedAt }, options.home)) {
20857
+ options.log?.(
20858
+ "could not write the pairing record; paired for this run only"
20859
+ );
20860
+ }
20861
+ token = presented;
20862
+ return "claimed";
20863
+ }
20864
+ };
20865
+ }
20866
+ var FILE_NAME3 = "apps.json";
20867
+ function appsPath(home = homedir3()) {
20868
+ return join4(logDir(home), FILE_NAME3);
20869
+ }
20870
+ function readApprovedApps(home = homedir3()) {
20871
+ let parsed;
20872
+ try {
20873
+ parsed = JSON.parse(readFileSync2(appsPath(home), "utf8"));
20874
+ } catch {
20875
+ return [];
20876
+ }
20877
+ if (typeof parsed !== "object" || parsed === null) return [];
20878
+ const list = parsed.apps;
20879
+ if (!Array.isArray(list)) return [];
20880
+ const out = [];
20881
+ for (const item of list) {
20882
+ if (typeof item !== "object" || item === null) continue;
20883
+ const { name, approvedAt } = item;
20884
+ const clean = normalizeAppName(name);
20885
+ if (clean === null || typeof approvedAt !== "string") continue;
20886
+ out.push({ name: clean, approvedAt });
20887
+ }
20888
+ return out;
20889
+ }
20890
+ function writeApprovedApps(apps, home = homedir3()) {
20891
+ try {
20892
+ writeOwnerOnly(appsPath(home), `${JSON.stringify({ apps })}
20893
+ `);
20894
+ return true;
20895
+ } catch {
20896
+ return false;
20897
+ }
20898
+ }
20899
+ var PENDING_CAP = 16;
20900
+ function createAppBook(options = {}) {
20901
+ const now = options.now ?? Date.now;
20902
+ let approved = readApprovedApps(options.home);
20903
+ const pending = /* @__PURE__ */ new Map();
20904
+ const refused = /* @__PURE__ */ new Set();
20905
+ const save = () => {
20906
+ if (writeApprovedApps(approved, options.home)) return;
20907
+ options.log?.("could not write the approved apps; kept for this run only");
20908
+ };
20909
+ return {
20910
+ see(raw) {
20911
+ const name = normalizeAppName(raw);
20912
+ if (name === null) return "refused";
20913
+ if (approved.some((app) => app.name === name)) return "approved";
20914
+ if (refused.has(name)) return "refused";
20915
+ if (!pending.has(name) && pending.size < PENDING_CAP) {
20916
+ pending.set(name, now());
20917
+ }
20918
+ return pending.has(name) ? "pending" : "refused";
20919
+ },
20920
+ approved: () => approved.map((app) => ({ ...app })),
20921
+ pending: () => [...pending].map(([name, askedAt]) => ({ name, askedAt })),
20922
+ approve(raw) {
20923
+ const name = normalizeAppName(raw);
20924
+ if (name === null || !pending.delete(name)) return false;
20925
+ approved = [
20926
+ ...approved,
20927
+ { name, approvedAt: new Date(now()).toISOString() }
20928
+ ];
20929
+ save();
20930
+ return true;
20931
+ },
20932
+ refuse(raw) {
20933
+ const name = normalizeAppName(raw);
20934
+ if (name === null || !pending.delete(name)) return false;
20935
+ refused.add(name);
20936
+ return true;
20937
+ },
20938
+ revoke(raw) {
20939
+ const name = normalizeAppName(raw);
20940
+ if (name === null) return false;
20941
+ const next = approved.filter((app) => app.name !== name);
20942
+ if (next.length === approved.length) return false;
20943
+ approved = next;
20944
+ refused.delete(name);
20945
+ save();
20946
+ return true;
20947
+ }
20948
+ };
20949
+ }
20950
+ var REFUSAL_STATUS = {
20951
+ forbidden_origin: 403,
20952
+ unauthorized: 403,
20953
+ paired_elsewhere: 403,
20954
+ window_closed: 403,
20955
+ unknown_app: 404,
20956
+ bad_request: 400
20957
+ };
20958
+ function refuse(reason) {
20959
+ return {
20960
+ status: REFUSAL_STATUS[reason],
20961
+ answer: { ok: false, reason }
20962
+ };
20963
+ }
20964
+ function createPairingDesk(options) {
20965
+ const { root, apps, extensionIds } = options;
20966
+ const statusFor = (yours) => {
20967
+ const held = root.current();
20968
+ const paired = held !== null;
20969
+ const windowOpen = root.acceptsClaim();
20970
+ const visible = paired ? yours : true;
20971
+ return {
20972
+ paired,
20973
+ yours,
20974
+ windowOpen,
20975
+ windowEndsAt: root.windowEndsAt(),
20976
+ pending: visible ? apps.pending() : [],
20977
+ apps: paired && yours ? apps.approved() : []
20978
+ };
20979
+ };
20980
+ return {
20981
+ handle(raw, origin) {
20982
+ const parsed = PairingRequestSchema.safeParse(raw);
20983
+ if (!parsed.success) return refuse("bad_request");
20984
+ const { action, token, extensionId, app } = parsed.data;
20985
+ const identity = checkExtensionIdentity(
20986
+ origin,
20987
+ extensionId,
20988
+ extensionIds
20989
+ );
20990
+ if (!identity.ok) return refuse("forbidden_origin");
20991
+ const held = root.current();
20992
+ const yours = held !== null && checkToken(token, held).ok;
20993
+ if (action === "status") {
20994
+ return { status: 200, answer: { ok: true, status: statusFor(yours) } };
20995
+ }
20996
+ if (held !== null && !yours) return refuse("paired_elsewhere");
20997
+ if (held === null && token.length < MIN_TOKEN_LENGTH) {
20998
+ return refuse("unauthorized");
20999
+ }
21000
+ if (app === void 0) return refuse("bad_request");
21001
+ if (action === "revoke") {
21002
+ if (held === null) return refuse("unauthorized");
21003
+ if (!apps.revoke(app)) return refuse("unknown_app");
21004
+ options.log?.("an approved AI app was revoked");
21005
+ return { status: 200, answer: { ok: true, status: statusFor(true) } };
21006
+ }
21007
+ const name = normalizeAppName(app);
21008
+ if (!apps.pending().some((entry) => entry.name === name)) {
21009
+ return refuse("unknown_app");
21010
+ }
21011
+ if (action === "refuse") {
21012
+ apps.refuse(app);
21013
+ return {
21014
+ status: 200,
21015
+ answer: { ok: true, status: statusFor(held !== null) }
21016
+ };
21017
+ }
21018
+ if (held === null) {
21019
+ if (!root.acceptsClaim()) return refuse("window_closed");
21020
+ if (root.claim(token) !== "claimed") return refuse("unauthorized");
21021
+ options.log?.("paired with a side panel");
21022
+ }
21023
+ apps.approve(app);
21024
+ return { status: 200, answer: { ok: true, status: statusFor(true) } };
21025
+ }
21026
+ };
21027
+ }
20645
21028
  function randomPrefix() {
20646
21029
  return Math.floor(Math.random() * 16777215).toString(36).padStart(4, "0");
20647
21030
  }
@@ -20797,6 +21180,7 @@ function daemonIdTag() {
20797
21180
  }
20798
21181
  var Bridge = class {
20799
21182
  #deps;
21183
+ #root;
20800
21184
  #sessions = /* @__PURE__ */ new Map();
20801
21185
  /** browserId to the name it reported, for datalab_browsers. */
20802
21186
  #labels = /* @__PURE__ */ new Map();
@@ -20811,6 +21195,7 @@ var Bridge = class {
20811
21195
  #cachedTools = [];
20812
21196
  constructor(deps) {
20813
21197
  this.#deps = deps;
21198
+ this.#root = resolveRoot(deps);
20814
21199
  const limit = deps.rateLimit ?? DEFAULT_RATE_LIMIT;
20815
21200
  this.#bucketTokens = limit.capacity;
20816
21201
  this.#bucketRefilledAt = (deps.now ?? Date.now)();
@@ -20952,8 +21337,24 @@ var Bridge = class {
20952
21337
  * The root token only. A browser's own credential must never open this:
20953
21338
  * one browser could then end another's unattended run.
20954
21339
  */
21340
+ /**
21341
+ * The root token a handshake is checked against. An unpaired connector
21342
+ * pairs only with a handshake that every other check admits: identity,
21343
+ * protocol and capabilities before this call, a routable name here.
21344
+ */
21345
+ #rootFor(presented, browserId) {
21346
+ const held = this.#root.current();
21347
+ if (held !== null) return held;
21348
+ if (browserId === void 0 || browserId.length === 0) return null;
21349
+ if (this.#root.claim(presented) === "claimed") {
21350
+ this.#deps.log?.("paired with a side panel");
21351
+ }
21352
+ return this.#root.current();
21353
+ }
20955
21354
  verifyRootToken(presented) {
20956
- return checkToken(presented ?? void 0, this.#deps.token).ok;
21355
+ const root = this.#root.current();
21356
+ if (root === null) return false;
21357
+ return checkToken(presented ?? void 0, root).ok;
20957
21358
  }
20958
21359
  /**
20959
21360
  * May this credential add a browser to this machine?
@@ -21158,10 +21559,19 @@ var Bridge = class {
21158
21559
  message: "This browser panel is outdated. Close and reopen the side panel before reconnecting."
21159
21560
  };
21160
21561
  }
21562
+ const rootToken = this.#rootFor(parsed.data.token, parsed.data.browserId);
21563
+ if (rootToken === null) {
21564
+ return {
21565
+ t: "hello_nack",
21566
+ reason: "unauthorized",
21567
+ supported: [],
21568
+ message: "This connector is not paired. Restart your AI app, then connect from the side panel within 10 minutes."
21569
+ };
21570
+ }
21161
21571
  const tokenHash = digestToken(parsed.data.token);
21162
21572
  const credential = resolveCredential(
21163
21573
  { token: parsed.data.token, browserId: parsed.data.browserId },
21164
- { rootToken: this.#deps.token }
21574
+ { rootToken }
21165
21575
  );
21166
21576
  if (credential.kind !== "claimed") {
21167
21577
  this.#deps.log?.("refused an unauthorized browser credential");
@@ -21520,6 +21930,14 @@ var BridgeError = class extends Error {
21520
21930
  if (timing) this.timing = timing;
21521
21931
  }
21522
21932
  };
21933
+ function resolveRoot(deps) {
21934
+ if (deps.root !== void 0 && deps.token !== void 0) {
21935
+ throw new Error("Bridge takes a root credential or a token, not both.");
21936
+ }
21937
+ if (deps.root !== void 0) return deps.root;
21938
+ if (deps.token !== void 0) return fixedRoot(deps.token);
21939
+ throw new Error("Bridge needs a root credential or a token.");
21940
+ }
21523
21941
  var MIB = 1024 * 1024;
21524
21942
  var MAX_STAGE_BYTES = 500 * MIB;
21525
21943
  var STAGE_KIND_LIMITS = {
@@ -21590,7 +22008,7 @@ var MAX_RANGE_BYTES = MIB;
21590
22008
  var HANDLE = /^stage:([0-9a-f]{32})$/;
21591
22009
  var DEFAULT_TOKEN_TTL_MS = 30 * 60 * 1e3;
21592
22010
  var STAGE_CAPABILITY = "datalab-mcp-stage-v1";
21593
- function refuse(reason, retryable, message) {
22011
+ function refuse2(reason, retryable, message) {
21594
22012
  return { state: "REFUSED", reason, retryable, message };
21595
22013
  }
21596
22014
  function segment(...parts) {
@@ -21599,8 +22017,8 @@ function segment(...parts) {
21599
22017
  function createMediaStage(opts) {
21600
22018
  const now = opts.now ?? Date.now;
21601
22019
  const ttl = opts.tokenTtlMs ?? DEFAULT_TOKEN_TTL_MS;
21602
- const ledgerDir = join(opts.root, "ledger");
21603
- const blobDir = join(opts.root, "blob");
22020
+ const ledgerDir = join5(opts.root, "ledger");
22021
+ const blobDir = join5(opts.root, "blob");
21604
22022
  const tokens = /* @__PURE__ */ new Map();
21605
22023
  const active = /* @__PURE__ */ new Map();
21606
22024
  const received = /* @__PURE__ */ new Map();
@@ -21609,12 +22027,12 @@ function createMediaStage(opts) {
21609
22027
  (names) => Promise.all(
21610
22028
  names.filter(
21611
22029
  (name) => name.endsWith(".part") && !receiving.has(name.slice(0, -5))
21612
- ).map((name) => rm(join(blobDir, name), { force: true }))
22030
+ ).map((name) => rm(join5(blobDir, name), { force: true }))
21613
22031
  )
21614
22032
  ).catch(() => void 0);
21615
22033
  const keyOf = (j) => segment(j.blogId, j.runId, j.actionId, j.jobId);
21616
- const ledgerPath = (key) => join(ledgerDir, `${key}.json`);
21617
- const blobPath = (key) => join(blobDir, key);
22034
+ const ledgerPath = (key) => join5(ledgerDir, `${key}.json`);
22035
+ const blobPath = (key) => join5(blobDir, key);
21618
22036
  async function readRow(key) {
21619
22037
  try {
21620
22038
  const raw = await readFile(ledgerPath(key), "utf8");
@@ -21633,18 +22051,18 @@ function createMediaStage(opts) {
21633
22051
  const key = keyOf(req);
21634
22052
  const row = await readRow(key);
21635
22053
  if (row === "unreadable") {
21636
- return refuse("uploads_unproven", true, "\uC791\uC5C5 \uC0C1\uD0DC\uB97C \uC77D\uC9C0 \uBABB\uD588\uC5B4\uC694.");
22054
+ return refuse2("uploads_unproven", true, "\uC791\uC5C5 \uC0C1\uD0DC\uB97C \uC77D\uC9C0 \uBABB\uD588\uC5B4\uC694.");
21637
22055
  }
21638
22056
  if (row) {
21639
22057
  if (req.fence < row.fence) {
21640
- return refuse(
22058
+ return refuse2(
21641
22059
  "stale_fence",
21642
22060
  false,
21643
22061
  "\uB354 \uC0C8\uB85C\uC6B4 \uC2DC\uB3C4\uAC00 \uC774\uBBF8 \uC9C4\uD589\uB410\uC5B4\uC694."
21644
22062
  );
21645
22063
  }
21646
22064
  if (row.state === "SEALED") {
21647
- return refuse("already_sealed", false, "\uC774\uBBF8 \uBD09\uC778\uB41C \uC790\uC0B0\uC774\uC5D0\uC694.");
22065
+ return refuse2("already_sealed", false, "\uC774\uBBF8 \uBD09\uC778\uB41C \uC790\uC0B0\uC774\uC5D0\uC694.");
21648
22066
  }
21649
22067
  if (row.state === "OPEN") {
21650
22068
  for (const [token2, held] of tokens) {
@@ -21736,11 +22154,11 @@ function createMediaStage(opts) {
21736
22154
  const key = keyOf(req);
21737
22155
  const row = await readRow(key);
21738
22156
  if (row === "unreadable") {
21739
- return refuse("uploads_unproven", true, "\uC791\uC5C5 \uC0C1\uD0DC\uB97C \uC77D\uC9C0 \uBABB\uD588\uC5B4\uC694.");
22157
+ return refuse2("uploads_unproven", true, "\uC791\uC5C5 \uC0C1\uD0DC\uB97C \uC77D\uC9C0 \uBABB\uD588\uC5B4\uC694.");
21740
22158
  }
21741
- if (!row) return refuse("upload_expired", false, "\uC5F4\uB9B0 \uC790\uB9AC\uAC00 \uC5C6\uC5B4\uC694.");
22159
+ if (!row) return refuse2("upload_expired", false, "\uC5F4\uB9B0 \uC790\uB9AC\uAC00 \uC5C6\uC5B4\uC694.");
21742
22160
  if (req.fence < row.fence) {
21743
- return refuse(
22161
+ return refuse2(
21744
22162
  "stale_fence",
21745
22163
  false,
21746
22164
  "\uB354 \uC0C8\uB85C\uC6B4 \uC2DC\uB3C4\uAC00 \uC774\uBBF8 \uC9C4\uD589\uB410\uC5B4\uC694."
@@ -21757,17 +22175,17 @@ function createMediaStage(opts) {
21757
22175
  capabilityVersion: STAGE_CAPABILITY
21758
22176
  };
21759
22177
  }
21760
- return refuse("already_sealed", false, "\uC774\uBBF8 \uBD09\uC778\uB41C \uC790\uC0B0\uC774\uC5D0\uC694.");
22178
+ return refuse2("already_sealed", false, "\uC774\uBBF8 \uBD09\uC778\uB41C \uC790\uC0B0\uC774\uC5D0\uC694.");
21761
22179
  }
21762
22180
  let digest;
21763
22181
  try {
21764
22182
  digest = received.get(key) ?? await hashFile(blobPath(key));
21765
22183
  } catch {
21766
- return refuse("upload_expired", false, "\uBC1B\uC740 \uBC14\uC774\uD2B8\uAC00 \uC5C6\uC5B4\uC694.");
22184
+ return refuse2("upload_expired", false, "\uBC1B\uC740 \uBC14\uC774\uD2B8\uAC00 \uC5C6\uC5B4\uC694.");
21767
22185
  }
21768
22186
  const actual = digest.sha256;
21769
22187
  if (actual !== req.sha256 || digest.bytes !== req.bytes) {
21770
- return refuse(
22188
+ return refuse2(
21771
22189
  "hash_mismatch",
21772
22190
  false,
21773
22191
  "\uBC1B\uC740 \uBC14\uC774\uD2B8\uAC00 \uC54C\uB824\uC8FC\uC2E0 \uAC83\uACFC \uB2EC\uB77C\uC694."
@@ -21778,7 +22196,7 @@ function createMediaStage(opts) {
21778
22196
  received.delete(key);
21779
22197
  await rm(blobPath(key), { force: true });
21780
22198
  const cap = Math.round(STAGE_KIND_LIMITS[kind] / MIB);
21781
- return refuse(
22199
+ return refuse2(
21782
22200
  "too_large",
21783
22201
  false,
21784
22202
  `\uC774 \uC885\uB958\uC758 \uD30C\uC77C\uC740 ${cap}MB \uAE4C\uC9C0 \uC62C\uB9B4 \uC218 \uC788\uC5B4\uC694.`
@@ -21836,7 +22254,7 @@ function createMediaStage(opts) {
21836
22254
  };
21837
22255
  }
21838
22256
  if (row?.state === "SEALED") {
21839
- return refuse("already_sealed", false, "\uC774\uBBF8 \uBD09\uC778\uB41C \uC790\uC0B0\uC774\uC5D0\uC694.");
22257
+ return refuse2("already_sealed", false, "\uC774\uBBF8 \uBD09\uC778\uB41C \uC790\uC0B0\uC774\uC5D0\uC694.");
21840
22258
  }
21841
22259
  if ((active.get(key) ?? 0) > 0) {
21842
22260
  return {
@@ -21893,7 +22311,7 @@ function createMediaStage(opts) {
21893
22311
  for (const dir of [ledgerDir, blobDir]) {
21894
22312
  try {
21895
22313
  for (const name of await readdir(dir)) {
21896
- if (!name.endsWith(".part")) out.push(join(dir, name));
22314
+ if (!name.endsWith(".part")) out.push(join5(dir, name));
21897
22315
  }
21898
22316
  } catch {
21899
22317
  }
@@ -22218,6 +22636,141 @@ async function handleMcpRequest(bridge, body, accept, stage) {
22218
22636
  );
22219
22637
  }
22220
22638
  var MAX_MCP_BODY_BYTES = 256 * 1024;
22639
+ var MAX_BODY_BYTES = 64 * 1024;
22640
+ var MAX_RESULT_BODY_BYTES = 4 * 1024 * 1024;
22641
+ var MAX_ARTIFACT_BODY_BYTES = 2 * 1024 * 1024;
22642
+ function isFirstOrDecade(n) {
22643
+ if (n === 1) return true;
22644
+ let at = 10;
22645
+ while (at < n) at *= 10;
22646
+ return at === n;
22647
+ }
22648
+ function headerValue(raw) {
22649
+ const one = Array.isArray(raw) ? raw[0] : raw;
22650
+ const trimmed = one?.trim();
22651
+ return trimmed ? trimmed.slice(0, 128) : void 0;
22652
+ }
22653
+ function correlationValue(value, max) {
22654
+ return /^[a-zA-Z0-9_-]+$/.test(value) ? value.slice(0, max) : "redacted";
22655
+ }
22656
+ function writeSafely(res, status, headers, body) {
22657
+ if (res.writableEnded || res.destroyed) return;
22658
+ try {
22659
+ res.writeHead(status, headers);
22660
+ res.end(body);
22661
+ } catch {
22662
+ }
22663
+ }
22664
+ function json2(res, status, body) {
22665
+ writeSafely(
22666
+ res,
22667
+ status,
22668
+ { "content-type": "application/json" },
22669
+ JSON.stringify(body)
22670
+ );
22671
+ }
22672
+ function readJson(req, maxBytes) {
22673
+ return new Promise((resolve, reject) => {
22674
+ let size = 0;
22675
+ const chunks = [];
22676
+ req.on("data", (chunk) => {
22677
+ size += chunk.length;
22678
+ if (size > maxBytes) {
22679
+ reject(new Error("body too large"));
22680
+ req.destroy();
22681
+ return;
22682
+ }
22683
+ chunks.push(chunk);
22684
+ });
22685
+ req.on("end", () => {
22686
+ try {
22687
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
22688
+ } catch (err) {
22689
+ reject(err instanceof Error ? err : new Error(String(err)));
22690
+ }
22691
+ });
22692
+ req.on("error", reject);
22693
+ });
22694
+ }
22695
+ var CLIENT_WINDOW_MS = 6e4;
22696
+ var CLIENT_ID_CAP = 64;
22697
+ function createMcpObservation(log) {
22698
+ let withCredential = 0;
22699
+ let withoutCredential = 0;
22700
+ const seenClients = /* @__PURE__ */ new Map();
22701
+ let mostAtOnce = 0;
22702
+ const noteCredential = (present) => {
22703
+ const n = present ? withCredential += 1 : withoutCredential += 1;
22704
+ if (!isFirstOrDecade(n)) return;
22705
+ log?.(
22706
+ present ? `/mcp: ${n} call(s) carrying the pairing credential` : `/mcp: ${n} call(s) with no pairing credential`
22707
+ );
22708
+ };
22709
+ const noteClient = (id, now) => {
22710
+ if (!id) return;
22711
+ seenClients.set(id, now);
22712
+ for (const [at, last] of seenClients) {
22713
+ if (now - last > CLIENT_WINDOW_MS) seenClients.delete(at);
22714
+ }
22715
+ while (seenClients.size > CLIENT_ID_CAP) {
22716
+ const oldest = seenClients.keys().next().value;
22717
+ if (oldest === void 0) break;
22718
+ seenClients.delete(oldest);
22719
+ }
22720
+ if (seenClients.size <= mostAtOnce) return;
22721
+ mostAtOnce = seenClients.size;
22722
+ if (mostAtOnce < 2) return;
22723
+ log?.(
22724
+ `/mcp: ${mostAtOnce} adapters called within ${CLIENT_WINDOW_MS / 1e3}s \u2014 outside callers are not told apart`
22725
+ );
22726
+ };
22727
+ return { noteCredential, noteClient };
22728
+ }
22729
+ function handleArtifact(ctx, req, res) {
22730
+ const { opts } = ctx;
22731
+ const store = opts.artifactStore;
22732
+ if (!store) {
22733
+ json2(res, 404, { error: "not found" });
22734
+ return;
22735
+ }
22736
+ void readJson(req, MAX_ARTIFACT_BODY_BYTES).then(async (body) => {
22737
+ const b = body ?? {};
22738
+ const str = (k) => typeof b[k] === "string" ? b[k] : "";
22739
+ const tool = str("tool");
22740
+ const path = artifactPath(b["job"]);
22741
+ if (!str("sessionId") || !str("requestId") || !ARTIFACT_TOOLS.has(tool) || path === void 0) {
22742
+ json2(res, 403, { error: "unauthorized" });
22743
+ return;
22744
+ }
22745
+ const auth = opts.bridge.authorizeFileRequest({
22746
+ sessionId: str("sessionId"),
22747
+ requestId: str("requestId"),
22748
+ token: str("token"),
22749
+ path,
22750
+ tool
22751
+ });
22752
+ if (!auth.ok) {
22753
+ opts.log?.(`artifact refused: reason=${auth.reason}`);
22754
+ json2(res, 403, { error: "unauthorized" });
22755
+ return;
22756
+ }
22757
+ const offset = b["offset"];
22758
+ if (typeof offset !== "number" || !Number.isInteger(offset)) {
22759
+ json2(res, 400, { error: "bad_offset" });
22760
+ return;
22761
+ }
22762
+ const out = await store.write({
22763
+ key: `${str("sessionId")}:${str("requestId")}:${str("name")}`,
22764
+ name: str("name"),
22765
+ offset,
22766
+ data: str("data"),
22767
+ final: b["final"] === true,
22768
+ ...typeof b["bytes"] === "number" ? { bytes: b["bytes"] } : {},
22769
+ ...str("sha256") ? { sha256: str("sha256") } : {}
22770
+ });
22771
+ json2(res, out.ok ? 200 : 400, out);
22772
+ }).catch(() => json2(res, 400, { error: "bad request" }));
22773
+ }
22221
22774
  var MAX_FILE_BYTES = 10 * 1024 * 1024;
22222
22775
  function sniff(head) {
22223
22776
  const b = head;
@@ -22381,26 +22934,252 @@ async function openStagedImage(stage, handle) {
22381
22934
  fileName: `${handle.slice(6, 14)}.${contentType.slice(6)}`
22382
22935
  };
22383
22936
  }
22384
- var MCP_SERVER_HEALTH_SCHEMA = "datalab-extension-mcp-health-v1";
22385
- var MAX_BODY_BYTES = 64 * 1024;
22386
- var DEFAULT_TOOLS_CHANGED_DEBOUNCE_MS = 600;
22387
- var MAX_MCP_BODY_BYTES2 = 256 * 1024;
22388
- var MAX_RESULT_BODY_BYTES = 4 * 1024 * 1024;
22389
- var MAX_ARTIFACT_BODY_BYTES = 2 * 1024 * 1024;
22390
- function isFirstOrDecade(n) {
22391
- if (n === 1) return true;
22392
- let at = 10;
22393
- while (at < n) at *= 10;
22394
- return at === n;
22937
+ function handleBridgeFile(ctx, req, res) {
22938
+ const { opts, streams } = ctx;
22939
+ void readJson(req, MAX_BODY_BYTES).then(async (body) => {
22940
+ const b = body;
22941
+ const token = typeof b?.token === "string" ? b.token : "";
22942
+ const path = typeof b?.path === "string" ? b.path : "";
22943
+ const hasSessionId = b !== null && Object.hasOwn(b, "sessionId");
22944
+ const hasRequestId = b !== null && Object.hasOwn(b, "requestId");
22945
+ const invalidSessionId = hasSessionId && (typeof b?.sessionId !== "string" || b.sessionId.length === 0);
22946
+ const invalidRequestId = hasRequestId && (typeof b?.requestId !== "string" || b.requestId.length === 0);
22947
+ if (!hasSessionId || !hasRequestId || invalidSessionId || invalidRequestId || // An export-save permit names a job, never a file to read.
22948
+ typeof b?.tool === "string" && ARTIFACT_TOOLS.has(b.tool)) {
22949
+ json2(res, 403, {
22950
+ error: "unauthorized",
22951
+ message: "\uC0AC\uC9C4 \uC694\uCCAD\uC758 \uC5F0\uACB0 \uC815\uBCF4\uB97C \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694."
22952
+ });
22953
+ return;
22954
+ }
22955
+ const auth = opts.bridge.authorizeFileRequest({
22956
+ sessionId: b.sessionId,
22957
+ requestId: b.requestId,
22958
+ token,
22959
+ path,
22960
+ ...typeof b?.tool === "string" ? { tool: b.tool } : {}
22961
+ });
22962
+ if (!auth.ok) {
22963
+ opts.log?.(
22964
+ `file request refused: reason=${auth.reason} credential=${auth.credential} tokenPresent=${String(token.length > 0)} sessionMatch=${String(auth.key !== void 0)} open=not-entered`
22965
+ );
22966
+ json2(res, 403, {
22967
+ error: "unauthorized",
22968
+ message: "\uC0AC\uC9C4\uC744 \uAC00\uC838\uC62C \uC5F0\uACB0\uC744 \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694."
22969
+ });
22970
+ return;
22971
+ }
22972
+ const streamEntry = streams.get(auth.key);
22973
+ if (!streamEntry || streamEntry.sessionId !== auth.sessionId || !opts.bridge.isSessionStreamActive(auth.key, auth.sessionId) || !opts.bridge.consumeFileRequest(auth)) {
22974
+ opts.log?.(
22975
+ `file request refused: reason=file_session_not_live credential=${auth.credential} tokenPresent=true sessionMatch=false open=not-entered`
22976
+ );
22977
+ json2(res, 403, {
22978
+ error: "unauthorized",
22979
+ message: "\uC0AC\uC9C4\uC744 \uAC00\uC838\uC62C \uC5F0\uACB0\uC774 \uC5F4\uB824 \uC788\uC9C0 \uC54A\uC544\uC694."
22980
+ });
22981
+ return;
22982
+ }
22983
+ opts.log?.(
22984
+ `file request authorised: browser=${correlationValue(auth.key, 8)} session=${correlationValue(auth.sessionId, 32)} request=${correlationValue(auth.requestId, 96)} credential=${auth.credential} open=entered`
22985
+ );
22986
+ let source = null;
22987
+ let owner = null;
22988
+ let peerClosed = false;
22989
+ const stop = () => {
22990
+ peerClosed = true;
22991
+ source?.destroy();
22992
+ };
22993
+ req.once("aborted", stop);
22994
+ res.once("close", stop);
22995
+ try {
22996
+ const out = path.startsWith("stage:") ? await openStagedImage(opts.mediaStage, path) : await (opts.openLocalImage ?? openLocalImage)(path);
22997
+ if (!out.ok) {
22998
+ if (!peerClosed) {
22999
+ json2(res, 400, { error: out.reason, message: out.message });
23000
+ }
23001
+ return;
23002
+ }
23003
+ source = out.stream;
23004
+ if (peerClosed) {
23005
+ source.destroy();
23006
+ return;
23007
+ }
23008
+ const current = streams.get(auth.key);
23009
+ if (current !== streamEntry || current.sessionId !== auth.sessionId || !opts.bridge.isSessionStreamActive(auth.key, auth.sessionId)) {
23010
+ source.destroy(new Error("browser session ended"));
23011
+ json2(res, 403, {
23012
+ error: "unauthorized",
23013
+ message: "\uC0AC\uC9C4\uC744 \uAC00\uC838\uC62C \uC5F0\uACB0\uC774 \uC5F4\uB824 \uC788\uC9C0 \uC54A\uC544\uC694."
23014
+ });
23015
+ return;
23016
+ }
23017
+ res.writeHead(200, {
23018
+ "content-type": out.contentType,
23019
+ "content-length": String(out.byteLength),
23020
+ "x-file-name": encodeURIComponent(out.fileName),
23021
+ "cache-control": "no-store"
23022
+ });
23023
+ owner = current;
23024
+ owner.fileStreams.add(source);
23025
+ await pipeline2(source, res);
23026
+ } catch {
23027
+ if (!res.writableEnded) res.destroy();
23028
+ } finally {
23029
+ req.off("aborted", stop);
23030
+ res.off("close", stop);
23031
+ if (source) owner?.fileStreams.delete(source);
23032
+ }
23033
+ }).catch(() => json2(res, 400, { error: "bad request" }));
23034
+ }
23035
+ function handleFileCancel(ctx, req, res) {
23036
+ const { opts } = ctx;
23037
+ void readJson(req, MAX_BODY_BYTES).then((body) => {
23038
+ const b = body;
23039
+ if (typeof b?.token !== "string" || typeof b.sessionId !== "string" || typeof b.requestId !== "string") {
23040
+ json2(res, 403, { error: "unauthorized" });
23041
+ return;
23042
+ }
23043
+ const reason = opts.bridge.cancelFileRequest({
23044
+ token: b.token,
23045
+ sessionId: b.sessionId,
23046
+ requestId: b.requestId
23047
+ });
23048
+ json2(res, reason === null ? 200 : 403, {
23049
+ ...reason === null ? { ok: true } : { error: "unauthorized" }
23050
+ });
23051
+ }).catch(() => json2(res, 400, { error: "bad request" }));
23052
+ }
23053
+ var CODE_APP_NOT_APPROVED = -32001;
23054
+ var WAITING_TEXT = "This AI app is waiting for approval in the Datalab side panel. Approve it there, then call again.";
23055
+ var REFUSED_TEXT = "This AI app was refused in the Datalab side panel. Restart the connector to be asked again.";
23056
+ function gateMcpApp(apps, nameHeader, body, accept) {
23057
+ if (apps === void 0) return null;
23058
+ const name = normalizeAppName(nameHeader);
23059
+ if (name === null) return null;
23060
+ const standing = apps.see(name);
23061
+ if (standing === "approved") return null;
23062
+ const request = typeof body === "object" && body !== null ? body : {};
23063
+ if (request.method !== "tools/call") return null;
23064
+ return frameMcpResponse(
23065
+ {
23066
+ jsonrpc: "2.0",
23067
+ id: request.id ?? null,
23068
+ error: {
23069
+ code: CODE_APP_NOT_APPROVED,
23070
+ message: standing === "refused" ? REFUSED_TEXT : WAITING_TEXT
23071
+ }
23072
+ },
23073
+ accept
23074
+ );
22395
23075
  }
22396
- function headerValue(raw) {
22397
- const one = Array.isArray(raw) ? raw[0] : raw;
22398
- const trimmed = one?.trim();
22399
- return trimmed ? trimmed.slice(0, 128) : void 0;
23076
+ function handleMediaUpload(ctx, req, res) {
23077
+ const { opts } = ctx;
23078
+ const stage = opts.mediaStage;
23079
+ if (!stage) {
23080
+ json2(res, 404, { error: "not found" });
23081
+ return;
23082
+ }
23083
+ const auth = req.headers.authorization ?? "";
23084
+ const token = auth.startsWith("Bearer ") ? auth.slice(7).trim() : "";
23085
+ if (!token) {
23086
+ json2(res, 403, { error: "unauthorized" });
23087
+ return;
23088
+ }
23089
+ void stage.receiveUpload(token, req).then((out) => {
23090
+ if (out.ok) {
23091
+ json2(res, 202, { ok: true, bytes: out.bytes });
23092
+ return;
23093
+ }
23094
+ const status = out.reason === "upload_expired" ? 403 : 400;
23095
+ json2(res, status, { error: out.reason });
23096
+ }).catch((err) => {
23097
+ opts.log?.(
23098
+ `media upload failed: ${err instanceof Error ? err.message : String(err)}`
23099
+ );
23100
+ json2(res, 500, { error: "upload_failed" });
23101
+ });
22400
23102
  }
22401
- function correlationValue(value, max) {
22402
- return /^[a-zA-Z0-9_-]+$/.test(value) ? value.slice(0, max) : "redacted";
23103
+ function handlePairing(ctx, req, res) {
23104
+ const desk = ctx.opts.pairingDesk;
23105
+ if (!desk) {
23106
+ json2(res, 404, { error: "not found" });
23107
+ return;
23108
+ }
23109
+ const origin = req.headers.origin;
23110
+ void readJson(req, MAX_BODY_BYTES).then((body) => {
23111
+ const reply = desk.handle(body, origin);
23112
+ json2(res, reply.status, reply.answer);
23113
+ }).catch(() => json2(res, 400, { ok: false, reason: "bad_request" }));
23114
+ }
23115
+ function handleStageRange(ctx, req, res) {
23116
+ const { opts } = ctx;
23117
+ void readJson(req, MAX_BODY_BYTES).then(async (body) => {
23118
+ const b = body;
23119
+ const handle = typeof b?.handle === "string" ? b.handle : "";
23120
+ const offset = b?.offset;
23121
+ const length = b?.length;
23122
+ if (typeof b?.sessionId !== "string" || typeof offset !== "number" || typeof length !== "number" || !Number.isInteger(offset) || !Number.isInteger(length) || offset < 0 || length < 1) {
23123
+ json2(res, 400, {
23124
+ error: "bad_request",
23125
+ message: "\uC77D\uC744 \uBC94\uC704\uB97C \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694."
23126
+ });
23127
+ return;
23128
+ }
23129
+ const auth = opts.bridge.authorizeStageRead({
23130
+ sessionId: b.sessionId,
23131
+ token: typeof b.token === "string" ? b.token : "",
23132
+ handle
23133
+ });
23134
+ if (!auth.ok || !opts.mediaStage) {
23135
+ opts.log?.(
23136
+ `stage range refused: reason=${auth.ok ? "no_stage" : auth.reason}`
23137
+ );
23138
+ json2(res, 403, {
23139
+ error: "unauthorized",
23140
+ message: "\uC774 \uD30C\uC77C\uC744 \uC77D\uC744 \uAD8C\uD55C\uC774 \uC5C6\uC5B4\uC694."
23141
+ });
23142
+ return;
23143
+ }
23144
+ const info = await opts.mediaStage.sealedInfo(handle);
23145
+ if (!info) {
23146
+ json2(res, 404, {
23147
+ error: "not_found",
23148
+ message: "\uBD09\uC778\uB41C \uD30C\uC77C\uC744 \uCC3E\uC9C0 \uBABB\uD588\uC5B4\uC694."
23149
+ });
23150
+ return;
23151
+ }
23152
+ if (offset > info.bytes) {
23153
+ json2(res, 416, {
23154
+ error: "out_of_range",
23155
+ message: "\uD30C\uC77C \uB05D\uC744 \uB118\uC5B4 \uC77D\uC73C\uB824\uACE0 \uD588\uC5B4\uC694."
23156
+ });
23157
+ return;
23158
+ }
23159
+ const piece = await opts.mediaStage.readRange(handle, offset, length);
23160
+ res.writeHead(200, {
23161
+ "content-type": "application/octet-stream",
23162
+ "content-length": String(piece.byteLength),
23163
+ "x-total-bytes": String(info.bytes),
23164
+ "x-stage-kind": info.kind,
23165
+ "access-control-expose-headers": "x-total-bytes, x-stage-kind",
23166
+ "cache-control": "no-store"
23167
+ });
23168
+ res.end(piece);
23169
+ }).catch(() => {
23170
+ if (!res.headersSent) {
23171
+ json2(res, 400, {
23172
+ error: "bad_request",
23173
+ message: "\uC77D\uC744 \uBC94\uC704\uB97C \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694."
23174
+ });
23175
+ } else if (!res.writableEnded) {
23176
+ res.destroy();
23177
+ }
23178
+ });
22403
23179
  }
23180
+ var MCP_SERVER_HEALTH_SCHEMA = "datalab-extension-mcp-health-v1";
23181
+ var DEFAULT_TOOLS_CHANGED_DEBOUNCE_MS = 600;
23182
+ var MAX_MCP_BODY_BYTES2 = 256 * 1024;
22404
23183
  function createHttpBridge(opts) {
22405
23184
  const host = opts.host ?? "127.0.0.1";
22406
23185
  if (!isLoopbackHost(host)) {
@@ -22408,6 +23187,7 @@ function createHttpBridge(opts) {
22408
23187
  }
22409
23188
  const lifecycle = opts.lifecycle;
22410
23189
  const streams = /* @__PURE__ */ new Map();
23190
+ const ctx = { opts, streams };
22411
23191
  let toolsDropTimer = null;
22412
23192
  const debounceMs = opts.toolsChangedDebounceMs ?? DEFAULT_TOOLS_CHANGED_DEBOUNCE_MS;
22413
23193
  const toolSubscribers = /* @__PURE__ */ new Set();
@@ -22440,37 +23220,7 @@ function createHttpBridge(opts) {
22440
23220
  }, debounceMs);
22441
23221
  toolsDropTimer.unref?.();
22442
23222
  };
22443
- let withCredential = 0;
22444
- let withoutCredential = 0;
22445
- const noteMcpCredential = (present) => {
22446
- const n = present ? withCredential += 1 : withoutCredential += 1;
22447
- if (!isFirstOrDecade(n)) return;
22448
- opts.log?.(
22449
- present ? `/mcp: ${n} call(s) carrying the pairing credential` : `/mcp: ${n} call(s) with no pairing credential`
22450
- );
22451
- };
22452
- const CLIENT_WINDOW_MS = 6e4;
22453
- const CLIENT_ID_CAP = 64;
22454
- const seenClients = /* @__PURE__ */ new Map();
22455
- let mostAtOnce = 0;
22456
- const noteMcpClient = (id, now) => {
22457
- if (!id) return;
22458
- seenClients.set(id, now);
22459
- for (const [at, last] of seenClients) {
22460
- if (now - last > CLIENT_WINDOW_MS) seenClients.delete(at);
22461
- }
22462
- while (seenClients.size > CLIENT_ID_CAP) {
22463
- const oldest = seenClients.keys().next().value;
22464
- if (oldest === void 0) break;
22465
- seenClients.delete(oldest);
22466
- }
22467
- if (seenClients.size <= mostAtOnce) return;
22468
- mostAtOnce = seenClients.size;
22469
- if (mostAtOnce < 2) return;
22470
- opts.log?.(
22471
- `/mcp: ${mostAtOnce} adapters called within ${CLIENT_WINDOW_MS / 1e3}s \u2014 outside callers are not told apart`
22472
- );
22473
- };
23223
+ const mcpObservation = createMcpObservation(opts.log);
22474
23224
  const send = (frame, key) => {
22475
23225
  const stream = streams.get(key);
22476
23226
  if (!stream || stream.res.writableEnded) return false;
@@ -22522,13 +23272,20 @@ function createHttpBridge(opts) {
22522
23272
  const origin = req.headers.origin;
22523
23273
  if (req.method === "POST" && url22.pathname === "/mcp") {
22524
23274
  lifecycle?.bump?.();
22525
- noteMcpCredential(bearerToken(req.headers.authorization) !== null);
22526
- noteMcpClient(
23275
+ mcpObservation.noteCredential(
23276
+ bearerToken(req.headers.authorization) !== null
23277
+ );
23278
+ mcpObservation.noteClient(
22527
23279
  headerValue(req.headers["x-datalab-mcp-client"]),
22528
23280
  Date.now()
22529
23281
  );
22530
23282
  void readJson(req, MAX_MCP_BODY_BYTES2).then(
22531
- (body) => handleMcpRequest(
23283
+ (body) => gateMcpApp(
23284
+ opts.apps,
23285
+ headerValue(req.headers[MCP_APP_HEADER]),
23286
+ body,
23287
+ req.headers.accept
23288
+ ) ?? handleMcpRequest(
22532
23289
  opts.bridge,
22533
23290
  body,
22534
23291
  req.headers.accept,
@@ -22645,230 +23402,24 @@ function createHttpBridge(opts) {
22645
23402
  }).catch(() => json2(res, 400, { error: "bad request" }));
22646
23403
  return;
22647
23404
  }
23405
+ if (req.method === "POST" && url22.pathname === PAIRING_ROUTE) {
23406
+ handlePairing(ctx, req, res);
23407
+ return;
23408
+ }
22648
23409
  if (req.method === "POST" && url22.pathname === "/bridge/file") {
22649
- void readJson(req, MAX_BODY_BYTES).then(async (body) => {
22650
- const b = body;
22651
- const token = typeof b?.token === "string" ? b.token : "";
22652
- const path = typeof b?.path === "string" ? b.path : "";
22653
- const hasSessionId = b !== null && Object.hasOwn(b, "sessionId");
22654
- const hasRequestId = b !== null && Object.hasOwn(b, "requestId");
22655
- const invalidSessionId = hasSessionId && (typeof b?.sessionId !== "string" || b.sessionId.length === 0);
22656
- const invalidRequestId = hasRequestId && (typeof b?.requestId !== "string" || b.requestId.length === 0);
22657
- if (!hasSessionId || !hasRequestId || invalidSessionId || invalidRequestId || // An export-save permit names a job, never a file to read.
22658
- typeof b?.tool === "string" && ARTIFACT_TOOLS.has(b.tool)) {
22659
- json2(res, 403, {
22660
- error: "unauthorized",
22661
- message: "\uC0AC\uC9C4 \uC694\uCCAD\uC758 \uC5F0\uACB0 \uC815\uBCF4\uB97C \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694."
22662
- });
22663
- return;
22664
- }
22665
- const auth = opts.bridge.authorizeFileRequest({
22666
- sessionId: b.sessionId,
22667
- requestId: b.requestId,
22668
- token,
22669
- path,
22670
- ...typeof b?.tool === "string" ? { tool: b.tool } : {}
22671
- });
22672
- if (!auth.ok) {
22673
- opts.log?.(
22674
- `file request refused: reason=${auth.reason} credential=${auth.credential} tokenPresent=${String(token.length > 0)} sessionMatch=${String(auth.key !== void 0)} open=not-entered`
22675
- );
22676
- json2(res, 403, {
22677
- error: "unauthorized",
22678
- message: "\uC0AC\uC9C4\uC744 \uAC00\uC838\uC62C \uC5F0\uACB0\uC744 \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694."
22679
- });
22680
- return;
22681
- }
22682
- const streamEntry = streams.get(auth.key);
22683
- if (!streamEntry || streamEntry.sessionId !== auth.sessionId || !opts.bridge.isSessionStreamActive(auth.key, auth.sessionId) || !opts.bridge.consumeFileRequest(auth)) {
22684
- opts.log?.(
22685
- `file request refused: reason=file_session_not_live credential=${auth.credential} tokenPresent=true sessionMatch=false open=not-entered`
22686
- );
22687
- json2(res, 403, {
22688
- error: "unauthorized",
22689
- message: "\uC0AC\uC9C4\uC744 \uAC00\uC838\uC62C \uC5F0\uACB0\uC774 \uC5F4\uB824 \uC788\uC9C0 \uC54A\uC544\uC694."
22690
- });
22691
- return;
22692
- }
22693
- opts.log?.(
22694
- `file request authorised: browser=${correlationValue(auth.key, 8)} session=${correlationValue(auth.sessionId, 32)} request=${correlationValue(auth.requestId, 96)} credential=${auth.credential} open=entered`
22695
- );
22696
- let source = null;
22697
- let owner = null;
22698
- let peerClosed = false;
22699
- const stop = () => {
22700
- peerClosed = true;
22701
- source?.destroy();
22702
- };
22703
- req.once("aborted", stop);
22704
- res.once("close", stop);
22705
- try {
22706
- const out = path.startsWith("stage:") ? await openStagedImage(opts.mediaStage, path) : await (opts.openLocalImage ?? openLocalImage)(path);
22707
- if (!out.ok) {
22708
- if (!peerClosed) {
22709
- json2(res, 400, { error: out.reason, message: out.message });
22710
- }
22711
- return;
22712
- }
22713
- source = out.stream;
22714
- if (peerClosed) {
22715
- source.destroy();
22716
- return;
22717
- }
22718
- const current = streams.get(auth.key);
22719
- if (current !== streamEntry || current.sessionId !== auth.sessionId || !opts.bridge.isSessionStreamActive(auth.key, auth.sessionId)) {
22720
- source.destroy(new Error("browser session ended"));
22721
- json2(res, 403, {
22722
- error: "unauthorized",
22723
- message: "\uC0AC\uC9C4\uC744 \uAC00\uC838\uC62C \uC5F0\uACB0\uC774 \uC5F4\uB824 \uC788\uC9C0 \uC54A\uC544\uC694."
22724
- });
22725
- return;
22726
- }
22727
- res.writeHead(200, {
22728
- "content-type": out.contentType,
22729
- "content-length": String(out.byteLength),
22730
- "x-file-name": encodeURIComponent(out.fileName),
22731
- "cache-control": "no-store"
22732
- });
22733
- owner = current;
22734
- owner.fileStreams.add(source);
22735
- await pipeline2(source, res);
22736
- } catch {
22737
- if (!res.writableEnded) res.destroy();
22738
- } finally {
22739
- req.off("aborted", stop);
22740
- res.off("close", stop);
22741
- if (source) owner?.fileStreams.delete(source);
22742
- }
22743
- }).catch(() => json2(res, 400, { error: "bad request" }));
23410
+ handleBridgeFile(ctx, req, res);
22744
23411
  return;
22745
23412
  }
22746
23413
  if (req.method === "POST" && url22.pathname === "/bridge/stage-range") {
22747
- void readJson(req, MAX_BODY_BYTES).then(async (body) => {
22748
- const b = body;
22749
- const handle = typeof b?.handle === "string" ? b.handle : "";
22750
- const offset = b?.offset;
22751
- const length = b?.length;
22752
- if (typeof b?.sessionId !== "string" || typeof offset !== "number" || typeof length !== "number" || !Number.isInteger(offset) || !Number.isInteger(length) || offset < 0 || length < 1) {
22753
- json2(res, 400, {
22754
- error: "bad_request",
22755
- message: "\uC77D\uC744 \uBC94\uC704\uB97C \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694."
22756
- });
22757
- return;
22758
- }
22759
- const auth = opts.bridge.authorizeStageRead({
22760
- sessionId: b.sessionId,
22761
- token: typeof b.token === "string" ? b.token : "",
22762
- handle
22763
- });
22764
- if (!auth.ok || !opts.mediaStage) {
22765
- opts.log?.(
22766
- `stage range refused: reason=${auth.ok ? "no_stage" : auth.reason}`
22767
- );
22768
- json2(res, 403, {
22769
- error: "unauthorized",
22770
- message: "\uC774 \uD30C\uC77C\uC744 \uC77D\uC744 \uAD8C\uD55C\uC774 \uC5C6\uC5B4\uC694."
22771
- });
22772
- return;
22773
- }
22774
- const info = await opts.mediaStage.sealedInfo(handle);
22775
- if (!info) {
22776
- json2(res, 404, {
22777
- error: "not_found",
22778
- message: "\uBD09\uC778\uB41C \uD30C\uC77C\uC744 \uCC3E\uC9C0 \uBABB\uD588\uC5B4\uC694."
22779
- });
22780
- return;
22781
- }
22782
- if (offset > info.bytes) {
22783
- json2(res, 416, {
22784
- error: "out_of_range",
22785
- message: "\uD30C\uC77C \uB05D\uC744 \uB118\uC5B4 \uC77D\uC73C\uB824\uACE0 \uD588\uC5B4\uC694."
22786
- });
22787
- return;
22788
- }
22789
- const piece = await opts.mediaStage.readRange(handle, offset, length);
22790
- res.writeHead(200, {
22791
- "content-type": "application/octet-stream",
22792
- "content-length": String(piece.byteLength),
22793
- "x-total-bytes": String(info.bytes),
22794
- "x-stage-kind": info.kind,
22795
- "access-control-expose-headers": "x-total-bytes, x-stage-kind",
22796
- "cache-control": "no-store"
22797
- });
22798
- res.end(piece);
22799
- }).catch(() => {
22800
- if (!res.headersSent) {
22801
- json2(res, 400, {
22802
- error: "bad_request",
22803
- message: "\uC77D\uC744 \uBC94\uC704\uB97C \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694."
22804
- });
22805
- } else if (!res.writableEnded) {
22806
- res.destroy();
22807
- }
22808
- });
23414
+ handleStageRange(ctx, req, res);
22809
23415
  return;
22810
23416
  }
22811
23417
  if (req.method === "POST" && url22.pathname === "/bridge/artifact") {
22812
- const store = opts.artifactStore;
22813
- if (!store) {
22814
- json2(res, 404, { error: "not found" });
22815
- return;
22816
- }
22817
- void readJson(req, MAX_ARTIFACT_BODY_BYTES).then(async (body) => {
22818
- const b = body ?? {};
22819
- const str = (k) => typeof b[k] === "string" ? b[k] : "";
22820
- const tool = str("tool");
22821
- const path = artifactPath(b["job"]);
22822
- if (!str("sessionId") || !str("requestId") || !ARTIFACT_TOOLS.has(tool) || path === void 0) {
22823
- json2(res, 403, { error: "unauthorized" });
22824
- return;
22825
- }
22826
- const auth = opts.bridge.authorizeFileRequest({
22827
- sessionId: str("sessionId"),
22828
- requestId: str("requestId"),
22829
- token: str("token"),
22830
- path,
22831
- tool
22832
- });
22833
- if (!auth.ok) {
22834
- opts.log?.(`artifact refused: reason=${auth.reason}`);
22835
- json2(res, 403, { error: "unauthorized" });
22836
- return;
22837
- }
22838
- const offset = b["offset"];
22839
- if (typeof offset !== "number" || !Number.isInteger(offset)) {
22840
- json2(res, 400, { error: "bad_offset" });
22841
- return;
22842
- }
22843
- const out = await store.write({
22844
- key: `${str("sessionId")}:${str("requestId")}:${str("name")}`,
22845
- name: str("name"),
22846
- offset,
22847
- data: str("data"),
22848
- final: b["final"] === true,
22849
- ...typeof b["bytes"] === "number" ? { bytes: b["bytes"] } : {},
22850
- ...str("sha256") ? { sha256: str("sha256") } : {}
22851
- });
22852
- json2(res, out.ok ? 200 : 400, out);
22853
- }).catch(() => json2(res, 400, { error: "bad request" }));
23418
+ handleArtifact(ctx, req, res);
22854
23419
  return;
22855
23420
  }
22856
23421
  if (req.method === "POST" && url22.pathname === "/bridge/file/cancel") {
22857
- void readJson(req, MAX_BODY_BYTES).then((body) => {
22858
- const b = body;
22859
- if (typeof b?.token !== "string" || typeof b.sessionId !== "string" || typeof b.requestId !== "string") {
22860
- json2(res, 403, { error: "unauthorized" });
22861
- return;
22862
- }
22863
- const reason = opts.bridge.cancelFileRequest({
22864
- token: b.token,
22865
- sessionId: b.sessionId,
22866
- requestId: b.requestId
22867
- });
22868
- json2(res, reason === null ? 200 : 403, {
22869
- ...reason === null ? { ok: true } : { error: "unauthorized" }
22870
- });
22871
- }).catch(() => json2(res, 400, { error: "bad request" }));
23422
+ handleFileCancel(ctx, req, res);
22872
23423
  return;
22873
23424
  }
22874
23425
  if (req.method === "GET" && url22.pathname === "/mcp/notifications") {
@@ -22897,30 +23448,7 @@ function createHttpBridge(opts) {
22897
23448
  return;
22898
23449
  }
22899
23450
  if (req.method === "POST" && url22.pathname === "/media/upload") {
22900
- const stage = opts.mediaStage;
22901
- if (!stage) {
22902
- json2(res, 404, { error: "not found" });
22903
- return;
22904
- }
22905
- const auth = req.headers.authorization ?? "";
22906
- const token = auth.startsWith("Bearer ") ? auth.slice(7).trim() : "";
22907
- if (!token) {
22908
- json2(res, 403, { error: "unauthorized" });
22909
- return;
22910
- }
22911
- void stage.receiveUpload(token, req).then((out) => {
22912
- if (out.ok) {
22913
- json2(res, 202, { ok: true, bytes: out.bytes });
22914
- return;
22915
- }
22916
- const status = out.reason === "upload_expired" ? 403 : 400;
22917
- json2(res, status, { error: out.reason });
22918
- }).catch((err) => {
22919
- opts.log?.(
22920
- `media upload failed: ${err instanceof Error ? err.message : String(err)}`
22921
- );
22922
- json2(res, 500, { error: "upload_failed" });
22923
- });
23451
+ handleMediaUpload(ctx, req, res);
22924
23452
  return;
22925
23453
  }
22926
23454
  if (req.method === "POST" && url22.pathname === "/bridge/result") {
@@ -22966,68 +23494,17 @@ function createHttpBridge(opts) {
22966
23494
  })
22967
23495
  };
22968
23496
  }
22969
- function writeSafely(res, status, headers, body) {
22970
- if (res.writableEnded || res.destroyed) return;
22971
- try {
22972
- res.writeHead(status, headers);
22973
- res.end(body);
22974
- } catch {
22975
- }
22976
- }
22977
- function json2(res, status, body) {
22978
- writeSafely(
22979
- res,
22980
- status,
22981
- { "content-type": "application/json" },
22982
- JSON.stringify(body)
22983
- );
22984
- }
22985
- function readJson(req, maxBytes) {
22986
- return new Promise((resolve, reject) => {
22987
- let size = 0;
22988
- const chunks = [];
22989
- req.on("data", (chunk) => {
22990
- size += chunk.length;
22991
- if (size > maxBytes) {
22992
- reject(new Error("body too large"));
22993
- req.destroy();
22994
- return;
22995
- }
22996
- chunks.push(chunk);
22997
- });
22998
- req.on("end", () => {
22999
- try {
23000
- resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
23001
- } catch (err) {
23002
- reject(err instanceof Error ? err : new Error(String(err)));
23003
- }
23004
- });
23005
- req.on("error", reject);
23006
- });
23007
- }
23008
23497
  var DEFAULT_PORT = 8765;
23009
23498
  var DEFAULT_HOST = "127.0.0.1";
23010
23499
  function resolveConfig(env) {
23011
- const token = env.DATALAB_MCP_TOKEN?.trim();
23012
- if (!token) {
23013
- return {
23014
- ok: false,
23015
- message: "DATALAB_MCP_TOKEN is not set. Copy the pairing token from the extension's side panel."
23016
- };
23017
- }
23018
- if (token.length < MIN_TOKEN_LENGTH) {
23500
+ const token = env.DATALAB_MCP_TOKEN?.trim() || null;
23501
+ if (token !== null && token.length < MIN_TOKEN_LENGTH) {
23019
23502
  return {
23020
23503
  ok: false,
23021
23504
  message: `DATALAB_MCP_TOKEN must be at least ${MIN_TOKEN_LENGTH} characters; got ${token.length}.`
23022
23505
  };
23023
23506
  }
23024
- const extensionId = env.DATALAB_MCP_EXTENSION_ID?.trim();
23025
- if (!extensionId) {
23026
- return {
23027
- ok: false,
23028
- message: "DATALAB_MCP_EXTENSION_ID is not set. Copy the extension id from the side panel."
23029
- };
23030
- }
23507
+ const extensionId = env.DATALAB_MCP_EXTENSION_ID?.trim() || PUBLISHED_EXTENSION_ID;
23031
23508
  const host = env.DATALAB_MCP_HOST?.trim() || DEFAULT_HOST;
23032
23509
  if (!isLoopbackHost(host)) {
23033
23510
  return {
@@ -23053,37 +23530,6 @@ function parsePort(raw) {
23053
23530
  if (!Number.isInteger(n) || n < 1 || n > 65535) return null;
23054
23531
  return n;
23055
23532
  }
23056
- var LOG_MAX_BYTES = 1024 * 1024;
23057
- var DIR_NAME = ".datalab-mcp";
23058
- var FILE_NAME = "connector.log";
23059
- function logDir(home = homedir()) {
23060
- return join2(home, DIR_NAME);
23061
- }
23062
- function logPath(home = homedir()) {
23063
- return join2(logDir(home), FILE_NAME);
23064
- }
23065
- function rolledLogPath(home = homedir()) {
23066
- return `${logPath(home)}.1`;
23067
- }
23068
- function rollIfLarge(home = homedir(), maxBytes = LOG_MAX_BYTES) {
23069
- try {
23070
- const size = statSync(logPath(home)).size;
23071
- if (size < maxBytes) return false;
23072
- renameSync(logPath(home), rolledLogPath(home));
23073
- return true;
23074
- } catch {
23075
- return false;
23076
- }
23077
- }
23078
- function openLogFd(home = homedir()) {
23079
- try {
23080
- mkdirSync(logDir(home), { recursive: true });
23081
- rollIfLarge(home);
23082
- return openSync(logPath(home), "a");
23083
- } catch {
23084
- return null;
23085
- }
23086
- }
23087
23533
  function tryConnect(host, port, timeoutMs, deps = {}) {
23088
23534
  const connect = deps.createConnection ?? createConnection;
23089
23535
  return new Promise((resolve) => {
@@ -23198,30 +23644,23 @@ var Lifecycle = class {
23198
23644
  }
23199
23645
  }
23200
23646
  };
23201
- var FILE_NAME2 = "takeover";
23202
- var OWNER_ONLY = 384;
23203
- function takeoverPath(home = homedir2()) {
23204
- return join3(logDir(home), FILE_NAME2);
23647
+ var FILE_NAME4 = "takeover";
23648
+ function takeoverPath(home = homedir4()) {
23649
+ return join6(logDir(home), FILE_NAME4);
23205
23650
  }
23206
- function writeTakeoverSecret(home = homedir2()) {
23651
+ function writeTakeoverSecret(home = homedir4()) {
23207
23652
  try {
23208
- mkdirSync2(logDir(home), { recursive: true });
23209
23653
  const secret = randomBytes(32).toString("hex");
23210
- const path = takeoverPath(home);
23211
- writeFileSync(path, `${secret}
23212
- `, { encoding: "utf8", mode: OWNER_ONLY });
23213
- try {
23214
- chmodSync(path, OWNER_ONLY);
23215
- } catch {
23216
- }
23654
+ writeOwnerOnly(takeoverPath(home), `${secret}
23655
+ `);
23217
23656
  return secret;
23218
23657
  } catch {
23219
23658
  return null;
23220
23659
  }
23221
23660
  }
23222
- function readTakeoverSecret(home = homedir2()) {
23661
+ function readTakeoverSecret(home = homedir4()) {
23223
23662
  try {
23224
- const raw = readFileSync(takeoverPath(home), "utf8").trim();
23663
+ const raw = readFileSync3(takeoverPath(home), "utf8").trim();
23225
23664
  return raw === "" ? null : raw;
23226
23665
  } catch {
23227
23666
  return null;
@@ -23238,7 +23677,7 @@ function safeArtifactName(name) {
23238
23677
  function day(now) {
23239
23678
  return new Date(now).toISOString().slice(0, 10).replace(/-/g, "");
23240
23679
  }
23241
- function refuse2(reason, message) {
23680
+ function refuse3(reason, message) {
23242
23681
  return { ok: false, reason, message };
23243
23682
  }
23244
23683
  function createArtifactStore(opts) {
@@ -23257,16 +23696,16 @@ function createArtifactStore(opts) {
23257
23696
  async function write(chunk) {
23258
23697
  await expire();
23259
23698
  if (!BASE642.test(chunk.data)) {
23260
- return refuse2("bad_chunk", "\uB0B4\uBCF4\uB0B8 \uD30C\uC77C \uC870\uAC01\uC744 \uC77D\uC9C0 \uBABB\uD588\uC5B4\uC694.");
23699
+ return refuse3("bad_chunk", "\uB0B4\uBCF4\uB0B8 \uD30C\uC77C \uC870\uAC01\uC744 \uC77D\uC9C0 \uBABB\uD588\uC5B4\uC694.");
23261
23700
  }
23262
23701
  let entry = open42.get(chunk.key);
23263
23702
  if (!entry) {
23264
23703
  if (chunk.offset !== 0) {
23265
- return refuse2("bad_offset", "\uB0B4\uBCF4\uB0B8 \uD30C\uC77C\uC744 \uCC98\uC74C\uBD80\uD130 \uB2E4\uC2DC \uBCF4\uB0B4 \uC8FC\uC138\uC694.");
23704
+ return refuse3("bad_offset", "\uB0B4\uBCF4\uB0B8 \uD30C\uC77C\uC744 \uCC98\uC74C\uBD80\uD130 \uB2E4\uC2DC \uBCF4\uB0B4 \uC8FC\uC138\uC694.");
23266
23705
  }
23267
- const dir = join4(opts.root, day(now()));
23706
+ const dir = join7(opts.root, day(now()));
23268
23707
  await mkdir2(dir, { recursive: true });
23269
- const finalPath = join4(
23708
+ const finalPath = join7(
23270
23709
  dir,
23271
23710
  `${randomUUID2().slice(0, 8)}-${safeArtifactName(chunk.name)}`
23272
23711
  );
@@ -23281,12 +23720,12 @@ function createArtifactStore(opts) {
23281
23720
  }
23282
23721
  if (chunk.offset !== entry.received) {
23283
23722
  await drop(chunk.key, entry);
23284
- return refuse2("bad_offset", "\uB0B4\uBCF4\uB0B8 \uD30C\uC77C \uC870\uAC01\uC758 \uC21C\uC11C\uAC00 \uB9DE\uC9C0 \uC54A\uC544\uC694.");
23723
+ return refuse3("bad_offset", "\uB0B4\uBCF4\uB0B8 \uD30C\uC77C \uC870\uAC01\uC758 \uC21C\uC11C\uAC00 \uB9DE\uC9C0 \uC54A\uC544\uC694.");
23285
23724
  }
23286
23725
  const bytes = Buffer.from(chunk.data, "base64");
23287
23726
  if (entry.received + bytes.length > MAX_ARTIFACT_BYTES) {
23288
23727
  await drop(chunk.key, entry);
23289
- return refuse2("too_large", "\uB0B4\uBCF4\uB0B8 \uD30C\uC77C\uC774 \uB108\uBB34 \uCEE4\uC694(\uCD5C\uB300 1GB).");
23728
+ return refuse3("too_large", "\uB0B4\uBCF4\uB0B8 \uD30C\uC77C\uC774 \uB108\uBB34 \uCEE4\uC694(\uCD5C\uB300 1GB).");
23290
23729
  }
23291
23730
  await appendFile(entry.partPath, bytes);
23292
23731
  entry.hash.update(bytes);
@@ -23297,7 +23736,7 @@ function createArtifactStore(opts) {
23297
23736
  const sha256 = entry.hash.digest("hex");
23298
23737
  if (chunk.bytes !== void 0 && chunk.bytes !== entry.received || chunk.sha256 !== void 0 && chunk.sha256 !== sha256) {
23299
23738
  await drop(chunk.key, entry);
23300
- return refuse2(
23739
+ return refuse3(
23301
23740
  "mismatch",
23302
23741
  "\uBC1B\uC740 \uD30C\uC77C\uC774 \uB0B4\uBCF4\uB0B8 \uD30C\uC77C\uACFC \uB2EC\uB77C\uC694. \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694."
23303
23742
  );
@@ -23340,18 +23779,21 @@ function runDaemon(env, deps = {}) {
23340
23779
  void http.close().finally(() => exit(0));
23341
23780
  }
23342
23781
  });
23782
+ const root = token === null ? pairingRoot({ home: deps.home, log }) : fixedRoot(token);
23783
+ const apps = token === null ? createAppBook({ home: deps.home, log }) : null;
23784
+ const pairingDesk = apps === null ? void 0 : createPairingDesk({ root, apps, extensionIds, log });
23343
23785
  const bridge = new Bridge({
23344
23786
  send: (frame, key) => http.send(frame, key),
23345
- token,
23787
+ root,
23346
23788
  extensionIds,
23347
23789
  serverVersion: version22,
23348
23790
  rateLimit: deps.rateLimit,
23349
23791
  log
23350
23792
  });
23351
23793
  const stateDir = logDir(deps.home);
23352
- const mediaStage = createMediaStage({ root: join5(stateDir, "media") });
23794
+ const mediaStage = createMediaStage({ root: join8(stateDir, "media") });
23353
23795
  const artifactStore = createArtifactStore({
23354
- root: join5(stateDir, "exports")
23796
+ root: join8(stateDir, "exports")
23355
23797
  });
23356
23798
  const http = createHttpBridge({
23357
23799
  bridge,
@@ -23359,6 +23801,8 @@ function runDaemon(env, deps = {}) {
23359
23801
  host,
23360
23802
  mediaStage,
23361
23803
  artifactStore,
23804
+ pairingDesk,
23805
+ apps: apps ?? void 0,
23362
23806
  heartbeatMs: deps.heartbeatMs,
23363
23807
  identity: { name: NAME, version: version22 },
23364
23808
  log,
@@ -23414,7 +23858,7 @@ function runDaemon(env, deps = {}) {
23414
23858
  }
23415
23859
 
23416
23860
  // ../mcp-server/dist/index.js
23417
- import { spawnSync } from "child_process";
23861
+ import { spawnSync as spawnSync2 } from "child_process";
23418
23862
  function parseNetstatListeners(output3, port) {
23419
23863
  const pids = /* @__PURE__ */ new Set();
23420
23864
  for (const line of output3.split(/\r?\n/)) {
@@ -23448,7 +23892,7 @@ function listenerPids(platform, port, run, selfPid) {
23448
23892
  return pids.filter((pid) => pid !== selfPid);
23449
23893
  }
23450
23894
  function runQuiet(command, args) {
23451
- const res = spawnSync(command, args, {
23895
+ const res = spawnSync2(command, args, {
23452
23896
  encoding: "utf8",
23453
23897
  windowsHide: true,
23454
23898
  timeout: 1e4
@@ -43360,6 +43804,59 @@ var FrameEnvelopeSchema2 = external_exports2.object({ t: external_exports2.strin
43360
43804
  var REQUEST_DEADLINE_MS2 = 9e4;
43361
43805
  var EXEC_RESERVE_MS2 = 3e4;
43362
43806
  var CONFIRM_TIMEOUT_MS2 = REQUEST_DEADLINE_MS2 - EXEC_RESERVE_MS2;
43807
+ var APP_NAME_MAX2 = 64;
43808
+ var PairingActionSchema2 = external_exports2.enum([
43809
+ "status",
43810
+ "approve",
43811
+ "refuse",
43812
+ "revoke"
43813
+ ]);
43814
+ var PairingRequestSchema2 = external_exports2.object({
43815
+ action: PairingActionSchema2,
43816
+ /** The panel's pairing token. Approving while unpaired pairs with it. */
43817
+ token: external_exports2.string(),
43818
+ /** The extension's own id; the panel's service worker sends no Origin. */
43819
+ extensionId: external_exports2.string().optional(),
43820
+ /** The app an approve, refuse or revoke is about. */
43821
+ app: external_exports2.string().max(APP_NAME_MAX2).optional()
43822
+ });
43823
+ var PendingAppSchema2 = external_exports2.object({
43824
+ name: external_exports2.string(),
43825
+ /** Epoch ms of the first call that asked. */
43826
+ askedAt: external_exports2.number().int().nonnegative()
43827
+ });
43828
+ var ApprovedAppSchema2 = external_exports2.object({
43829
+ name: external_exports2.string(),
43830
+ /** ISO time of the user's approval. */
43831
+ approvedAt: external_exports2.string()
43832
+ });
43833
+ var PairingStatusSchema2 = external_exports2.object({
43834
+ /** A pairing record or a configured token exists on this computer. */
43835
+ paired: external_exports2.boolean(),
43836
+ /** The presented token is the paired one. False for another browser profile. */
43837
+ yours: external_exports2.boolean(),
43838
+ /** An unpaired connector still accepts a claim. */
43839
+ windowOpen: external_exports2.boolean(),
43840
+ /** Epoch ms when the claim window ends; null once paired. */
43841
+ windowEndsAt: external_exports2.number().int().nonnegative().nullable(),
43842
+ /** Empty unless the presented token is the paired one, or nothing is paired yet. */
43843
+ pending: external_exports2.array(PendingAppSchema2),
43844
+ /** Empty unless the presented token is the paired one. */
43845
+ apps: external_exports2.array(ApprovedAppSchema2)
43846
+ });
43847
+ var PairingRefusalSchema2 = external_exports2.enum([
43848
+ "forbidden_origin",
43849
+ "unauthorized",
43850
+ "paired_elsewhere",
43851
+ "window_closed",
43852
+ "unknown_app",
43853
+ "bad_request"
43854
+ ]);
43855
+ var PairingAnswerSchema2 = external_exports2.discriminatedUnion("ok", [
43856
+ external_exports2.object({ ok: external_exports2.literal(true), status: PairingStatusSchema2 }),
43857
+ external_exports2.object({ ok: external_exports2.literal(false), reason: PairingRefusalSchema2 })
43858
+ ]);
43859
+ var MCP_APP_HEADER2 = "x-datalab-mcp-app";
43363
43860
  var READ_ONLY_TOOLS2 = [
43364
43861
  "datalab_browsers",
43365
43862
  // --- Search-ad estimates. Uses the user's own advertiser API credentials. ---
@@ -43597,6 +44094,7 @@ var TOOL_TIERS2 = Object.freeze({
43597
44094
  photo_inpaint: "write",
43598
44095
  photo_group: "write",
43599
44096
  photo_ungroup: "write",
44097
+ photo_redact_add: "write",
43600
44098
  // ── Gallery: the free way in ────────────────────────────────────
43601
44099
  //
43602
44100
  // Destructive because it reads a path off the user's disk, the same
@@ -43652,11 +44150,13 @@ var TOOL_TIERS2 = Object.freeze({
43652
44150
  video_marker_add: "write",
43653
44151
  video_marker_remove: "destructive",
43654
44152
  video_lane_set: "write",
44153
+ video_subtitle_style_set: "write",
43655
44154
  video_auto_edit: "write",
43656
44155
  video_template_list: "read",
43657
44156
  video_template_apply: "destructive",
43658
44157
  video_post_import: "write",
43659
44158
  video_source_add: "write",
44159
+ video_redact_add: "write",
43660
44160
  // ── Post editor: reads ──────────────────────────────────────────
43661
44161
  editor_read: "read",
43662
44162
  editor_read_structure: "read",
@@ -43728,6 +44228,8 @@ var TOOL_TIERS2 = Object.freeze({
43728
44228
  tab_open: "write",
43729
44229
  tab_focus: "write",
43730
44230
  tab_close: "destructive",
44231
+ // Runs the caller's own code in one open tab, so it can do anything that page can.
44232
+ tab_debug: "destructive",
43731
44233
  // Insertion appends, so it never passes through the overwrite prompt; the
43732
44234
  // tier is the only barrier, and the user approves each image's source.
43733
44235
  editor_insert_image: "destructive",
@@ -43762,6 +44264,9 @@ var TOOL_TIERS2 = Object.freeze({
43762
44264
  editor_insert_component: "write",
43763
44265
  editor_replace: "destructive"
43764
44266
  });
44267
+ var ADMITTED_TOOLS2 = Object.freeze([
44268
+ .../* @__PURE__ */ new Set([...READ_ONLY_TOOLS2, ...Object.keys(TOOL_TIERS2)])
44269
+ ]);
43765
44270
  var PAID_TOOL_COSTS2 = Object.freeze({
43766
44271
  video_narration_generate: Object.freeze({
43767
44272
  basis: "\uBAA9\uC18C\uB9AC\uAC00 \uC5C6\uB294 \uC7A5\uBA74 \uC218\uB9CC\uD07C \uC74C\uC131 \uC0DD\uC131",
@@ -44098,12 +44603,22 @@ function defaultSpawn(daemonEntry, args) {
44098
44603
  var nextRpcId = 0;
44099
44604
  var POST_TIMEOUT_MS = REQUEST_DEADLINE_MS2 + 15e3;
44100
44605
  function credentialHeader() {
44101
- const token = process.env["DATALAB_MCP_TOKEN"]?.trim();
44606
+ const token = localRootToken();
44102
44607
  return token ? { authorization: `Bearer ${token}` } : {};
44103
44608
  }
44609
+ function localRootToken() {
44610
+ const configured = process.env["DATALAB_MCP_TOKEN"]?.trim();
44611
+ if (configured) return configured;
44612
+ return readPairingRecord()?.token;
44613
+ }
44104
44614
  var CLIENT_ID = randomUUID3();
44105
44615
  var CLIENT_ID_HEADER = "x-datalab-mcp-client";
44106
- async function postMcp(fetchImpl, url3, method, params) {
44616
+ function appHeader(name) {
44617
+ const ascii2 = (name ?? "").replace(/[^\x20-\x7e]/gu, "").trim();
44618
+ if (ascii2.length === 0) return {};
44619
+ return { [MCP_APP_HEADER2]: ascii2.slice(0, APP_NAME_MAX2) };
44620
+ }
44621
+ async function postMcp(fetchImpl, url3, method, params, appName) {
44107
44622
  nextRpcId += 1;
44108
44623
  const payload = {
44109
44624
  jsonrpc: "2.0",
@@ -44117,7 +44632,8 @@ async function postMcp(fetchImpl, url3, method, params) {
44117
44632
  "content-type": "application/json",
44118
44633
  accept: "application/json",
44119
44634
  ...credentialHeader(),
44120
- [CLIENT_ID_HEADER]: CLIENT_ID
44635
+ [CLIENT_ID_HEADER]: CLIENT_ID,
44636
+ ...appHeader(appName)
44121
44637
  },
44122
44638
  body: JSON.stringify(payload),
44123
44639
  signal: AbortSignal.timeout(POST_TIMEOUT_MS)
@@ -44178,7 +44694,7 @@ async function ensureDaemonRunning(deps = {}) {
44178
44694
  const intervalMs = deps.intervalMs ?? READY_INTERVAL_MS;
44179
44695
  const base = `http://${host}:${port}`;
44180
44696
  const selfVersion = deps.selfVersion;
44181
- const token = deps.token ?? process.env["DATALAB_MCP_TOKEN"];
44697
+ const token = deps.token ?? localRootToken();
44182
44698
  const readVersion2 = deps.readVersion ?? defaultReadVersion;
44183
44699
  const shutdown = deps.shutdown ?? defaultShutdown;
44184
44700
  const checkAuthority = deps.checkAuthority ?? defaultCheckAuthority;
@@ -44272,6 +44788,7 @@ function createAdapterServer(deps = {}) {
44272
44788
  // re-fetch the catalog without a restart.
44273
44789
  { capabilities: { tools: { listChanged: true } } }
44274
44790
  );
44791
+ const hostApp = () => server.getClientVersion()?.name;
44275
44792
  let daemonReady = deps.ready === void 0;
44276
44793
  let servedEarly = false;
44277
44794
  void deps.ready?.then(() => {
@@ -44300,7 +44817,13 @@ function createAdapterServer(deps = {}) {
44300
44817
  }
44301
44818
  let resp;
44302
44819
  try {
44303
- resp = await postMcp(fetchImpl, mcpUrl, "tools/list");
44820
+ resp = await postMcp(
44821
+ fetchImpl,
44822
+ mcpUrl,
44823
+ "tools/list",
44824
+ void 0,
44825
+ hostApp()
44826
+ );
44304
44827
  } catch (first) {
44305
44828
  log(`tools/list found no connector; restarting it and retrying`);
44306
44829
  try {
@@ -44310,7 +44833,13 @@ function createAdapterServer(deps = {}) {
44310
44833
  log,
44311
44834
  selfVersion: deps.version
44312
44835
  });
44313
- resp = await postMcp(fetchImpl, mcpUrl, "tools/list");
44836
+ resp = await postMcp(
44837
+ fetchImpl,
44838
+ mcpUrl,
44839
+ "tools/list",
44840
+ void 0,
44841
+ hostApp()
44842
+ );
44314
44843
  } catch (second) {
44315
44844
  log(`tools/list serving the offline fa\xE7ade: ${describeError(second)}`);
44316
44845
  return {
@@ -44340,10 +44869,13 @@ function createAdapterServer(deps = {}) {
44340
44869
  await deps.ready;
44341
44870
  let resp;
44342
44871
  try {
44343
- resp = await postMcp(fetchImpl, mcpUrl, "tools/call", {
44344
- name,
44345
- arguments: args ?? {}
44346
- });
44872
+ resp = await postMcp(
44873
+ fetchImpl,
44874
+ mcpUrl,
44875
+ "tools/call",
44876
+ { name, arguments: args ?? {} },
44877
+ hostApp()
44878
+ );
44347
44879
  } catch (first) {
44348
44880
  if (isTimeout(first)) return failedCall(first);
44349
44881
  try {
@@ -44362,10 +44894,13 @@ function createAdapterServer(deps = {}) {
44362
44894
  log,
44363
44895
  selfVersion: deps.version
44364
44896
  });
44365
- return postMcp(fetchImpl, mcpUrl, "tools/call", {
44366
- name,
44367
- arguments: args ?? {}
44368
- });
44897
+ return postMcp(
44898
+ fetchImpl,
44899
+ mcpUrl,
44900
+ "tools/call",
44901
+ { name, arguments: args ?? {} },
44902
+ hostApp()
44903
+ );
44369
44904
  }
44370
44905
  function failedCall(err) {
44371
44906
  log(`tools/call transport failure: ${describeError(err)}`);
@@ -44493,7 +45028,7 @@ async function updateInstalledCopy(selfVersion, log, deps = {}) {
44493
45028
  return "migrated";
44494
45029
  }
44495
45030
  async function quietInstallerIo() {
44496
- const installer = await import("./dist-5AJOOWYN.js");
45031
+ const installer = await import("./dist-JMZ4GVJ4.js");
44497
45032
  const io = installer.createNodeIo();
44498
45033
  io.out = (line) => defaultLog(line);
44499
45034
  return { installer, io };
@@ -44633,6 +45168,10 @@ async function dispatchCli(argv, handlers) {
44633
45168
  handlers.serve();
44634
45169
  return;
44635
45170
  }
45171
+ if (sub === "unpair") {
45172
+ await handlers.unpair();
45173
+ return;
45174
+ }
44636
45175
  if (sub !== void 0 && !sub.startsWith("-")) {
44637
45176
  handlers.unknown(sub);
44638
45177
  return;
@@ -44641,8 +45180,14 @@ async function dispatchCli(argv, handlers) {
44641
45180
  }
44642
45181
 
44643
45182
  export {
45183
+ deletePairingRecord,
45184
+ DEFAULT_PORT,
45185
+ DEFAULT_HOST,
44644
45186
  resolveConfig,
45187
+ tryConnect,
45188
+ readTakeoverSecret,
44645
45189
  runDaemon,
45190
+ defaultShutdown,
44646
45191
  ensureDaemonRunning,
44647
45192
  createAdapterServer,
44648
45193
  runAdapter,