@modootoday/datalab-extension-mcp 1.17.1 → 1.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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-MX35GA3V.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)
@@ -19671,7 +19680,11 @@ var HelloNackReasonSchema = external_exports.enum([
19671
19680
  /** Root authority cannot open a browser session. */
19672
19681
  "browser_registration_required",
19673
19682
  /** This panel predates mandatory browser routing and file permits. */
19674
- "browser_capability_required"
19683
+ "browser_capability_required",
19684
+ /** The connector is paired with another browser's key; only that key is accepted. */
19685
+ "paired_elsewhere",
19686
+ /** Nothing is paired and the pairing window has ended; a restart reopens it. */
19687
+ "window_closed"
19675
19688
  ]);
19676
19689
  var BrowserRoutingSchema = external_exports.object({
19677
19690
  targetBrowserId: external_exports.string(),
@@ -19822,6 +19835,7 @@ function timingSafeEqual(a, b) {
19822
19835
  return equal(left, right);
19823
19836
  }
19824
19837
  var MIN_TOKEN_LENGTH = 32;
19838
+ var PUBLISHED_EXTENSION_ID = "ldoknfkedngbdfgdkeicojmhnojgpdcb";
19825
19839
  function checkToken(presented, expected) {
19826
19840
  const fail = {
19827
19841
  ok: false,
@@ -19881,6 +19895,70 @@ function resolveCredential(presented, known) {
19881
19895
  if (browserId === void 0 || browserId.length === 0) return REFUSED;
19882
19896
  return { kind: "claimed", browserId };
19883
19897
  }
19898
+ var PAIRING_ROUTE = "/bridge/pairing";
19899
+ var APP_NAME_MAX = 64;
19900
+ function normalizeAppName(raw) {
19901
+ if (typeof raw !== "string") return null;
19902
+ const printable = Array.from(raw, (ch) => {
19903
+ const code = ch.charCodeAt(0);
19904
+ return code < 32 || code === 127 ? " " : ch;
19905
+ });
19906
+ const cleaned = printable.join("").trim();
19907
+ if (cleaned.length === 0) return null;
19908
+ return cleaned.slice(0, APP_NAME_MAX);
19909
+ }
19910
+ var PairingActionSchema = external_exports.enum([
19911
+ "status",
19912
+ "approve",
19913
+ "refuse",
19914
+ "revoke"
19915
+ ]);
19916
+ var PairingRequestSchema = external_exports.object({
19917
+ action: PairingActionSchema,
19918
+ /** The panel's pairing token. Approving while unpaired pairs with it. */
19919
+ token: external_exports.string(),
19920
+ /** The extension's own id; the panel's service worker sends no Origin. */
19921
+ extensionId: external_exports.string().optional(),
19922
+ /** The app an approve, refuse or revoke is about. */
19923
+ app: external_exports.string().max(APP_NAME_MAX).optional()
19924
+ });
19925
+ var PendingAppSchema = external_exports.object({
19926
+ name: external_exports.string(),
19927
+ /** Epoch ms of the first call that asked. */
19928
+ askedAt: external_exports.number().int().nonnegative()
19929
+ });
19930
+ var ApprovedAppSchema = external_exports.object({
19931
+ name: external_exports.string(),
19932
+ /** ISO time of the user's approval. */
19933
+ approvedAt: external_exports.string()
19934
+ });
19935
+ var PairingStatusSchema = external_exports.object({
19936
+ /** A pairing record or a configured token exists on this computer. */
19937
+ paired: external_exports.boolean(),
19938
+ /** The presented token is the paired one. False for another browser profile. */
19939
+ yours: external_exports.boolean(),
19940
+ /** An unpaired connector still accepts a claim. */
19941
+ windowOpen: external_exports.boolean(),
19942
+ /** Epoch ms when the claim window ends; null once paired. */
19943
+ windowEndsAt: external_exports.number().int().nonnegative().nullable(),
19944
+ /** Empty unless the presented token is the paired one, or nothing is paired yet. */
19945
+ pending: external_exports.array(PendingAppSchema),
19946
+ /** Empty unless the presented token is the paired one. */
19947
+ apps: external_exports.array(ApprovedAppSchema)
19948
+ });
19949
+ var PairingRefusalSchema = external_exports.enum([
19950
+ "forbidden_origin",
19951
+ "unauthorized",
19952
+ "paired_elsewhere",
19953
+ "window_closed",
19954
+ "unknown_app",
19955
+ "bad_request"
19956
+ ]);
19957
+ var PairingAnswerSchema = external_exports.discriminatedUnion("ok", [
19958
+ external_exports.object({ ok: external_exports.literal(true), status: PairingStatusSchema }),
19959
+ external_exports.object({ ok: external_exports.literal(false), reason: PairingRefusalSchema })
19960
+ ]);
19961
+ var MCP_APP_HEADER = "x-datalab-mcp-app";
19884
19962
  var READ_ONLY_TOOLS = [
19885
19963
  "datalab_browsers",
19886
19964
  // --- Search-ad estimates. Uses the user's own advertiser API credentials. ---
@@ -20118,6 +20196,7 @@ var TOOL_TIERS = Object.freeze({
20118
20196
  photo_inpaint: "write",
20119
20197
  photo_group: "write",
20120
20198
  photo_ungroup: "write",
20199
+ photo_redact_add: "write",
20121
20200
  // ── Gallery: the free way in ────────────────────────────────────
20122
20201
  //
20123
20202
  // Destructive because it reads a path off the user's disk, the same
@@ -20173,11 +20252,13 @@ var TOOL_TIERS = Object.freeze({
20173
20252
  video_marker_add: "write",
20174
20253
  video_marker_remove: "destructive",
20175
20254
  video_lane_set: "write",
20255
+ video_subtitle_style_set: "write",
20176
20256
  video_auto_edit: "write",
20177
20257
  video_template_list: "read",
20178
20258
  video_template_apply: "destructive",
20179
20259
  video_post_import: "write",
20180
20260
  video_source_add: "write",
20261
+ video_redact_add: "write",
20181
20262
  // ── Post editor: reads ──────────────────────────────────────────
20182
20263
  editor_read: "read",
20183
20264
  editor_read_structure: "read",
@@ -20249,6 +20330,8 @@ var TOOL_TIERS = Object.freeze({
20249
20330
  tab_open: "write",
20250
20331
  tab_focus: "write",
20251
20332
  tab_close: "destructive",
20333
+ // Runs the caller's own code in one open tab, so it can do anything that page can.
20334
+ tab_debug: "destructive",
20252
20335
  // Insertion appends, so it never passes through the overwrite prompt; the
20253
20336
  // tier is the only barrier, and the user approves each image's source.
20254
20337
  editor_insert_image: "destructive",
@@ -20283,6 +20366,9 @@ var TOOL_TIERS = Object.freeze({
20283
20366
  editor_insert_component: "write",
20284
20367
  editor_replace: "destructive"
20285
20368
  });
20369
+ var ADMITTED_TOOLS = Object.freeze([
20370
+ .../* @__PURE__ */ new Set([...READ_ONLY_TOOLS, ...Object.keys(TOOL_TIERS)])
20371
+ ]);
20286
20372
  var PAID_TOOL_COSTS = Object.freeze({
20287
20373
  video_narration_generate: Object.freeze({
20288
20374
  basis: "\uBAA9\uC18C\uB9AC\uAC00 \uC5C6\uB294 \uC7A5\uBA74 \uC218\uB9CC\uD07C \uC74C\uC131 \uC0DD\uC131",
@@ -20642,6 +20728,326 @@ function splitResultImages(result) {
20642
20728
  return { result: rest, images };
20643
20729
  }
20644
20730
  var MCP_SERVER_HEALTH_NAME = "datalab-extension-mcp-server";
20731
+ var LOG_MAX_BYTES = 1024 * 1024;
20732
+ var DIR_NAME = ".datalab-mcp";
20733
+ var FILE_NAME = "connector.log";
20734
+ function logDir(home = homedir()) {
20735
+ return join(home, DIR_NAME);
20736
+ }
20737
+ function logPath(home = homedir()) {
20738
+ return join(logDir(home), FILE_NAME);
20739
+ }
20740
+ function rolledLogPath(home = homedir()) {
20741
+ return `${logPath(home)}.1`;
20742
+ }
20743
+ function rollIfLarge(home = homedir(), maxBytes = LOG_MAX_BYTES) {
20744
+ try {
20745
+ const size = statSync(logPath(home)).size;
20746
+ if (size < maxBytes) return false;
20747
+ renameSync(logPath(home), rolledLogPath(home));
20748
+ return true;
20749
+ } catch {
20750
+ return false;
20751
+ }
20752
+ }
20753
+ function openLogFd(home = homedir()) {
20754
+ try {
20755
+ mkdirSync(logDir(home), { recursive: true });
20756
+ rollIfLarge(home);
20757
+ return openSync(logPath(home), "a");
20758
+ } catch {
20759
+ return null;
20760
+ }
20761
+ }
20762
+ function currentAccount(env = process.env, username = userInfo().username) {
20763
+ const domain22 = env["USERDOMAIN"]?.trim();
20764
+ if (!domain22) return username;
20765
+ return `${domain22}\\${username}`;
20766
+ }
20767
+ function ownerOnlyArgs(path, account) {
20768
+ return [path, "/inheritance:r", "/grant:r", `${account}:F`];
20769
+ }
20770
+ function defaultRunIcacls(args) {
20771
+ const root = process.env["SystemRoot"] ?? "C:\\Windows";
20772
+ const result = spawnSync(join2(root, "System32", "icacls.exe"), [...args], {
20773
+ stdio: "ignore",
20774
+ windowsHide: true,
20775
+ timeout: 1e4
20776
+ });
20777
+ return result.status === 0;
20778
+ }
20779
+ function restrictToOwner(path, run = defaultRunIcacls, account = currentAccount()) {
20780
+ return run(ownerOnlyArgs(path, account));
20781
+ }
20782
+ var OWNER_ONLY = 384;
20783
+ function writeOwnerOnly(path, body, deps = {}) {
20784
+ mkdirSync2(dirname(path), { recursive: true });
20785
+ writeFileSync(path, body, { encoding: "utf8", mode: OWNER_ONLY });
20786
+ if ((deps.platform ?? process.platform) === "win32") {
20787
+ restrictToOwner(path, deps.runIcacls);
20788
+ return;
20789
+ }
20790
+ try {
20791
+ chmodSync(path, OWNER_ONLY);
20792
+ } catch {
20793
+ }
20794
+ }
20795
+ var FILE_NAME2 = "pairing.json";
20796
+ function pairingPath(home = homedir2()) {
20797
+ return join3(logDir(home), FILE_NAME2);
20798
+ }
20799
+ function readPairingRecord(home = homedir2()) {
20800
+ let raw;
20801
+ try {
20802
+ raw = readFileSync(pairingPath(home), "utf8");
20803
+ } catch {
20804
+ return null;
20805
+ }
20806
+ let parsed;
20807
+ try {
20808
+ parsed = JSON.parse(raw);
20809
+ } catch {
20810
+ return null;
20811
+ }
20812
+ if (typeof parsed !== "object" || parsed === null) return null;
20813
+ const { token, pairedAt } = parsed;
20814
+ if (typeof token !== "string" || token.length < MIN_TOKEN_LENGTH) return null;
20815
+ if (typeof pairedAt !== "string") return null;
20816
+ return { token, pairedAt };
20817
+ }
20818
+ function writePairingRecord(record22, home = homedir2()) {
20819
+ try {
20820
+ writeOwnerOnly(pairingPath(home), `${JSON.stringify(record22)}
20821
+ `);
20822
+ return true;
20823
+ } catch {
20824
+ return false;
20825
+ }
20826
+ }
20827
+ function deletePairingRecord(home = homedir2()) {
20828
+ const path = pairingPath(home);
20829
+ try {
20830
+ readFileSync(path);
20831
+ } catch {
20832
+ return false;
20833
+ }
20834
+ rmSync(path, { force: true });
20835
+ return true;
20836
+ }
20837
+ var CLAIM_WINDOW_MS = 10 * 60 * 1e3;
20838
+ function fixedRoot(token) {
20839
+ return {
20840
+ source: "environment",
20841
+ current: () => token,
20842
+ claim: () => "already_paired",
20843
+ windowEndsAt: () => null,
20844
+ acceptsClaim: () => false
20845
+ };
20846
+ }
20847
+ function pairingRoot(options = {}) {
20848
+ const now = options.now ?? Date.now;
20849
+ const windowMs = options.windowMs ?? CLAIM_WINDOW_MS;
20850
+ const startedAt = now();
20851
+ let token = readPairingRecord(options.home)?.token ?? null;
20852
+ return {
20853
+ source: "side_panel",
20854
+ current: () => token,
20855
+ windowEndsAt: () => token === null ? startedAt + windowMs : null,
20856
+ acceptsClaim: () => token === null && now() - startedAt <= windowMs,
20857
+ claim(presented) {
20858
+ if (token !== null) return "already_paired";
20859
+ if (now() - startedAt > windowMs) return "window_closed";
20860
+ if (presented.length < MIN_TOKEN_LENGTH) return "invalid_token";
20861
+ const pairedAt = new Date(now()).toISOString();
20862
+ if (!writePairingRecord({ token: presented, pairedAt }, options.home)) {
20863
+ options.log?.(
20864
+ "could not write the pairing record; paired for this run only"
20865
+ );
20866
+ }
20867
+ token = presented;
20868
+ return "claimed";
20869
+ }
20870
+ };
20871
+ }
20872
+ var FILE_NAME3 = "apps.json";
20873
+ function appsPath(home = homedir3()) {
20874
+ return join4(logDir(home), FILE_NAME3);
20875
+ }
20876
+ function readApprovedApps(home = homedir3()) {
20877
+ let parsed;
20878
+ try {
20879
+ parsed = JSON.parse(readFileSync2(appsPath(home), "utf8"));
20880
+ } catch {
20881
+ return [];
20882
+ }
20883
+ if (typeof parsed !== "object" || parsed === null) return [];
20884
+ const list = parsed.apps;
20885
+ if (!Array.isArray(list)) return [];
20886
+ const out = [];
20887
+ for (const item of list) {
20888
+ if (typeof item !== "object" || item === null) continue;
20889
+ const { name, approvedAt } = item;
20890
+ const clean = normalizeAppName(name);
20891
+ if (clean === null || typeof approvedAt !== "string") continue;
20892
+ out.push({ name: clean, approvedAt });
20893
+ }
20894
+ return out;
20895
+ }
20896
+ function writeApprovedApps(apps, home = homedir3()) {
20897
+ try {
20898
+ writeOwnerOnly(appsPath(home), `${JSON.stringify({ apps })}
20899
+ `);
20900
+ return true;
20901
+ } catch {
20902
+ return false;
20903
+ }
20904
+ }
20905
+ var PENDING_CAP = 16;
20906
+ function createAppBook(options = {}) {
20907
+ const now = options.now ?? Date.now;
20908
+ let approved = readApprovedApps(options.home);
20909
+ const pending = /* @__PURE__ */ new Map();
20910
+ const refused = /* @__PURE__ */ new Set();
20911
+ const save = () => {
20912
+ if (writeApprovedApps(approved, options.home)) return;
20913
+ options.log?.("could not write the approved apps; kept for this run only");
20914
+ };
20915
+ return {
20916
+ see(raw) {
20917
+ const name = normalizeAppName(raw);
20918
+ if (name === null) return "refused";
20919
+ if (approved.some((app) => app.name === name)) return "approved";
20920
+ if (refused.has(name)) return "refused";
20921
+ if (!pending.has(name) && pending.size < PENDING_CAP) {
20922
+ pending.set(name, now());
20923
+ }
20924
+ return pending.has(name) ? "pending" : "refused";
20925
+ },
20926
+ approved: () => approved.map((app) => ({ ...app })),
20927
+ pending: () => [...pending].map(([name, askedAt]) => ({ name, askedAt })),
20928
+ approve(raw) {
20929
+ const name = normalizeAppName(raw);
20930
+ if (name === null || !pending.delete(name)) return false;
20931
+ approved = [
20932
+ ...approved,
20933
+ { name, approvedAt: new Date(now()).toISOString() }
20934
+ ];
20935
+ save();
20936
+ return true;
20937
+ },
20938
+ refuse(raw) {
20939
+ const name = normalizeAppName(raw);
20940
+ if (name === null || !pending.delete(name)) return false;
20941
+ refused.add(name);
20942
+ return true;
20943
+ },
20944
+ revoke(raw) {
20945
+ const name = normalizeAppName(raw);
20946
+ if (name === null) return false;
20947
+ const next = approved.filter((app) => app.name !== name);
20948
+ if (next.length === approved.length) return false;
20949
+ approved = next;
20950
+ refused.delete(name);
20951
+ save();
20952
+ return true;
20953
+ }
20954
+ };
20955
+ }
20956
+ var REFUSAL_STATUS = {
20957
+ forbidden_origin: 403,
20958
+ unauthorized: 403,
20959
+ paired_elsewhere: 403,
20960
+ window_closed: 403,
20961
+ unknown_app: 404,
20962
+ bad_request: 400
20963
+ };
20964
+ function refuse(reason) {
20965
+ return {
20966
+ status: REFUSAL_STATUS[reason],
20967
+ answer: { ok: false, reason }
20968
+ };
20969
+ }
20970
+ function createPairingDesk(options) {
20971
+ const { root, apps, extensionIds } = options;
20972
+ const statusFor = (yours) => {
20973
+ const held = root.current();
20974
+ const paired = held !== null;
20975
+ const windowOpen = root.acceptsClaim();
20976
+ const visible = paired ? yours : true;
20977
+ return {
20978
+ paired,
20979
+ yours,
20980
+ windowOpen,
20981
+ windowEndsAt: root.windowEndsAt(),
20982
+ pending: visible ? apps.pending() : [],
20983
+ apps: paired && yours ? apps.approved() : []
20984
+ };
20985
+ };
20986
+ return {
20987
+ handle(raw, origin) {
20988
+ const parsed = PairingRequestSchema.safeParse(raw);
20989
+ if (!parsed.success) return refuse("bad_request");
20990
+ const { action, token, extensionId, app } = parsed.data;
20991
+ const identity = checkExtensionIdentity(
20992
+ origin,
20993
+ extensionId,
20994
+ extensionIds
20995
+ );
20996
+ if (!identity.ok) return refuse("forbidden_origin");
20997
+ const held = root.current();
20998
+ const yours = held !== null && checkToken(token, held).ok;
20999
+ if (action === "status") {
21000
+ return { status: 200, answer: { ok: true, status: statusFor(yours) } };
21001
+ }
21002
+ if (held !== null && !yours) return refuse("paired_elsewhere");
21003
+ if (held === null && token.length < MIN_TOKEN_LENGTH) {
21004
+ return refuse("unauthorized");
21005
+ }
21006
+ if (app === void 0) return refuse("bad_request");
21007
+ if (action === "revoke") {
21008
+ if (held === null) return refuse("unauthorized");
21009
+ if (!apps.revoke(app)) return refuse("unknown_app");
21010
+ options.log?.("an approved AI app was revoked");
21011
+ return { status: 200, answer: { ok: true, status: statusFor(true) } };
21012
+ }
21013
+ const name = normalizeAppName(app);
21014
+ if (!apps.pending().some((entry) => entry.name === name)) {
21015
+ return refuse("unknown_app");
21016
+ }
21017
+ if (action === "refuse") {
21018
+ apps.refuse(app);
21019
+ return {
21020
+ status: 200,
21021
+ answer: { ok: true, status: statusFor(held !== null) }
21022
+ };
21023
+ }
21024
+ if (held === null) {
21025
+ if (!root.acceptsClaim()) return refuse("window_closed");
21026
+ if (root.claim(token) !== "claimed") return refuse("unauthorized");
21027
+ options.log?.("paired with a side panel");
21028
+ }
21029
+ apps.approve(app);
21030
+ return { status: 200, answer: { ok: true, status: statusFor(true) } };
21031
+ }
21032
+ };
21033
+ }
21034
+ var PAIRED_ELSEWHERE = "This connector is paired with another browser. Copy the connection key from that browser's settings into this browser's settings.";
21035
+ var WINDOW_CLOSED = "The pairing window has ended. Restart your AI app, then open the side panel within 10 minutes.";
21036
+ function nack(reason, message) {
21037
+ return { t: "hello_nack", reason, supported: [], message };
21038
+ }
21039
+ function pairingRefusal(root, presented, browserId) {
21040
+ if (browserId === void 0 || browserId.length === 0) return null;
21041
+ const held = root.current();
21042
+ if (held === null) {
21043
+ if (root.acceptsClaim()) return null;
21044
+ return nack("window_closed", WINDOW_CLOSED);
21045
+ }
21046
+ if (root.source !== "side_panel") return null;
21047
+ if (presented.length < MIN_TOKEN_LENGTH) return null;
21048
+ if (checkToken(presented, held).ok) return null;
21049
+ return nack("paired_elsewhere", PAIRED_ELSEWHERE);
21050
+ }
20645
21051
  function randomPrefix() {
20646
21052
  return Math.floor(Math.random() * 16777215).toString(36).padStart(4, "0");
20647
21053
  }
@@ -20797,6 +21203,7 @@ function daemonIdTag() {
20797
21203
  }
20798
21204
  var Bridge = class {
20799
21205
  #deps;
21206
+ #root;
20800
21207
  #sessions = /* @__PURE__ */ new Map();
20801
21208
  /** browserId to the name it reported, for datalab_browsers. */
20802
21209
  #labels = /* @__PURE__ */ new Map();
@@ -20811,6 +21218,7 @@ var Bridge = class {
20811
21218
  #cachedTools = [];
20812
21219
  constructor(deps) {
20813
21220
  this.#deps = deps;
21221
+ this.#root = resolveRoot(deps);
20814
21222
  const limit = deps.rateLimit ?? DEFAULT_RATE_LIMIT;
20815
21223
  this.#bucketTokens = limit.capacity;
20816
21224
  this.#bucketRefilledAt = (deps.now ?? Date.now)();
@@ -20952,8 +21360,24 @@ var Bridge = class {
20952
21360
  * The root token only. A browser's own credential must never open this:
20953
21361
  * one browser could then end another's unattended run.
20954
21362
  */
21363
+ /**
21364
+ * The root token a handshake is checked against. An unpaired connector
21365
+ * pairs only with a handshake that every other check admits: identity,
21366
+ * protocol and capabilities before this call, a routable name here.
21367
+ */
21368
+ #rootFor(presented, browserId) {
21369
+ const held = this.#root.current();
21370
+ if (held !== null) return held;
21371
+ if (browserId === void 0 || browserId.length === 0) return null;
21372
+ if (this.#root.claim(presented) === "claimed") {
21373
+ this.#deps.log?.("paired with a side panel");
21374
+ }
21375
+ return this.#root.current();
21376
+ }
20955
21377
  verifyRootToken(presented) {
20956
- return checkToken(presented ?? void 0, this.#deps.token).ok;
21378
+ const root = this.#root.current();
21379
+ if (root === null) return false;
21380
+ return checkToken(presented ?? void 0, root).ok;
20957
21381
  }
20958
21382
  /**
20959
21383
  * May this credential add a browser to this machine?
@@ -21158,10 +21582,28 @@ var Bridge = class {
21158
21582
  message: "This browser panel is outdated. Close and reopen the side panel before reconnecting."
21159
21583
  };
21160
21584
  }
21585
+ const rootToken = this.#rootFor(parsed.data.token, parsed.data.browserId);
21586
+ const explained = pairingRefusal(
21587
+ this.#root,
21588
+ parsed.data.token,
21589
+ parsed.data.browserId
21590
+ );
21591
+ if (explained !== null) {
21592
+ this.#deps.log?.(`refused a browser handshake: ${explained.reason}`);
21593
+ return explained;
21594
+ }
21595
+ if (rootToken === null) {
21596
+ return {
21597
+ t: "hello_nack",
21598
+ reason: "unauthorized",
21599
+ supported: [],
21600
+ message: "This connector is not paired. Restart your AI app, then connect from the side panel within 10 minutes."
21601
+ };
21602
+ }
21161
21603
  const tokenHash = digestToken(parsed.data.token);
21162
21604
  const credential = resolveCredential(
21163
21605
  { token: parsed.data.token, browserId: parsed.data.browserId },
21164
- { rootToken: this.#deps.token }
21606
+ { rootToken }
21165
21607
  );
21166
21608
  if (credential.kind !== "claimed") {
21167
21609
  this.#deps.log?.("refused an unauthorized browser credential");
@@ -21520,6 +21962,14 @@ var BridgeError = class extends Error {
21520
21962
  if (timing) this.timing = timing;
21521
21963
  }
21522
21964
  };
21965
+ function resolveRoot(deps) {
21966
+ if (deps.root !== void 0 && deps.token !== void 0) {
21967
+ throw new Error("Bridge takes a root credential or a token, not both.");
21968
+ }
21969
+ if (deps.root !== void 0) return deps.root;
21970
+ if (deps.token !== void 0) return fixedRoot(deps.token);
21971
+ throw new Error("Bridge needs a root credential or a token.");
21972
+ }
21523
21973
  var MIB = 1024 * 1024;
21524
21974
  var MAX_STAGE_BYTES = 500 * MIB;
21525
21975
  var STAGE_KIND_LIMITS = {
@@ -21590,7 +22040,7 @@ var MAX_RANGE_BYTES = MIB;
21590
22040
  var HANDLE = /^stage:([0-9a-f]{32})$/;
21591
22041
  var DEFAULT_TOKEN_TTL_MS = 30 * 60 * 1e3;
21592
22042
  var STAGE_CAPABILITY = "datalab-mcp-stage-v1";
21593
- function refuse(reason, retryable, message) {
22043
+ function refuse2(reason, retryable, message) {
21594
22044
  return { state: "REFUSED", reason, retryable, message };
21595
22045
  }
21596
22046
  function segment(...parts) {
@@ -21599,8 +22049,8 @@ function segment(...parts) {
21599
22049
  function createMediaStage(opts) {
21600
22050
  const now = opts.now ?? Date.now;
21601
22051
  const ttl = opts.tokenTtlMs ?? DEFAULT_TOKEN_TTL_MS;
21602
- const ledgerDir = join(opts.root, "ledger");
21603
- const blobDir = join(opts.root, "blob");
22052
+ const ledgerDir = join5(opts.root, "ledger");
22053
+ const blobDir = join5(opts.root, "blob");
21604
22054
  const tokens = /* @__PURE__ */ new Map();
21605
22055
  const active = /* @__PURE__ */ new Map();
21606
22056
  const received = /* @__PURE__ */ new Map();
@@ -21609,12 +22059,12 @@ function createMediaStage(opts) {
21609
22059
  (names) => Promise.all(
21610
22060
  names.filter(
21611
22061
  (name) => name.endsWith(".part") && !receiving.has(name.slice(0, -5))
21612
- ).map((name) => rm(join(blobDir, name), { force: true }))
22062
+ ).map((name) => rm(join5(blobDir, name), { force: true }))
21613
22063
  )
21614
22064
  ).catch(() => void 0);
21615
22065
  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);
22066
+ const ledgerPath = (key) => join5(ledgerDir, `${key}.json`);
22067
+ const blobPath = (key) => join5(blobDir, key);
21618
22068
  async function readRow(key) {
21619
22069
  try {
21620
22070
  const raw = await readFile(ledgerPath(key), "utf8");
@@ -21633,18 +22083,18 @@ function createMediaStage(opts) {
21633
22083
  const key = keyOf(req);
21634
22084
  const row = await readRow(key);
21635
22085
  if (row === "unreadable") {
21636
- return refuse("uploads_unproven", true, "\uC791\uC5C5 \uC0C1\uD0DC\uB97C \uC77D\uC9C0 \uBABB\uD588\uC5B4\uC694.");
22086
+ return refuse2("uploads_unproven", true, "\uC791\uC5C5 \uC0C1\uD0DC\uB97C \uC77D\uC9C0 \uBABB\uD588\uC5B4\uC694.");
21637
22087
  }
21638
22088
  if (row) {
21639
22089
  if (req.fence < row.fence) {
21640
- return refuse(
22090
+ return refuse2(
21641
22091
  "stale_fence",
21642
22092
  false,
21643
22093
  "\uB354 \uC0C8\uB85C\uC6B4 \uC2DC\uB3C4\uAC00 \uC774\uBBF8 \uC9C4\uD589\uB410\uC5B4\uC694."
21644
22094
  );
21645
22095
  }
21646
22096
  if (row.state === "SEALED") {
21647
- return refuse("already_sealed", false, "\uC774\uBBF8 \uBD09\uC778\uB41C \uC790\uC0B0\uC774\uC5D0\uC694.");
22097
+ return refuse2("already_sealed", false, "\uC774\uBBF8 \uBD09\uC778\uB41C \uC790\uC0B0\uC774\uC5D0\uC694.");
21648
22098
  }
21649
22099
  if (row.state === "OPEN") {
21650
22100
  for (const [token2, held] of tokens) {
@@ -21736,11 +22186,11 @@ function createMediaStage(opts) {
21736
22186
  const key = keyOf(req);
21737
22187
  const row = await readRow(key);
21738
22188
  if (row === "unreadable") {
21739
- return refuse("uploads_unproven", true, "\uC791\uC5C5 \uC0C1\uD0DC\uB97C \uC77D\uC9C0 \uBABB\uD588\uC5B4\uC694.");
22189
+ return refuse2("uploads_unproven", true, "\uC791\uC5C5 \uC0C1\uD0DC\uB97C \uC77D\uC9C0 \uBABB\uD588\uC5B4\uC694.");
21740
22190
  }
21741
- if (!row) return refuse("upload_expired", false, "\uC5F4\uB9B0 \uC790\uB9AC\uAC00 \uC5C6\uC5B4\uC694.");
22191
+ if (!row) return refuse2("upload_expired", false, "\uC5F4\uB9B0 \uC790\uB9AC\uAC00 \uC5C6\uC5B4\uC694.");
21742
22192
  if (req.fence < row.fence) {
21743
- return refuse(
22193
+ return refuse2(
21744
22194
  "stale_fence",
21745
22195
  false,
21746
22196
  "\uB354 \uC0C8\uB85C\uC6B4 \uC2DC\uB3C4\uAC00 \uC774\uBBF8 \uC9C4\uD589\uB410\uC5B4\uC694."
@@ -21757,17 +22207,17 @@ function createMediaStage(opts) {
21757
22207
  capabilityVersion: STAGE_CAPABILITY
21758
22208
  };
21759
22209
  }
21760
- return refuse("already_sealed", false, "\uC774\uBBF8 \uBD09\uC778\uB41C \uC790\uC0B0\uC774\uC5D0\uC694.");
22210
+ return refuse2("already_sealed", false, "\uC774\uBBF8 \uBD09\uC778\uB41C \uC790\uC0B0\uC774\uC5D0\uC694.");
21761
22211
  }
21762
22212
  let digest;
21763
22213
  try {
21764
22214
  digest = received.get(key) ?? await hashFile(blobPath(key));
21765
22215
  } catch {
21766
- return refuse("upload_expired", false, "\uBC1B\uC740 \uBC14\uC774\uD2B8\uAC00 \uC5C6\uC5B4\uC694.");
22216
+ return refuse2("upload_expired", false, "\uBC1B\uC740 \uBC14\uC774\uD2B8\uAC00 \uC5C6\uC5B4\uC694.");
21767
22217
  }
21768
22218
  const actual = digest.sha256;
21769
22219
  if (actual !== req.sha256 || digest.bytes !== req.bytes) {
21770
- return refuse(
22220
+ return refuse2(
21771
22221
  "hash_mismatch",
21772
22222
  false,
21773
22223
  "\uBC1B\uC740 \uBC14\uC774\uD2B8\uAC00 \uC54C\uB824\uC8FC\uC2E0 \uAC83\uACFC \uB2EC\uB77C\uC694."
@@ -21778,7 +22228,7 @@ function createMediaStage(opts) {
21778
22228
  received.delete(key);
21779
22229
  await rm(blobPath(key), { force: true });
21780
22230
  const cap = Math.round(STAGE_KIND_LIMITS[kind] / MIB);
21781
- return refuse(
22231
+ return refuse2(
21782
22232
  "too_large",
21783
22233
  false,
21784
22234
  `\uC774 \uC885\uB958\uC758 \uD30C\uC77C\uC740 ${cap}MB \uAE4C\uC9C0 \uC62C\uB9B4 \uC218 \uC788\uC5B4\uC694.`
@@ -21836,7 +22286,7 @@ function createMediaStage(opts) {
21836
22286
  };
21837
22287
  }
21838
22288
  if (row?.state === "SEALED") {
21839
- return refuse("already_sealed", false, "\uC774\uBBF8 \uBD09\uC778\uB41C \uC790\uC0B0\uC774\uC5D0\uC694.");
22289
+ return refuse2("already_sealed", false, "\uC774\uBBF8 \uBD09\uC778\uB41C \uC790\uC0B0\uC774\uC5D0\uC694.");
21840
22290
  }
21841
22291
  if ((active.get(key) ?? 0) > 0) {
21842
22292
  return {
@@ -21893,7 +22343,7 @@ function createMediaStage(opts) {
21893
22343
  for (const dir of [ledgerDir, blobDir]) {
21894
22344
  try {
21895
22345
  for (const name of await readdir(dir)) {
21896
- if (!name.endsWith(".part")) out.push(join(dir, name));
22346
+ if (!name.endsWith(".part")) out.push(join5(dir, name));
21897
22347
  }
21898
22348
  } catch {
21899
22349
  }
@@ -22218,6 +22668,141 @@ async function handleMcpRequest(bridge, body, accept, stage) {
22218
22668
  );
22219
22669
  }
22220
22670
  var MAX_MCP_BODY_BYTES = 256 * 1024;
22671
+ var MAX_BODY_BYTES = 64 * 1024;
22672
+ var MAX_RESULT_BODY_BYTES = 4 * 1024 * 1024;
22673
+ var MAX_ARTIFACT_BODY_BYTES = 2 * 1024 * 1024;
22674
+ function isFirstOrDecade(n) {
22675
+ if (n === 1) return true;
22676
+ let at = 10;
22677
+ while (at < n) at *= 10;
22678
+ return at === n;
22679
+ }
22680
+ function headerValue(raw) {
22681
+ const one = Array.isArray(raw) ? raw[0] : raw;
22682
+ const trimmed = one?.trim();
22683
+ return trimmed ? trimmed.slice(0, 128) : void 0;
22684
+ }
22685
+ function correlationValue(value, max) {
22686
+ return /^[a-zA-Z0-9_-]+$/.test(value) ? value.slice(0, max) : "redacted";
22687
+ }
22688
+ function writeSafely(res, status, headers, body) {
22689
+ if (res.writableEnded || res.destroyed) return;
22690
+ try {
22691
+ res.writeHead(status, headers);
22692
+ res.end(body);
22693
+ } catch {
22694
+ }
22695
+ }
22696
+ function json2(res, status, body) {
22697
+ writeSafely(
22698
+ res,
22699
+ status,
22700
+ { "content-type": "application/json" },
22701
+ JSON.stringify(body)
22702
+ );
22703
+ }
22704
+ function readJson(req, maxBytes) {
22705
+ return new Promise((resolve, reject) => {
22706
+ let size = 0;
22707
+ const chunks = [];
22708
+ req.on("data", (chunk) => {
22709
+ size += chunk.length;
22710
+ if (size > maxBytes) {
22711
+ reject(new Error("body too large"));
22712
+ req.destroy();
22713
+ return;
22714
+ }
22715
+ chunks.push(chunk);
22716
+ });
22717
+ req.on("end", () => {
22718
+ try {
22719
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
22720
+ } catch (err) {
22721
+ reject(err instanceof Error ? err : new Error(String(err)));
22722
+ }
22723
+ });
22724
+ req.on("error", reject);
22725
+ });
22726
+ }
22727
+ var CLIENT_WINDOW_MS = 6e4;
22728
+ var CLIENT_ID_CAP = 64;
22729
+ function createMcpObservation(log) {
22730
+ let withCredential = 0;
22731
+ let withoutCredential = 0;
22732
+ const seenClients = /* @__PURE__ */ new Map();
22733
+ let mostAtOnce = 0;
22734
+ const noteCredential = (present) => {
22735
+ const n = present ? withCredential += 1 : withoutCredential += 1;
22736
+ if (!isFirstOrDecade(n)) return;
22737
+ log?.(
22738
+ present ? `/mcp: ${n} call(s) carrying the pairing credential` : `/mcp: ${n} call(s) with no pairing credential`
22739
+ );
22740
+ };
22741
+ const noteClient = (id, now) => {
22742
+ if (!id) return;
22743
+ seenClients.set(id, now);
22744
+ for (const [at, last] of seenClients) {
22745
+ if (now - last > CLIENT_WINDOW_MS) seenClients.delete(at);
22746
+ }
22747
+ while (seenClients.size > CLIENT_ID_CAP) {
22748
+ const oldest = seenClients.keys().next().value;
22749
+ if (oldest === void 0) break;
22750
+ seenClients.delete(oldest);
22751
+ }
22752
+ if (seenClients.size <= mostAtOnce) return;
22753
+ mostAtOnce = seenClients.size;
22754
+ if (mostAtOnce < 2) return;
22755
+ log?.(
22756
+ `/mcp: ${mostAtOnce} adapters called within ${CLIENT_WINDOW_MS / 1e3}s \u2014 outside callers are not told apart`
22757
+ );
22758
+ };
22759
+ return { noteCredential, noteClient };
22760
+ }
22761
+ function handleArtifact(ctx, req, res) {
22762
+ const { opts } = ctx;
22763
+ const store = opts.artifactStore;
22764
+ if (!store) {
22765
+ json2(res, 404, { error: "not found" });
22766
+ return;
22767
+ }
22768
+ void readJson(req, MAX_ARTIFACT_BODY_BYTES).then(async (body) => {
22769
+ const b = body ?? {};
22770
+ const str = (k) => typeof b[k] === "string" ? b[k] : "";
22771
+ const tool = str("tool");
22772
+ const path = artifactPath(b["job"]);
22773
+ if (!str("sessionId") || !str("requestId") || !ARTIFACT_TOOLS.has(tool) || path === void 0) {
22774
+ json2(res, 403, { error: "unauthorized" });
22775
+ return;
22776
+ }
22777
+ const auth = opts.bridge.authorizeFileRequest({
22778
+ sessionId: str("sessionId"),
22779
+ requestId: str("requestId"),
22780
+ token: str("token"),
22781
+ path,
22782
+ tool
22783
+ });
22784
+ if (!auth.ok) {
22785
+ opts.log?.(`artifact refused: reason=${auth.reason}`);
22786
+ json2(res, 403, { error: "unauthorized" });
22787
+ return;
22788
+ }
22789
+ const offset = b["offset"];
22790
+ if (typeof offset !== "number" || !Number.isInteger(offset)) {
22791
+ json2(res, 400, { error: "bad_offset" });
22792
+ return;
22793
+ }
22794
+ const out = await store.write({
22795
+ key: `${str("sessionId")}:${str("requestId")}:${str("name")}`,
22796
+ name: str("name"),
22797
+ offset,
22798
+ data: str("data"),
22799
+ final: b["final"] === true,
22800
+ ...typeof b["bytes"] === "number" ? { bytes: b["bytes"] } : {},
22801
+ ...str("sha256") ? { sha256: str("sha256") } : {}
22802
+ });
22803
+ json2(res, out.ok ? 200 : 400, out);
22804
+ }).catch(() => json2(res, 400, { error: "bad request" }));
22805
+ }
22221
22806
  var MAX_FILE_BYTES = 10 * 1024 * 1024;
22222
22807
  function sniff(head) {
22223
22808
  const b = head;
@@ -22381,26 +22966,252 @@ async function openStagedImage(stage, handle) {
22381
22966
  fileName: `${handle.slice(6, 14)}.${contentType.slice(6)}`
22382
22967
  };
22383
22968
  }
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;
22969
+ function handleBridgeFile(ctx, req, res) {
22970
+ const { opts, streams } = ctx;
22971
+ void readJson(req, MAX_BODY_BYTES).then(async (body) => {
22972
+ const b = body;
22973
+ const token = typeof b?.token === "string" ? b.token : "";
22974
+ const path = typeof b?.path === "string" ? b.path : "";
22975
+ const hasSessionId = b !== null && Object.hasOwn(b, "sessionId");
22976
+ const hasRequestId = b !== null && Object.hasOwn(b, "requestId");
22977
+ const invalidSessionId = hasSessionId && (typeof b?.sessionId !== "string" || b.sessionId.length === 0);
22978
+ const invalidRequestId = hasRequestId && (typeof b?.requestId !== "string" || b.requestId.length === 0);
22979
+ if (!hasSessionId || !hasRequestId || invalidSessionId || invalidRequestId || // An export-save permit names a job, never a file to read.
22980
+ typeof b?.tool === "string" && ARTIFACT_TOOLS.has(b.tool)) {
22981
+ json2(res, 403, {
22982
+ error: "unauthorized",
22983
+ message: "\uC0AC\uC9C4 \uC694\uCCAD\uC758 \uC5F0\uACB0 \uC815\uBCF4\uB97C \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694."
22984
+ });
22985
+ return;
22986
+ }
22987
+ const auth = opts.bridge.authorizeFileRequest({
22988
+ sessionId: b.sessionId,
22989
+ requestId: b.requestId,
22990
+ token,
22991
+ path,
22992
+ ...typeof b?.tool === "string" ? { tool: b.tool } : {}
22993
+ });
22994
+ if (!auth.ok) {
22995
+ opts.log?.(
22996
+ `file request refused: reason=${auth.reason} credential=${auth.credential} tokenPresent=${String(token.length > 0)} sessionMatch=${String(auth.key !== void 0)} open=not-entered`
22997
+ );
22998
+ json2(res, 403, {
22999
+ error: "unauthorized",
23000
+ message: "\uC0AC\uC9C4\uC744 \uAC00\uC838\uC62C \uC5F0\uACB0\uC744 \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694."
23001
+ });
23002
+ return;
23003
+ }
23004
+ const streamEntry = streams.get(auth.key);
23005
+ if (!streamEntry || streamEntry.sessionId !== auth.sessionId || !opts.bridge.isSessionStreamActive(auth.key, auth.sessionId) || !opts.bridge.consumeFileRequest(auth)) {
23006
+ opts.log?.(
23007
+ `file request refused: reason=file_session_not_live credential=${auth.credential} tokenPresent=true sessionMatch=false open=not-entered`
23008
+ );
23009
+ json2(res, 403, {
23010
+ error: "unauthorized",
23011
+ message: "\uC0AC\uC9C4\uC744 \uAC00\uC838\uC62C \uC5F0\uACB0\uC774 \uC5F4\uB824 \uC788\uC9C0 \uC54A\uC544\uC694."
23012
+ });
23013
+ return;
23014
+ }
23015
+ opts.log?.(
23016
+ `file request authorised: browser=${correlationValue(auth.key, 8)} session=${correlationValue(auth.sessionId, 32)} request=${correlationValue(auth.requestId, 96)} credential=${auth.credential} open=entered`
23017
+ );
23018
+ let source = null;
23019
+ let owner = null;
23020
+ let peerClosed = false;
23021
+ const stop = () => {
23022
+ peerClosed = true;
23023
+ source?.destroy();
23024
+ };
23025
+ req.once("aborted", stop);
23026
+ res.once("close", stop);
23027
+ try {
23028
+ const out = path.startsWith("stage:") ? await openStagedImage(opts.mediaStage, path) : await (opts.openLocalImage ?? openLocalImage)(path);
23029
+ if (!out.ok) {
23030
+ if (!peerClosed) {
23031
+ json2(res, 400, { error: out.reason, message: out.message });
23032
+ }
23033
+ return;
23034
+ }
23035
+ source = out.stream;
23036
+ if (peerClosed) {
23037
+ source.destroy();
23038
+ return;
23039
+ }
23040
+ const current = streams.get(auth.key);
23041
+ if (current !== streamEntry || current.sessionId !== auth.sessionId || !opts.bridge.isSessionStreamActive(auth.key, auth.sessionId)) {
23042
+ source.destroy(new Error("browser session ended"));
23043
+ json2(res, 403, {
23044
+ error: "unauthorized",
23045
+ message: "\uC0AC\uC9C4\uC744 \uAC00\uC838\uC62C \uC5F0\uACB0\uC774 \uC5F4\uB824 \uC788\uC9C0 \uC54A\uC544\uC694."
23046
+ });
23047
+ return;
23048
+ }
23049
+ res.writeHead(200, {
23050
+ "content-type": out.contentType,
23051
+ "content-length": String(out.byteLength),
23052
+ "x-file-name": encodeURIComponent(out.fileName),
23053
+ "cache-control": "no-store"
23054
+ });
23055
+ owner = current;
23056
+ owner.fileStreams.add(source);
23057
+ await pipeline2(source, res);
23058
+ } catch {
23059
+ if (!res.writableEnded) res.destroy();
23060
+ } finally {
23061
+ req.off("aborted", stop);
23062
+ res.off("close", stop);
23063
+ if (source) owner?.fileStreams.delete(source);
23064
+ }
23065
+ }).catch(() => json2(res, 400, { error: "bad request" }));
23066
+ }
23067
+ function handleFileCancel(ctx, req, res) {
23068
+ const { opts } = ctx;
23069
+ void readJson(req, MAX_BODY_BYTES).then((body) => {
23070
+ const b = body;
23071
+ if (typeof b?.token !== "string" || typeof b.sessionId !== "string" || typeof b.requestId !== "string") {
23072
+ json2(res, 403, { error: "unauthorized" });
23073
+ return;
23074
+ }
23075
+ const reason = opts.bridge.cancelFileRequest({
23076
+ token: b.token,
23077
+ sessionId: b.sessionId,
23078
+ requestId: b.requestId
23079
+ });
23080
+ json2(res, reason === null ? 200 : 403, {
23081
+ ...reason === null ? { ok: true } : { error: "unauthorized" }
23082
+ });
23083
+ }).catch(() => json2(res, 400, { error: "bad request" }));
23084
+ }
23085
+ var CODE_APP_NOT_APPROVED = -32001;
23086
+ var WAITING_TEXT = "This AI app is waiting for approval in the Datalab side panel. Approve it there, then call again.";
23087
+ var REFUSED_TEXT = "This AI app was refused in the Datalab side panel. Restart the connector to be asked again.";
23088
+ function gateMcpApp(apps, nameHeader, body, accept) {
23089
+ if (apps === void 0) return null;
23090
+ const name = normalizeAppName(nameHeader);
23091
+ if (name === null) return null;
23092
+ const standing = apps.see(name);
23093
+ if (standing === "approved") return null;
23094
+ const request = typeof body === "object" && body !== null ? body : {};
23095
+ if (request.method !== "tools/call") return null;
23096
+ return frameMcpResponse(
23097
+ {
23098
+ jsonrpc: "2.0",
23099
+ id: request.id ?? null,
23100
+ error: {
23101
+ code: CODE_APP_NOT_APPROVED,
23102
+ message: standing === "refused" ? REFUSED_TEXT : WAITING_TEXT
23103
+ }
23104
+ },
23105
+ accept
23106
+ );
22395
23107
  }
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;
23108
+ function handleMediaUpload(ctx, req, res) {
23109
+ const { opts } = ctx;
23110
+ const stage = opts.mediaStage;
23111
+ if (!stage) {
23112
+ json2(res, 404, { error: "not found" });
23113
+ return;
23114
+ }
23115
+ const auth = req.headers.authorization ?? "";
23116
+ const token = auth.startsWith("Bearer ") ? auth.slice(7).trim() : "";
23117
+ if (!token) {
23118
+ json2(res, 403, { error: "unauthorized" });
23119
+ return;
23120
+ }
23121
+ void stage.receiveUpload(token, req).then((out) => {
23122
+ if (out.ok) {
23123
+ json2(res, 202, { ok: true, bytes: out.bytes });
23124
+ return;
23125
+ }
23126
+ const status = out.reason === "upload_expired" ? 403 : 400;
23127
+ json2(res, status, { error: out.reason });
23128
+ }).catch((err) => {
23129
+ opts.log?.(
23130
+ `media upload failed: ${err instanceof Error ? err.message : String(err)}`
23131
+ );
23132
+ json2(res, 500, { error: "upload_failed" });
23133
+ });
22400
23134
  }
22401
- function correlationValue(value, max) {
22402
- return /^[a-zA-Z0-9_-]+$/.test(value) ? value.slice(0, max) : "redacted";
23135
+ function handlePairing(ctx, req, res) {
23136
+ const desk = ctx.opts.pairingDesk;
23137
+ if (!desk) {
23138
+ json2(res, 404, { error: "not found" });
23139
+ return;
23140
+ }
23141
+ const origin = req.headers.origin;
23142
+ void readJson(req, MAX_BODY_BYTES).then((body) => {
23143
+ const reply = desk.handle(body, origin);
23144
+ json2(res, reply.status, reply.answer);
23145
+ }).catch(() => json2(res, 400, { ok: false, reason: "bad_request" }));
23146
+ }
23147
+ function handleStageRange(ctx, req, res) {
23148
+ const { opts } = ctx;
23149
+ void readJson(req, MAX_BODY_BYTES).then(async (body) => {
23150
+ const b = body;
23151
+ const handle = typeof b?.handle === "string" ? b.handle : "";
23152
+ const offset = b?.offset;
23153
+ const length = b?.length;
23154
+ if (typeof b?.sessionId !== "string" || typeof offset !== "number" || typeof length !== "number" || !Number.isInteger(offset) || !Number.isInteger(length) || offset < 0 || length < 1) {
23155
+ json2(res, 400, {
23156
+ error: "bad_request",
23157
+ message: "\uC77D\uC744 \uBC94\uC704\uB97C \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694."
23158
+ });
23159
+ return;
23160
+ }
23161
+ const auth = opts.bridge.authorizeStageRead({
23162
+ sessionId: b.sessionId,
23163
+ token: typeof b.token === "string" ? b.token : "",
23164
+ handle
23165
+ });
23166
+ if (!auth.ok || !opts.mediaStage) {
23167
+ opts.log?.(
23168
+ `stage range refused: reason=${auth.ok ? "no_stage" : auth.reason}`
23169
+ );
23170
+ json2(res, 403, {
23171
+ error: "unauthorized",
23172
+ message: "\uC774 \uD30C\uC77C\uC744 \uC77D\uC744 \uAD8C\uD55C\uC774 \uC5C6\uC5B4\uC694."
23173
+ });
23174
+ return;
23175
+ }
23176
+ const info = await opts.mediaStage.sealedInfo(handle);
23177
+ if (!info) {
23178
+ json2(res, 404, {
23179
+ error: "not_found",
23180
+ message: "\uBD09\uC778\uB41C \uD30C\uC77C\uC744 \uCC3E\uC9C0 \uBABB\uD588\uC5B4\uC694."
23181
+ });
23182
+ return;
23183
+ }
23184
+ if (offset > info.bytes) {
23185
+ json2(res, 416, {
23186
+ error: "out_of_range",
23187
+ message: "\uD30C\uC77C \uB05D\uC744 \uB118\uC5B4 \uC77D\uC73C\uB824\uACE0 \uD588\uC5B4\uC694."
23188
+ });
23189
+ return;
23190
+ }
23191
+ const piece = await opts.mediaStage.readRange(handle, offset, length);
23192
+ res.writeHead(200, {
23193
+ "content-type": "application/octet-stream",
23194
+ "content-length": String(piece.byteLength),
23195
+ "x-total-bytes": String(info.bytes),
23196
+ "x-stage-kind": info.kind,
23197
+ "access-control-expose-headers": "x-total-bytes, x-stage-kind",
23198
+ "cache-control": "no-store"
23199
+ });
23200
+ res.end(piece);
23201
+ }).catch(() => {
23202
+ if (!res.headersSent) {
23203
+ json2(res, 400, {
23204
+ error: "bad_request",
23205
+ message: "\uC77D\uC744 \uBC94\uC704\uB97C \uD655\uC778\uD558\uC9C0 \uBABB\uD588\uC5B4\uC694."
23206
+ });
23207
+ } else if (!res.writableEnded) {
23208
+ res.destroy();
23209
+ }
23210
+ });
22403
23211
  }
23212
+ var MCP_SERVER_HEALTH_SCHEMA = "datalab-extension-mcp-health-v1";
23213
+ var DEFAULT_TOOLS_CHANGED_DEBOUNCE_MS = 600;
23214
+ var MAX_MCP_BODY_BYTES2 = 256 * 1024;
22404
23215
  function createHttpBridge(opts) {
22405
23216
  const host = opts.host ?? "127.0.0.1";
22406
23217
  if (!isLoopbackHost(host)) {
@@ -22408,6 +23219,7 @@ function createHttpBridge(opts) {
22408
23219
  }
22409
23220
  const lifecycle = opts.lifecycle;
22410
23221
  const streams = /* @__PURE__ */ new Map();
23222
+ const ctx = { opts, streams };
22411
23223
  let toolsDropTimer = null;
22412
23224
  const debounceMs = opts.toolsChangedDebounceMs ?? DEFAULT_TOOLS_CHANGED_DEBOUNCE_MS;
22413
23225
  const toolSubscribers = /* @__PURE__ */ new Set();
@@ -22440,37 +23252,7 @@ function createHttpBridge(opts) {
22440
23252
  }, debounceMs);
22441
23253
  toolsDropTimer.unref?.();
22442
23254
  };
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
- };
23255
+ const mcpObservation = createMcpObservation(opts.log);
22474
23256
  const send = (frame, key) => {
22475
23257
  const stream = streams.get(key);
22476
23258
  if (!stream || stream.res.writableEnded) return false;
@@ -22522,13 +23304,20 @@ function createHttpBridge(opts) {
22522
23304
  const origin = req.headers.origin;
22523
23305
  if (req.method === "POST" && url22.pathname === "/mcp") {
22524
23306
  lifecycle?.bump?.();
22525
- noteMcpCredential(bearerToken(req.headers.authorization) !== null);
22526
- noteMcpClient(
23307
+ mcpObservation.noteCredential(
23308
+ bearerToken(req.headers.authorization) !== null
23309
+ );
23310
+ mcpObservation.noteClient(
22527
23311
  headerValue(req.headers["x-datalab-mcp-client"]),
22528
23312
  Date.now()
22529
23313
  );
22530
23314
  void readJson(req, MAX_MCP_BODY_BYTES2).then(
22531
- (body) => handleMcpRequest(
23315
+ (body) => gateMcpApp(
23316
+ opts.apps,
23317
+ headerValue(req.headers[MCP_APP_HEADER]),
23318
+ body,
23319
+ req.headers.accept
23320
+ ) ?? handleMcpRequest(
22532
23321
  opts.bridge,
22533
23322
  body,
22534
23323
  req.headers.accept,
@@ -22555,7 +23344,9 @@ function createHttpBridge(opts) {
22555
23344
  json2(res, 200, {
22556
23345
  name: MCP_SERVER_HEALTH_NAME,
22557
23346
  version: opts.identity.version,
22558
- schema: MCP_SERVER_HEALTH_SCHEMA
23347
+ schema: MCP_SERVER_HEALTH_SCHEMA,
23348
+ // Lets a local installer tie this answer to the process it may end.
23349
+ pid: process.pid
22559
23350
  });
22560
23351
  return;
22561
23352
  }
@@ -22645,230 +23436,24 @@ function createHttpBridge(opts) {
22645
23436
  }).catch(() => json2(res, 400, { error: "bad request" }));
22646
23437
  return;
22647
23438
  }
23439
+ if (req.method === "POST" && url22.pathname === PAIRING_ROUTE) {
23440
+ handlePairing(ctx, req, res);
23441
+ return;
23442
+ }
22648
23443
  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" }));
23444
+ handleBridgeFile(ctx, req, res);
22744
23445
  return;
22745
23446
  }
22746
23447
  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
- });
23448
+ handleStageRange(ctx, req, res);
22809
23449
  return;
22810
23450
  }
22811
23451
  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" }));
23452
+ handleArtifact(ctx, req, res);
22854
23453
  return;
22855
23454
  }
22856
23455
  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" }));
23456
+ handleFileCancel(ctx, req, res);
22872
23457
  return;
22873
23458
  }
22874
23459
  if (req.method === "GET" && url22.pathname === "/mcp/notifications") {
@@ -22897,30 +23482,7 @@ function createHttpBridge(opts) {
22897
23482
  return;
22898
23483
  }
22899
23484
  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
- });
23485
+ handleMediaUpload(ctx, req, res);
22924
23486
  return;
22925
23487
  }
22926
23488
  if (req.method === "POST" && url22.pathname === "/bridge/result") {
@@ -22966,68 +23528,17 @@ function createHttpBridge(opts) {
22966
23528
  })
22967
23529
  };
22968
23530
  }
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
23531
  var DEFAULT_PORT = 8765;
23009
23532
  var DEFAULT_HOST = "127.0.0.1";
23010
23533
  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) {
23534
+ const token = env.DATALAB_MCP_TOKEN?.trim() || null;
23535
+ if (token !== null && token.length < MIN_TOKEN_LENGTH) {
23019
23536
  return {
23020
23537
  ok: false,
23021
23538
  message: `DATALAB_MCP_TOKEN must be at least ${MIN_TOKEN_LENGTH} characters; got ${token.length}.`
23022
23539
  };
23023
23540
  }
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
- }
23541
+ const extensionId = env.DATALAB_MCP_EXTENSION_ID?.trim() || PUBLISHED_EXTENSION_ID;
23031
23542
  const host = env.DATALAB_MCP_HOST?.trim() || DEFAULT_HOST;
23032
23543
  if (!isLoopbackHost(host)) {
23033
23544
  return {
@@ -23053,37 +23564,6 @@ function parsePort(raw) {
23053
23564
  if (!Number.isInteger(n) || n < 1 || n > 65535) return null;
23054
23565
  return n;
23055
23566
  }
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
23567
  function tryConnect(host, port, timeoutMs, deps = {}) {
23088
23568
  const connect = deps.createConnection ?? createConnection;
23089
23569
  return new Promise((resolve) => {
@@ -23198,30 +23678,23 @@ var Lifecycle = class {
23198
23678
  }
23199
23679
  }
23200
23680
  };
23201
- var FILE_NAME2 = "takeover";
23202
- var OWNER_ONLY = 384;
23203
- function takeoverPath(home = homedir2()) {
23204
- return join3(logDir(home), FILE_NAME2);
23681
+ var FILE_NAME4 = "takeover";
23682
+ function takeoverPath(home = homedir4()) {
23683
+ return join6(logDir(home), FILE_NAME4);
23205
23684
  }
23206
- function writeTakeoverSecret(home = homedir2()) {
23685
+ function writeTakeoverSecret(home = homedir4()) {
23207
23686
  try {
23208
- mkdirSync2(logDir(home), { recursive: true });
23209
23687
  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
- }
23688
+ writeOwnerOnly(takeoverPath(home), `${secret}
23689
+ `);
23217
23690
  return secret;
23218
23691
  } catch {
23219
23692
  return null;
23220
23693
  }
23221
23694
  }
23222
- function readTakeoverSecret(home = homedir2()) {
23695
+ function readTakeoverSecret(home = homedir4()) {
23223
23696
  try {
23224
- const raw = readFileSync(takeoverPath(home), "utf8").trim();
23697
+ const raw = readFileSync3(takeoverPath(home), "utf8").trim();
23225
23698
  return raw === "" ? null : raw;
23226
23699
  } catch {
23227
23700
  return null;
@@ -23238,7 +23711,7 @@ function safeArtifactName(name) {
23238
23711
  function day(now) {
23239
23712
  return new Date(now).toISOString().slice(0, 10).replace(/-/g, "");
23240
23713
  }
23241
- function refuse2(reason, message) {
23714
+ function refuse3(reason, message) {
23242
23715
  return { ok: false, reason, message };
23243
23716
  }
23244
23717
  function createArtifactStore(opts) {
@@ -23257,16 +23730,16 @@ function createArtifactStore(opts) {
23257
23730
  async function write(chunk) {
23258
23731
  await expire();
23259
23732
  if (!BASE642.test(chunk.data)) {
23260
- return refuse2("bad_chunk", "\uB0B4\uBCF4\uB0B8 \uD30C\uC77C \uC870\uAC01\uC744 \uC77D\uC9C0 \uBABB\uD588\uC5B4\uC694.");
23733
+ return refuse3("bad_chunk", "\uB0B4\uBCF4\uB0B8 \uD30C\uC77C \uC870\uAC01\uC744 \uC77D\uC9C0 \uBABB\uD588\uC5B4\uC694.");
23261
23734
  }
23262
23735
  let entry = open42.get(chunk.key);
23263
23736
  if (!entry) {
23264
23737
  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.");
23738
+ return refuse3("bad_offset", "\uB0B4\uBCF4\uB0B8 \uD30C\uC77C\uC744 \uCC98\uC74C\uBD80\uD130 \uB2E4\uC2DC \uBCF4\uB0B4 \uC8FC\uC138\uC694.");
23266
23739
  }
23267
- const dir = join4(opts.root, day(now()));
23740
+ const dir = join7(opts.root, day(now()));
23268
23741
  await mkdir2(dir, { recursive: true });
23269
- const finalPath = join4(
23742
+ const finalPath = join7(
23270
23743
  dir,
23271
23744
  `${randomUUID2().slice(0, 8)}-${safeArtifactName(chunk.name)}`
23272
23745
  );
@@ -23281,12 +23754,12 @@ function createArtifactStore(opts) {
23281
23754
  }
23282
23755
  if (chunk.offset !== entry.received) {
23283
23756
  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.");
23757
+ return refuse3("bad_offset", "\uB0B4\uBCF4\uB0B8 \uD30C\uC77C \uC870\uAC01\uC758 \uC21C\uC11C\uAC00 \uB9DE\uC9C0 \uC54A\uC544\uC694.");
23285
23758
  }
23286
23759
  const bytes = Buffer.from(chunk.data, "base64");
23287
23760
  if (entry.received + bytes.length > MAX_ARTIFACT_BYTES) {
23288
23761
  await drop(chunk.key, entry);
23289
- return refuse2("too_large", "\uB0B4\uBCF4\uB0B8 \uD30C\uC77C\uC774 \uB108\uBB34 \uCEE4\uC694(\uCD5C\uB300 1GB).");
23762
+ return refuse3("too_large", "\uB0B4\uBCF4\uB0B8 \uD30C\uC77C\uC774 \uB108\uBB34 \uCEE4\uC694(\uCD5C\uB300 1GB).");
23290
23763
  }
23291
23764
  await appendFile(entry.partPath, bytes);
23292
23765
  entry.hash.update(bytes);
@@ -23297,7 +23770,7 @@ function createArtifactStore(opts) {
23297
23770
  const sha256 = entry.hash.digest("hex");
23298
23771
  if (chunk.bytes !== void 0 && chunk.bytes !== entry.received || chunk.sha256 !== void 0 && chunk.sha256 !== sha256) {
23299
23772
  await drop(chunk.key, entry);
23300
- return refuse2(
23773
+ return refuse3(
23301
23774
  "mismatch",
23302
23775
  "\uBC1B\uC740 \uD30C\uC77C\uC774 \uB0B4\uBCF4\uB0B8 \uD30C\uC77C\uACFC \uB2EC\uB77C\uC694. \uB2E4\uC2DC \uC2DC\uB3C4\uD574 \uC8FC\uC138\uC694."
23303
23776
  );
@@ -23340,18 +23813,21 @@ function runDaemon(env, deps = {}) {
23340
23813
  void http.close().finally(() => exit(0));
23341
23814
  }
23342
23815
  });
23816
+ const root = token === null ? pairingRoot({ home: deps.home, log }) : fixedRoot(token);
23817
+ const apps = token === null ? createAppBook({ home: deps.home, log }) : null;
23818
+ const pairingDesk = apps === null ? void 0 : createPairingDesk({ root, apps, extensionIds, log });
23343
23819
  const bridge = new Bridge({
23344
23820
  send: (frame, key) => http.send(frame, key),
23345
- token,
23821
+ root,
23346
23822
  extensionIds,
23347
23823
  serverVersion: version22,
23348
23824
  rateLimit: deps.rateLimit,
23349
23825
  log
23350
23826
  });
23351
23827
  const stateDir = logDir(deps.home);
23352
- const mediaStage = createMediaStage({ root: join5(stateDir, "media") });
23828
+ const mediaStage = createMediaStage({ root: join8(stateDir, "media") });
23353
23829
  const artifactStore = createArtifactStore({
23354
- root: join5(stateDir, "exports")
23830
+ root: join8(stateDir, "exports")
23355
23831
  });
23356
23832
  const http = createHttpBridge({
23357
23833
  bridge,
@@ -23359,6 +23835,8 @@ function runDaemon(env, deps = {}) {
23359
23835
  host,
23360
23836
  mediaStage,
23361
23837
  artifactStore,
23838
+ pairingDesk,
23839
+ apps: apps ?? void 0,
23362
23840
  heartbeatMs: deps.heartbeatMs,
23363
23841
  identity: { name: NAME, version: version22 },
23364
23842
  log,
@@ -23414,58 +23892,99 @@ function runDaemon(env, deps = {}) {
23414
23892
  }
23415
23893
 
23416
23894
  // ../mcp-server/dist/index.js
23417
- import { spawnSync } from "child_process";
23895
+ import { spawnSync as spawnSync2 } from "child_process";
23418
23896
  function parseNetstatListeners(output3, port) {
23419
23897
  const pids = /* @__PURE__ */ new Set();
23420
23898
  for (const line of output3.split(/\r?\n/)) {
23421
23899
  const cols = line.trim().split(/\s+/);
23422
23900
  if (cols.length < 5 || cols[0]?.toUpperCase() !== "TCP") continue;
23423
23901
  if (cols[3]?.toUpperCase() !== "LISTENING") continue;
23424
- const local = cols[1] ?? "";
23425
- if (local.slice(local.lastIndexOf(":") + 1) !== String(port)) continue;
23902
+ if (cols[1] !== `127.0.0.1:${String(port)}`) continue;
23426
23903
  const pid = Number(cols[4]);
23427
23904
  if (Number.isInteger(pid) && pid > 0) pids.add(pid);
23428
23905
  }
23429
23906
  return [...pids];
23430
23907
  }
23431
- function parseLsofPids(output3) {
23432
- return output3.split(/\r?\n/).map((l) => Number(l.trim())).filter((n) => Number.isInteger(n) && n > 0);
23908
+ function parseLsofListeners(output3, port) {
23909
+ const pids = /* @__PURE__ */ new Set();
23910
+ let pid = 0;
23911
+ for (const line of output3.split(/\r?\n/)) {
23912
+ if (line.startsWith("p")) {
23913
+ pid = Number(line.slice(1));
23914
+ continue;
23915
+ }
23916
+ if (!line.startsWith("n")) continue;
23917
+ if (line.slice(1) !== `127.0.0.1:${String(port)}`) continue;
23918
+ if (Number.isInteger(pid) && pid > 0) pids.add(pid);
23919
+ }
23920
+ return [...pids];
23433
23921
  }
23434
23922
  function listenerQuery(platform, port) {
23435
23923
  if (platform === "win32") {
23436
23924
  return { command: "netstat", args: ["-ano", "-p", "TCP"] };
23437
23925
  }
23438
23926
  if (platform === "darwin" || platform === "linux") {
23439
- return { command: "lsof", args: ["-ti", `tcp:${port}`, "-sTCP:LISTEN"] };
23927
+ return {
23928
+ command: "lsof",
23929
+ args: ["-nP", `-iTCP:${String(port)}`, "-sTCP:LISTEN", "-Fpn"]
23930
+ };
23440
23931
  }
23441
23932
  return null;
23442
23933
  }
23443
- function listenerPids(platform, port, run, selfPid) {
23444
- const query = listenerQuery(platform, port);
23445
- if (query === null) return [];
23446
- const output3 = run(query.command, query.args);
23447
- const pids = platform === "win32" ? parseNetstatListeners(output3, port) : parseLsofPids(output3);
23448
- return pids.filter((pid) => pid !== selfPid);
23934
+ function identityQuery(platform, pid) {
23935
+ if (platform === "darwin" || platform === "linux") {
23936
+ return { command: "ps", args: ["-o", "uid=,command=", "-p", String(pid)] };
23937
+ }
23938
+ return null;
23939
+ }
23940
+ function isOwnConnector(output3, uid) {
23941
+ const match = /^\s*(\d+)\s+(.+)$/.exec(output3.trim());
23942
+ if (match === null) return false;
23943
+ if (Number(match[1]) !== uid) return false;
23944
+ return (match[2] ?? "").includes("datalab-extension-mcp");
23945
+ }
23946
+ function soleListener(pids, selfPid) {
23947
+ const others = pids.filter((pid) => pid !== selfPid);
23948
+ if (others.length !== 1) return null;
23949
+ return others[0] ?? null;
23449
23950
  }
23450
23951
  function runQuiet(command, args) {
23451
- const res = spawnSync(command, args, {
23952
+ const res = spawnSync2(command, args, {
23452
23953
  encoding: "utf8",
23453
23954
  windowsHide: true,
23454
23955
  timeout: 1e4
23455
23956
  });
23456
23957
  return typeof res.stdout === "string" ? res.stdout : "";
23457
23958
  }
23458
- function killPortOwner(port, platform = process.platform) {
23959
+ function ownListener(platform, port, reportedPid, run, selfPid, uid) {
23960
+ if (reportedPid === null || uid === void 0) return null;
23961
+ const query = listenerQuery(platform, port);
23962
+ if (query === null) return null;
23963
+ const listing = run(query.command, query.args);
23964
+ const pids = platform === "win32" ? parseNetstatListeners(listing, port) : parseLsofListeners(listing, port);
23965
+ const pid = soleListener(pids, selfPid);
23966
+ if (pid === null || pid !== reportedPid) return null;
23967
+ const identity = identityQuery(platform, pid);
23968
+ if (identity === null) return null;
23969
+ return isOwnConnector(run(identity.command, identity.args), uid) ? pid : null;
23970
+ }
23971
+ function killPortOwner(port, reportedPid, platform = process.platform) {
23459
23972
  if (process.env["VITEST"] !== void 0) return false;
23460
- let signalled = false;
23461
- for (const pid of listenerPids(platform, port, runQuiet, process.pid)) {
23462
- try {
23463
- process.kill(pid, "SIGKILL");
23464
- signalled = true;
23465
- } catch {
23466
- }
23973
+ const pid = ownListener(
23974
+ platform,
23975
+ port,
23976
+ reportedPid,
23977
+ runQuiet,
23978
+ process.pid,
23979
+ process.getuid?.()
23980
+ );
23981
+ if (pid === null) return false;
23982
+ try {
23983
+ process.kill(pid, "SIGKILL");
23984
+ return true;
23985
+ } catch {
23986
+ return false;
23467
23987
  }
23468
- return signalled;
23469
23988
  }
23470
23989
 
23471
23990
  // src/adapter.ts
@@ -43280,7 +43799,11 @@ var HelloNackReasonSchema2 = external_exports2.enum([
43280
43799
  /** Root authority cannot open a browser session. */
43281
43800
  "browser_registration_required",
43282
43801
  /** This panel predates mandatory browser routing and file permits. */
43283
- "browser_capability_required"
43802
+ "browser_capability_required",
43803
+ /** The connector is paired with another browser's key; only that key is accepted. */
43804
+ "paired_elsewhere",
43805
+ /** Nothing is paired and the pairing window has ended; a restart reopens it. */
43806
+ "window_closed"
43284
43807
  ]);
43285
43808
  var BrowserRoutingSchema2 = external_exports2.object({
43286
43809
  targetBrowserId: external_exports2.string(),
@@ -43360,6 +43883,59 @@ var FrameEnvelopeSchema2 = external_exports2.object({ t: external_exports2.strin
43360
43883
  var REQUEST_DEADLINE_MS2 = 9e4;
43361
43884
  var EXEC_RESERVE_MS2 = 3e4;
43362
43885
  var CONFIRM_TIMEOUT_MS2 = REQUEST_DEADLINE_MS2 - EXEC_RESERVE_MS2;
43886
+ var APP_NAME_MAX2 = 64;
43887
+ var PairingActionSchema2 = external_exports2.enum([
43888
+ "status",
43889
+ "approve",
43890
+ "refuse",
43891
+ "revoke"
43892
+ ]);
43893
+ var PairingRequestSchema2 = external_exports2.object({
43894
+ action: PairingActionSchema2,
43895
+ /** The panel's pairing token. Approving while unpaired pairs with it. */
43896
+ token: external_exports2.string(),
43897
+ /** The extension's own id; the panel's service worker sends no Origin. */
43898
+ extensionId: external_exports2.string().optional(),
43899
+ /** The app an approve, refuse or revoke is about. */
43900
+ app: external_exports2.string().max(APP_NAME_MAX2).optional()
43901
+ });
43902
+ var PendingAppSchema2 = external_exports2.object({
43903
+ name: external_exports2.string(),
43904
+ /** Epoch ms of the first call that asked. */
43905
+ askedAt: external_exports2.number().int().nonnegative()
43906
+ });
43907
+ var ApprovedAppSchema2 = external_exports2.object({
43908
+ name: external_exports2.string(),
43909
+ /** ISO time of the user's approval. */
43910
+ approvedAt: external_exports2.string()
43911
+ });
43912
+ var PairingStatusSchema2 = external_exports2.object({
43913
+ /** A pairing record or a configured token exists on this computer. */
43914
+ paired: external_exports2.boolean(),
43915
+ /** The presented token is the paired one. False for another browser profile. */
43916
+ yours: external_exports2.boolean(),
43917
+ /** An unpaired connector still accepts a claim. */
43918
+ windowOpen: external_exports2.boolean(),
43919
+ /** Epoch ms when the claim window ends; null once paired. */
43920
+ windowEndsAt: external_exports2.number().int().nonnegative().nullable(),
43921
+ /** Empty unless the presented token is the paired one, or nothing is paired yet. */
43922
+ pending: external_exports2.array(PendingAppSchema2),
43923
+ /** Empty unless the presented token is the paired one. */
43924
+ apps: external_exports2.array(ApprovedAppSchema2)
43925
+ });
43926
+ var PairingRefusalSchema2 = external_exports2.enum([
43927
+ "forbidden_origin",
43928
+ "unauthorized",
43929
+ "paired_elsewhere",
43930
+ "window_closed",
43931
+ "unknown_app",
43932
+ "bad_request"
43933
+ ]);
43934
+ var PairingAnswerSchema2 = external_exports2.discriminatedUnion("ok", [
43935
+ external_exports2.object({ ok: external_exports2.literal(true), status: PairingStatusSchema2 }),
43936
+ external_exports2.object({ ok: external_exports2.literal(false), reason: PairingRefusalSchema2 })
43937
+ ]);
43938
+ var MCP_APP_HEADER2 = "x-datalab-mcp-app";
43363
43939
  var READ_ONLY_TOOLS2 = [
43364
43940
  "datalab_browsers",
43365
43941
  // --- Search-ad estimates. Uses the user's own advertiser API credentials. ---
@@ -43597,6 +44173,7 @@ var TOOL_TIERS2 = Object.freeze({
43597
44173
  photo_inpaint: "write",
43598
44174
  photo_group: "write",
43599
44175
  photo_ungroup: "write",
44176
+ photo_redact_add: "write",
43600
44177
  // ── Gallery: the free way in ────────────────────────────────────
43601
44178
  //
43602
44179
  // Destructive because it reads a path off the user's disk, the same
@@ -43652,11 +44229,13 @@ var TOOL_TIERS2 = Object.freeze({
43652
44229
  video_marker_add: "write",
43653
44230
  video_marker_remove: "destructive",
43654
44231
  video_lane_set: "write",
44232
+ video_subtitle_style_set: "write",
43655
44233
  video_auto_edit: "write",
43656
44234
  video_template_list: "read",
43657
44235
  video_template_apply: "destructive",
43658
44236
  video_post_import: "write",
43659
44237
  video_source_add: "write",
44238
+ video_redact_add: "write",
43660
44239
  // ── Post editor: reads ──────────────────────────────────────────
43661
44240
  editor_read: "read",
43662
44241
  editor_read_structure: "read",
@@ -43728,6 +44307,8 @@ var TOOL_TIERS2 = Object.freeze({
43728
44307
  tab_open: "write",
43729
44308
  tab_focus: "write",
43730
44309
  tab_close: "destructive",
44310
+ // Runs the caller's own code in one open tab, so it can do anything that page can.
44311
+ tab_debug: "destructive",
43731
44312
  // Insertion appends, so it never passes through the overwrite prompt; the
43732
44313
  // tier is the only barrier, and the user approves each image's source.
43733
44314
  editor_insert_image: "destructive",
@@ -43762,6 +44343,9 @@ var TOOL_TIERS2 = Object.freeze({
43762
44343
  editor_insert_component: "write",
43763
44344
  editor_replace: "destructive"
43764
44345
  });
44346
+ var ADMITTED_TOOLS2 = Object.freeze([
44347
+ .../* @__PURE__ */ new Set([...READ_ONLY_TOOLS2, ...Object.keys(TOOL_TIERS2)])
44348
+ ]);
43765
44349
  var PAID_TOOL_COSTS2 = Object.freeze({
43766
44350
  video_narration_generate: Object.freeze({
43767
44351
  basis: "\uBAA9\uC18C\uB9AC\uAC00 \uC5C6\uB294 \uC7A5\uBA74 \uC218\uB9CC\uD07C \uC74C\uC131 \uC0DD\uC131",
@@ -44098,12 +44682,22 @@ function defaultSpawn(daemonEntry, args) {
44098
44682
  var nextRpcId = 0;
44099
44683
  var POST_TIMEOUT_MS = REQUEST_DEADLINE_MS2 + 15e3;
44100
44684
  function credentialHeader() {
44101
- const token = process.env["DATALAB_MCP_TOKEN"]?.trim();
44685
+ const token = localRootToken();
44102
44686
  return token ? { authorization: `Bearer ${token}` } : {};
44103
44687
  }
44688
+ function localRootToken() {
44689
+ const configured = process.env["DATALAB_MCP_TOKEN"]?.trim();
44690
+ if (configured) return configured;
44691
+ return readPairingRecord()?.token;
44692
+ }
44104
44693
  var CLIENT_ID = randomUUID3();
44105
44694
  var CLIENT_ID_HEADER = "x-datalab-mcp-client";
44106
- async function postMcp(fetchImpl, url3, method, params) {
44695
+ function appHeader(name) {
44696
+ const ascii2 = (name ?? "").replace(/[^\x20-\x7e]/gu, "").trim();
44697
+ if (ascii2.length === 0) return {};
44698
+ return { [MCP_APP_HEADER2]: ascii2.slice(0, APP_NAME_MAX2) };
44699
+ }
44700
+ async function postMcp(fetchImpl, url3, method, params, appName) {
44107
44701
  nextRpcId += 1;
44108
44702
  const payload = {
44109
44703
  jsonrpc: "2.0",
@@ -44117,7 +44711,8 @@ async function postMcp(fetchImpl, url3, method, params) {
44117
44711
  "content-type": "application/json",
44118
44712
  accept: "application/json",
44119
44713
  ...credentialHeader(),
44120
- [CLIENT_ID_HEADER]: CLIENT_ID
44714
+ [CLIENT_ID_HEADER]: CLIENT_ID,
44715
+ ...appHeader(appName)
44121
44716
  },
44122
44717
  body: JSON.stringify(payload),
44123
44718
  signal: AbortSignal.timeout(POST_TIMEOUT_MS)
@@ -44136,6 +44731,18 @@ async function defaultReadVersion(base) {
44136
44731
  return null;
44137
44732
  }
44138
44733
  }
44734
+ async function defaultReadPid(base) {
44735
+ try {
44736
+ const res = await globalThis.fetch(
44737
+ `${base}/bridge/health`
44738
+ );
44739
+ const body = await res.json();
44740
+ if (!isOurConnector(body)) return null;
44741
+ return typeof body.pid === "number" && Number.isInteger(body.pid) ? body.pid : null;
44742
+ } catch {
44743
+ return null;
44744
+ }
44745
+ }
44139
44746
  async function defaultShutdown(base, token) {
44140
44747
  try {
44141
44748
  const res = await globalThis.fetch(
@@ -44178,18 +44785,18 @@ async function ensureDaemonRunning(deps = {}) {
44178
44785
  const intervalMs = deps.intervalMs ?? READY_INTERVAL_MS;
44179
44786
  const base = `http://${host}:${port}`;
44180
44787
  const selfVersion = deps.selfVersion;
44181
- const token = deps.token ?? process.env["DATALAB_MCP_TOKEN"];
44788
+ const token = deps.token ?? localRootToken();
44182
44789
  const readVersion2 = deps.readVersion ?? defaultReadVersion;
44183
44790
  const shutdown = deps.shutdown ?? defaultShutdown;
44184
44791
  const checkAuthority = deps.checkAuthority ?? defaultCheckAuthority;
44185
44792
  const readTakeover = deps.readTakeover ?? (() => readTakeoverSecret());
44186
- const killOwner = deps.killOwner ?? ((p) => killPortOwner(p));
44793
+ const killOwner = deps.killOwner ?? (async (p) => killPortOwner(p, await defaultReadPid(base)));
44187
44794
  const shutdownWithTakeover = async () => {
44188
44795
  const secret = readTakeover();
44189
44796
  return secret !== null && await shutdown(base, secret);
44190
44797
  };
44191
44798
  const seizePort = async () => {
44192
- if (!killOwner(port)) return false;
44799
+ if (!await killOwner(port)) return false;
44193
44800
  log(`ending the connector that holds port ${String(port)}`);
44194
44801
  await waitForPortRelease();
44195
44802
  await spawnAndWait();
@@ -44272,6 +44879,7 @@ function createAdapterServer(deps = {}) {
44272
44879
  // re-fetch the catalog without a restart.
44273
44880
  { capabilities: { tools: { listChanged: true } } }
44274
44881
  );
44882
+ const hostApp = () => server.getClientVersion()?.name;
44275
44883
  let daemonReady = deps.ready === void 0;
44276
44884
  let servedEarly = false;
44277
44885
  void deps.ready?.then(() => {
@@ -44300,7 +44908,13 @@ function createAdapterServer(deps = {}) {
44300
44908
  }
44301
44909
  let resp;
44302
44910
  try {
44303
- resp = await postMcp(fetchImpl, mcpUrl, "tools/list");
44911
+ resp = await postMcp(
44912
+ fetchImpl,
44913
+ mcpUrl,
44914
+ "tools/list",
44915
+ void 0,
44916
+ hostApp()
44917
+ );
44304
44918
  } catch (first) {
44305
44919
  log(`tools/list found no connector; restarting it and retrying`);
44306
44920
  try {
@@ -44310,7 +44924,13 @@ function createAdapterServer(deps = {}) {
44310
44924
  log,
44311
44925
  selfVersion: deps.version
44312
44926
  });
44313
- resp = await postMcp(fetchImpl, mcpUrl, "tools/list");
44927
+ resp = await postMcp(
44928
+ fetchImpl,
44929
+ mcpUrl,
44930
+ "tools/list",
44931
+ void 0,
44932
+ hostApp()
44933
+ );
44314
44934
  } catch (second) {
44315
44935
  log(`tools/list serving the offline fa\xE7ade: ${describeError(second)}`);
44316
44936
  return {
@@ -44340,10 +44960,13 @@ function createAdapterServer(deps = {}) {
44340
44960
  await deps.ready;
44341
44961
  let resp;
44342
44962
  try {
44343
- resp = await postMcp(fetchImpl, mcpUrl, "tools/call", {
44344
- name,
44345
- arguments: args ?? {}
44346
- });
44963
+ resp = await postMcp(
44964
+ fetchImpl,
44965
+ mcpUrl,
44966
+ "tools/call",
44967
+ { name, arguments: args ?? {} },
44968
+ hostApp()
44969
+ );
44347
44970
  } catch (first) {
44348
44971
  if (isTimeout(first)) return failedCall(first);
44349
44972
  try {
@@ -44362,10 +44985,13 @@ function createAdapterServer(deps = {}) {
44362
44985
  log,
44363
44986
  selfVersion: deps.version
44364
44987
  });
44365
- return postMcp(fetchImpl, mcpUrl, "tools/call", {
44366
- name,
44367
- arguments: args ?? {}
44368
- });
44988
+ return postMcp(
44989
+ fetchImpl,
44990
+ mcpUrl,
44991
+ "tools/call",
44992
+ { name, arguments: args ?? {} },
44993
+ hostApp()
44994
+ );
44369
44995
  }
44370
44996
  function failedCall(err) {
44371
44997
  log(`tools/call transport failure: ${describeError(err)}`);
@@ -44493,7 +45119,7 @@ async function updateInstalledCopy(selfVersion, log, deps = {}) {
44493
45119
  return "migrated";
44494
45120
  }
44495
45121
  async function quietInstallerIo() {
44496
- const installer = await import("./dist-5AJOOWYN.js");
45122
+ const installer = await import("./dist-43NMRYEU.js");
44497
45123
  const io = installer.createNodeIo();
44498
45124
  io.out = (line) => defaultLog(line);
44499
45125
  return { installer, io };
@@ -44633,6 +45259,10 @@ async function dispatchCli(argv, handlers) {
44633
45259
  handlers.serve();
44634
45260
  return;
44635
45261
  }
45262
+ if (sub === "unpair") {
45263
+ await handlers.unpair();
45264
+ return;
45265
+ }
44636
45266
  if (sub !== void 0 && !sub.startsWith("-")) {
44637
45267
  handlers.unknown(sub);
44638
45268
  return;
@@ -44641,8 +45271,14 @@ async function dispatchCli(argv, handlers) {
44641
45271
  }
44642
45272
 
44643
45273
  export {
45274
+ deletePairingRecord,
45275
+ DEFAULT_PORT,
45276
+ DEFAULT_HOST,
44644
45277
  resolveConfig,
45278
+ tryConnect,
45279
+ readTakeoverSecret,
44645
45280
  runDaemon,
45281
+ defaultShutdown,
44646
45282
  ensureDaemonRunning,
44647
45283
  createAdapterServer,
44648
45284
  runAdapter,