@tempad-dev/mcp 1.0.4 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -10
- package/README.zh-Hans.md +24 -9
- package/dist/{acquire-DHwsqq0j.mjs → acquire-CCPjn86-.mjs} +4 -4
- package/dist/acquire-CCPjn86-.mjs.map +1 -0
- package/dist/{acquire-BtKFZ9Lz.mjs → acquire-C_qsbxdV.mjs} +1 -1
- package/dist/{bootstrap-B9-RyWlM.mjs → bootstrap-BkZ1dGkI.mjs} +33 -27
- package/dist/bootstrap-BkZ1dGkI.mjs.map +1 -0
- package/dist/cli.mjs +6 -6
- package/dist/cli.mjs.map +1 -1
- package/dist/client-binding-CvSSv9JC.mjs.map +1 -1
- package/dist/{cold-start-U3cW0q9T.mjs → cold-start-Cv4OAoez.mjs} +1 -1
- package/dist/{cold-start-DOy9JsIQ.mjs → cold-start-qMVT1cNu.mjs} +94 -47
- package/dist/cold-start-qMVT1cNu.mjs.map +1 -0
- package/dist/{config-Busa_Dqv.mjs → config-Qvh73WBD.mjs} +20 -73
- package/dist/config-Qvh73WBD.mjs.map +1 -0
- package/dist/{design-task-store-BHR54v8-.mjs → design-task-store-BQy2SO7l.mjs} +4 -3
- package/dist/design-task-store-BQy2SO7l.mjs.map +1 -0
- package/dist/durable-json-_WKesGDj.mjs.map +1 -1
- package/dist/{edge-BUf7gs4J.mjs → edge-DO3aAdn1.mjs} +9 -9
- package/dist/edge-DO3aAdn1.mjs.map +1 -0
- package/dist/{edge-CHzaTUFt.mjs → edge-DdEimtG9.mjs} +1 -1
- package/dist/{hook-receipts-QJU3AMoY.mjs → hook-receipts-BIUk86RJ.mjs} +2 -2
- package/dist/hook-receipts-BIUk86RJ.mjs.map +1 -0
- package/dist/host-context-9TVtjsSm.mjs.map +1 -1
- package/dist/{hub-control-UlA4Fncg.mjs → hub-control-C2jNTi3G.mjs} +3 -3
- package/dist/hub-control-C2jNTi3G.mjs.map +1 -0
- package/dist/{hub-runtime-DsEO9zvX.mjs → hub-runtime-ApgbrLQI.mjs} +500 -454
- package/dist/hub-runtime-ApgbrLQI.mjs.map +1 -0
- package/dist/{hub-runtime-DjdqIgGl.mjs → hub-runtime-BZ6Nrold.mjs} +1 -1
- package/dist/hub.mjs +2 -2
- package/dist/hub.mjs.map +1 -1
- package/dist/{identity-CCaDEwgc.mjs → identity-C80lcT6j.mjs} +2 -2
- package/dist/identity-C80lcT6j.mjs.map +1 -0
- package/dist/indexes-zYqwqnU6.mjs.map +1 -1
- package/dist/log-transport.mjs.map +1 -1
- package/dist/managed-runtime.mjs +12 -12
- package/dist/managed-runtime.mjs.map +1 -1
- package/dist/on-exit-leak-free-By20-eFK.mjs.map +1 -1
- package/dist/pino-BiEyUxFF.mjs.map +1 -1
- package/dist/pino-abstract-transport-BBwCGDga.mjs.map +1 -1
- package/dist/pino-file.mjs.map +1 -1
- package/dist/pino-worker.mjs.map +1 -1
- package/dist/{probe-BeWkMbzQ.mjs → probe-BBGkIAHT.mjs} +7 -15
- package/dist/probe-BBGkIAHT.mjs.map +1 -0
- package/dist/process-environment-DRRIdoL8.mjs.map +1 -1
- package/dist/{processes-CBoalzSk.mjs → processes-BL7g1Hvw.mjs} +1 -1
- package/dist/{processes-BCCE8As7.mjs → processes-BX-yLfvZ.mjs} +67 -36
- package/dist/processes-BX-yLfvZ.mjs.map +1 -0
- package/dist/proper-lockfile-BgKrOq5D.mjs.map +1 -1
- package/dist/{protocol-7m-E_iFu.mjs → protocol-DlkrVyMK.mjs} +2 -2
- package/dist/protocol-DlkrVyMK.mjs.map +1 -0
- package/dist/{protocol-COK3rM6m.mjs → protocol-G4tyEGD3.mjs} +1 -1
- package/dist/runtime-identity-D9V-g5M-.mjs.map +1 -1
- package/dist/runtime-installer.mjs +3 -3
- package/dist/runtime-installer.mjs.map +1 -1
- package/dist/runtime-manifest.json +96 -97
- package/dist/{runtime-platform-C-Yk9F3L.mjs → runtime-platform-CpunJOI4.mjs} +143 -43
- package/dist/runtime-platform-CpunJOI4.mjs.map +1 -0
- package/dist/{runtime-recovery-DaRaQ8qY.mjs → runtime-recovery-CPfCb3rY.mjs} +2 -2
- package/dist/runtime-recovery-CPfCb3rY.mjs.map +1 -0
- package/dist/{runtime-recovery-DAYSaVV2.mjs → runtime-recovery-CexhaHl_.mjs} +1 -1
- package/dist/runtime-verification.mjs +5 -5
- package/dist/schemas-ZDdPV7RQ.mjs.map +1 -1
- package/dist/{server-CsCpY0Ft.mjs → server-CyzfkzoZ.mjs} +2 -2
- package/dist/server-CyzfkzoZ.mjs.map +1 -0
- package/dist/{shared-S0dtOYq8.mjs → shared-BRxN9qqm.mjs} +1 -1
- package/dist/{shared--othnF1c.mjs → shared-avqQD-kX.mjs} +10 -7
- package/dist/shared-avqQD-kX.mjs.map +1 -0
- package/dist/src-BSnzZMvK.mjs.map +1 -1
- package/dist/{stable-edge-VAAxSYSS.mjs → stable-edge-C5C0Rx5t.mjs} +3 -3
- package/dist/stable-edge-C5C0Rx5t.mjs.map +1 -0
- package/dist/{startup-log-CYlFgdy5.mjs → startup-log-CVOxFwjV.mjs} +2 -2
- package/dist/startup-log-CVOxFwjV.mjs.map +1 -0
- package/dist/{startup-log-DqK2uwBd.mjs → startup-log-DUPFFTwJ.mjs} +1 -1
- package/dist/{state-6qFcvi-I.mjs → state-4Dz7r-_n.mjs} +2 -2
- package/dist/state-4Dz7r-_n.mjs.map +1 -0
- package/dist/{state-BrWBtYNG.mjs → state-DDpxeTVd.mjs} +1 -1
- package/dist/stdio-20SBFdww.mjs.map +1 -1
- package/dist/{supervisor-CesT-H5_.mjs → supervisor-IWbA-VOB.mjs} +40 -42
- package/dist/supervisor-IWbA-VOB.mjs.map +1 -0
- package/dist/{task-storage-recovery-I9lpYYX6.mjs → task-storage-recovery-CabVFMUg.mjs} +3 -3
- package/dist/task-storage-recovery-CabVFMUg.mjs.map +1 -0
- package/dist/thread-stream-worker.mjs.map +1 -1
- package/dist/types-kNTSQOnR.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/acquire-DHwsqq0j.mjs.map +0 -1
- package/dist/bootstrap-B9-RyWlM.mjs.map +0 -1
- package/dist/cold-start-DOy9JsIQ.mjs.map +0 -1
- package/dist/config-Busa_Dqv.mjs.map +0 -1
- package/dist/design-task-store-BHR54v8-.mjs.map +0 -1
- package/dist/edge-BUf7gs4J.mjs.map +0 -1
- package/dist/hook-receipts-QJU3AMoY.mjs.map +0 -1
- package/dist/hub-control-UlA4Fncg.mjs.map +0 -1
- package/dist/hub-runtime-DsEO9zvX.mjs.map +0 -1
- package/dist/identity-CCaDEwgc.mjs.map +0 -1
- package/dist/probe-BeWkMbzQ.mjs.map +0 -1
- package/dist/processes-BCCE8As7.mjs.map +0 -1
- package/dist/protocol-7m-E_iFu.mjs.map +0 -1
- package/dist/runtime-platform-C-Yk9F3L.mjs.map +0 -1
- package/dist/runtime-recovery-DaRaQ8qY.mjs.map +0 -1
- package/dist/server-CsCpY0Ft.mjs.map +0 -1
- package/dist/shared--othnF1c.mjs.map +0 -1
- package/dist/stable-edge-VAAxSYSS.mjs.map +0 -1
- package/dist/startup-log-CYlFgdy5.mjs.map +0 -1
- package/dist/state-6qFcvi-I.mjs.map +0 -1
- package/dist/supervisor-CesT-H5_.mjs.map +0 -1
- package/dist/task-storage-recovery-I9lpYYX6.mjs.map +0 -1
|
@@ -5,34 +5,34 @@ globalThis.__bundlerPathsOverrides = {
|
|
|
5
5
|
'pino/file': runtimeFilePath(new URL('./pino-file.mjs', import.meta.url))
|
|
6
6
|
};
|
|
7
7
|
import { i as __toESM, r as __require, t as __commonJSMin } from "./rolldown-runtime-BH1-_iVd.mjs";
|
|
8
|
-
import { t as Server } from "./server-
|
|
9
|
-
import { C as getSchemaDescription, E as objectFromShape, O as safeParseAsync, S as getParseErrorMessage, T as normalizeObjectSchema, a as IdSchema, b as getLiteralValue, d as RuntimeDataTransport, f as SocketTransport, g as ConsumerTransport,
|
|
8
|
+
import { t as Server } from "./server-CyzfkzoZ.mjs";
|
|
9
|
+
import { C as getSchemaDescription, E as objectFromShape, O as safeParseAsync, S as getParseErrorMessage, T as normalizeObjectSchema, a as IdSchema, b as getLiteralValue, d as RuntimeDataTransport, f as SocketTransport, g as ConsumerTransport, w as isSchemaOptional, x as getObjectShape, y as toJsonSchemaCompat } from "./protocol-DlkrVyMK.mjs";
|
|
10
10
|
import { Bn as assertCompleteRequestResourceTemplate, F as ErrorCode, L as GetPromptRequestSchema, Vt as ReadResourceRequestSchema, ct as ListResourcesRequestSchema, g as CompleteRequestSchema, it as ListPromptsRequestSchema, mt as ListToolsRequestSchema, ot as ListResourceTemplatesRequestSchema, s as CallToolRequestSchema, yt as McpError, zn as assertCompleteRequestPrompt } from "./types-kNTSQOnR.mjs";
|
|
11
11
|
import { m as object$3, n as ZodOptional, o as array } from "./schemas-ZDdPV7RQ.mjs";
|
|
12
12
|
import { r as deserializeMessage } from "./stdio-20SBFdww.mjs";
|
|
13
|
-
import {
|
|
13
|
+
import { B as formatDesignFeedback, C as measureCallToolResultBytes, D as sameRuntimeProfile, F as FigmaSessionSchema, G as TEMPAD_MCP_BRIDGE_SUBPROTOCOL, H as MCP_MAX_ASSET_BYTES, K as TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS, L as ManageDesignTaskParametersSchema, M as DesignAnchorSchema, N as DesignTaskIdSchema, O as TEMPAD_MCP_ERROR_CODES, P as DesignTaskSchema, R as RESUMABLE_DESIGN_TASK_STATUSES, S as buildUploadAssetToolResult, T as MessageFromExtensionSchema, U as MCP_NODE_READ_BATCH_WORK_BUDGET_MS, W as MCP_TOOL_INLINE_BUDGET_BYTES, _ as buildApplyCanvasToolResult, a as ClientHookRequestSchema, b as buildGetScreenshotToolResult, c as GetDesignSystemResultSchema, d as UploadAssetParametersSchema, f as UploadAssetResultSchema, h as CanvasPageSnapshotSchema, i as ClientHookParamsSchema, k as AGENT_CLIENTS, l as GetScreenshotParametersSchema, m as ApplyCanvasResultSchema, o as GetCodeParametersSchema, p as ApplyCanvasParametersSchema, s as GetDesignSystemParametersSchema, t as getMcpServerConfig, u as GetStructureParametersSchema, v as buildGetCodeToolResult, w as utf8Bytes, x as buildGetStructureToolResult, y as buildGetDesignSystemToolResult, z as SetDesignAnchorParametersSchema } from "./config-Qvh73WBD.mjs";
|
|
14
14
|
import { t as require_proper_lockfile } from "./proper-lockfile-BgKrOq5D.mjs";
|
|
15
15
|
import { t as hostEnvironment } from "./process-environment-DRRIdoL8.mjs";
|
|
16
16
|
import { a as codexConversationKey, c as hostConversationKey, l as requireHostContext, n as HostContextSchema, o as codexStoreKey, r as MISSING_HOST_CONTEXT_MESSAGE, s as hostContextKey, t as HostContextNotificationSchema } from "./host-context-9TVtjsSm.mjs";
|
|
17
|
-
import { i as ClientHooks, n as HubControl } from "./hub-control-
|
|
18
|
-
import { n as bindRequestMetadata, r as clientDescriptor, t as ClientEventSchema } from "./identity-
|
|
19
|
-
import { a as LEGACY_HOOK_EXHAUSTED_RESULT, c as hookPressureCutoff, d as isExpiredHookResult, l as hookRetentionCutoff, n as ExpiredHookError, o as LegacyHookCapacityError, s as hookCutoff, t as EXPIRED_HOOK_RESULT, u as hookSignature } from "./hook-receipts-
|
|
20
|
-
import { a as HUB_RUNTIME_IDENTITY_PATH, b as resolveStateDir, c as PACKAGE_VERSION, d as SOCK_PATH, g as log, h as getRecordProperty, i as HUB_LOCK_UPDATE_MS, l as RUNTIME_DIR, m as ensureFile, n as HUB_LOCK_PATH, p as ensureDir, r as HUB_LOCK_STALE_MS, t as ASSET_DIR, u as RUNTIME_PROFILE, x as assertTrustedSocket } from "./shared
|
|
17
|
+
import { i as ClientHooks, n as HubControl } from "./hub-control-C2jNTi3G.mjs";
|
|
18
|
+
import { n as bindRequestMetadata, r as clientDescriptor, t as ClientEventSchema } from "./identity-C80lcT6j.mjs";
|
|
19
|
+
import { a as LEGACY_HOOK_EXHAUSTED_RESULT, c as hookPressureCutoff, d as isExpiredHookResult, l as hookRetentionCutoff, n as ExpiredHookError, o as LegacyHookCapacityError, s as hookCutoff, t as EXPIRED_HOOK_RESULT, u as hookSignature } from "./hook-receipts-BIUk86RJ.mjs";
|
|
20
|
+
import { a as HUB_RUNTIME_IDENTITY_PATH, b as resolveStateDir, c as PACKAGE_VERSION, d as SOCK_PATH, g as log, h as getRecordProperty, i as HUB_LOCK_UPDATE_MS, l as RUNTIME_DIR, m as ensureFile, n as HUB_LOCK_PATH, p as ensureDir, r as HUB_LOCK_STALE_MS, t as ASSET_DIR, u as RUNTIME_PROFILE, x as assertTrustedSocket } from "./shared-avqQD-kX.mjs";
|
|
21
21
|
import { n as ClientBindingSubscribeSchema, r as ClientBindingUpdateSchema } from "./client-binding-CvSSv9JC.mjs";
|
|
22
|
-
import { t as DesignTaskStore } from "./design-task-store-
|
|
22
|
+
import { t as DesignTaskStore } from "./design-task-store-BQy2SO7l.mjs";
|
|
23
23
|
import { a as removeHubRuntimeIdentityIfOwned, n as getExtensionRuntimeIssues, o as writeHubRuntimeIdentity, t as createHubRuntimeIdentity } from "./runtime-identity-D9V-g5M-.mjs";
|
|
24
|
-
import {
|
|
25
|
-
import { d as writeEndpoints, o as readEndpoints } from "./state-
|
|
26
|
-
import { n as attachRuntimeRecovery, t as RECOVERY_METHODS } from "./runtime-recovery-
|
|
24
|
+
import { F as VersionSchema, a as listenPrivate, z as compareVersions } from "./processes-BX-yLfvZ.mjs";
|
|
25
|
+
import { d as writeEndpoints, o as readEndpoints } from "./state-4Dz7r-_n.mjs";
|
|
26
|
+
import { n as attachRuntimeRecovery, t as RECOVERY_METHODS } from "./runtime-recovery-CPfCb3rY.mjs";
|
|
27
27
|
import { execFile, spawn } from "node:child_process";
|
|
28
28
|
import { connect, createServer } from "node:net";
|
|
29
29
|
import { dirname, join } from "node:path";
|
|
30
30
|
import { URL as URL$1, fileURLToPath } from "node:url";
|
|
31
|
-
import { Transform, pipeline } from "node:stream";
|
|
31
|
+
import { Readable, Transform, pipeline } from "node:stream";
|
|
32
32
|
import { createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
33
33
|
import { isDeepStrictEqual, promisify } from "node:util";
|
|
34
34
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
35
|
-
import { lstat, mkdir, opendir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
35
|
+
import { lstat, mkdir, opendir, readFile, readlink, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
36
36
|
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
37
37
|
import { createInterface } from "node:readline";
|
|
38
38
|
import { createServer as createServer$1 } from "node:http";
|
|
@@ -814,7 +814,7 @@ const EMPTY_COMPLETION_RESULT = { completion: {
|
|
|
814
814
|
values: [],
|
|
815
815
|
hasMore: false
|
|
816
816
|
} };
|
|
817
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
817
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/constants.js
|
|
818
818
|
var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
819
819
|
const BINARY_TYPES = [
|
|
820
820
|
"nodebuffer",
|
|
@@ -836,7 +836,7 @@ var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
836
836
|
NOOP: () => {}
|
|
837
837
|
};
|
|
838
838
|
}));
|
|
839
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
839
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/buffer-util.js
|
|
840
840
|
var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
841
841
|
const { websocketMask, websocketUnmask } = __require("http");
|
|
842
842
|
const { EMPTY_BUFFER } = require_constants();
|
|
@@ -944,7 +944,7 @@ var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
944
944
|
};
|
|
945
945
|
} catch (e) {}
|
|
946
946
|
}));
|
|
947
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
947
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/limiter.js
|
|
948
948
|
var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
949
949
|
const kDone = Symbol("kDone");
|
|
950
950
|
const kRun = Symbol("kRun");
|
|
@@ -994,7 +994,7 @@ var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
994
994
|
};
|
|
995
995
|
module.exports = Limiter;
|
|
996
996
|
}));
|
|
997
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
997
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/permessage-deflate.js
|
|
998
998
|
var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
999
999
|
const zlib = __require("zlib");
|
|
1000
1000
|
const bufferUtil = require_buffer_util();
|
|
@@ -1329,7 +1329,7 @@ var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module
|
|
|
1329
1329
|
this[kCallback](err);
|
|
1330
1330
|
}
|
|
1331
1331
|
}));
|
|
1332
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
1332
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/validation.js
|
|
1333
1333
|
var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
1334
1334
|
const { isUtf8 } = __require("buffer");
|
|
1335
1335
|
const { hasBlob } = require_constants();
|
|
@@ -1524,7 +1524,7 @@ var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
1524
1524
|
};
|
|
1525
1525
|
} catch (e) {}
|
|
1526
1526
|
}));
|
|
1527
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
1527
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/receiver.js
|
|
1528
1528
|
var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
1529
1529
|
const { Writable } = __require("stream");
|
|
1530
1530
|
const PerMessageDeflate = require_permessage_deflate();
|
|
@@ -1987,7 +1987,7 @@ var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
1987
1987
|
};
|
|
1988
1988
|
module.exports = Receiver;
|
|
1989
1989
|
}));
|
|
1990
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
1990
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/sender.js
|
|
1991
1991
|
var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
1992
1992
|
const { Duplex } = __require("stream");
|
|
1993
1993
|
const { randomFillSync } = __require("crypto");
|
|
@@ -2485,7 +2485,7 @@ var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
2485
2485
|
sender.onerror(err);
|
|
2486
2486
|
}
|
|
2487
2487
|
}));
|
|
2488
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
2488
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/event-target.js
|
|
2489
2489
|
var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
2490
2490
|
const { kForOnEventAttribute, kListener } = require_constants();
|
|
2491
2491
|
const kCode = Symbol("kCode");
|
|
@@ -2715,7 +2715,7 @@ var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
2715
2715
|
else listener.call(thisArg, event);
|
|
2716
2716
|
}
|
|
2717
2717
|
}));
|
|
2718
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
2718
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/extension.js
|
|
2719
2719
|
var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
2720
2720
|
const { tokenChars } = require_validation();
|
|
2721
2721
|
/**
|
|
@@ -2860,7 +2860,7 @@ var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
2860
2860
|
parse
|
|
2861
2861
|
};
|
|
2862
2862
|
}));
|
|
2863
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
2863
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/websocket.js
|
|
2864
2864
|
var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
2865
2865
|
const EventEmitter = __require("events");
|
|
2866
2866
|
const https = __require("https");
|
|
@@ -2933,12 +2933,15 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
2933
2933
|
else protocols = [options.protocols];
|
|
2934
2934
|
} else protocols = [protocols];
|
|
2935
2935
|
}
|
|
2936
|
-
initAsClient(this, address, protocols, options);
|
|
2937
|
-
} else
|
|
2938
|
-
|
|
2939
|
-
this.
|
|
2940
|
-
this.
|
|
2936
|
+
options = initAsClient(this, address, protocols, options);
|
|
2937
|
+
} else this._isServer = true;
|
|
2938
|
+
if (options.autoPong) {
|
|
2939
|
+
this._autoPong = true;
|
|
2940
|
+
this._autoPongComplete = () => autoPongComplete(this);
|
|
2941
|
+
this._pendingAutoPongs = 0;
|
|
2942
|
+
this._maxPendingAutoPongs = options.maxPendingAutoPongs | 0;
|
|
2941
2943
|
}
|
|
2944
|
+
this._closeTimeout = options.closeTimeout;
|
|
2942
2945
|
}
|
|
2943
2946
|
/**
|
|
2944
2947
|
* For historical reasons, the custom "nodebuffer" type is used by the default
|
|
@@ -3379,6 +3382,8 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
3379
3382
|
* fragments
|
|
3380
3383
|
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
|
|
3381
3384
|
* size
|
|
3385
|
+
* @param {Number} [options.maxPendingAutoPongs=60] The maximum number of
|
|
3386
|
+
* pending automatic pongs
|
|
3382
3387
|
* @param {Number} [options.maxRedirects=10] The maximum number of redirects
|
|
3383
3388
|
* allowed
|
|
3384
3389
|
* @param {String} [options.origin] Value of the `Origin` or
|
|
@@ -3389,6 +3394,7 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
3389
3394
|
* `Sec-WebSocket-Version` header
|
|
3390
3395
|
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
|
|
3391
3396
|
* not to skip UTF-8 validation for text and close messages
|
|
3397
|
+
* @return {Object} The resolved options object used for initialization
|
|
3392
3398
|
* @private
|
|
3393
3399
|
*/
|
|
3394
3400
|
function initAsClient(websocket, address, protocols, options) {
|
|
@@ -3400,6 +3406,7 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
3400
3406
|
maxBufferedChunks: 262144,
|
|
3401
3407
|
maxFragments: 16384,
|
|
3402
3408
|
maxPayload: 104857600,
|
|
3409
|
+
maxPendingAutoPongs: 60,
|
|
3403
3410
|
skipUTF8Validation: false,
|
|
3404
3411
|
perMessageDeflate: true,
|
|
3405
3412
|
followRedirects: false,
|
|
@@ -3415,8 +3422,6 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
3415
3422
|
path: void 0,
|
|
3416
3423
|
port: void 0
|
|
3417
3424
|
};
|
|
3418
|
-
websocket._autoPong = opts.autoPong;
|
|
3419
|
-
websocket._closeTimeout = opts.closeTimeout;
|
|
3420
3425
|
if (!protocolVersions.includes(opts.protocolVersion)) throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);
|
|
3421
3426
|
let parsedUrl;
|
|
3422
3427
|
if (address instanceof URL) parsedUrl = address;
|
|
@@ -3606,6 +3611,7 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
3606
3611
|
});
|
|
3607
3612
|
if (opts.finishRequest) opts.finishRequest(req, websocket);
|
|
3608
3613
|
else req.end();
|
|
3614
|
+
return opts;
|
|
3609
3615
|
}
|
|
3610
3616
|
/**
|
|
3611
3617
|
* Emit the `'error'` and `'close'` events.
|
|
@@ -3762,10 +3768,25 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
3762
3768
|
*/
|
|
3763
3769
|
function receiverOnPing(data) {
|
|
3764
3770
|
const websocket = this[kWebSocket];
|
|
3765
|
-
if (websocket._autoPong
|
|
3771
|
+
if (websocket._autoPong && websocket.readyState === WebSocket.OPEN) {
|
|
3772
|
+
if (websocket._maxPendingAutoPongs > 0 && websocket._pendingAutoPongs >= websocket._maxPendingAutoPongs) websocket.terminate();
|
|
3773
|
+
else {
|
|
3774
|
+
websocket._pendingAutoPongs++;
|
|
3775
|
+
websocket.pong(data, !this._isServer, websocket._autoPongComplete);
|
|
3776
|
+
}
|
|
3777
|
+
}
|
|
3766
3778
|
websocket.emit("ping", data);
|
|
3767
3779
|
}
|
|
3768
3780
|
/**
|
|
3781
|
+
* The callback for automatic pong responses.
|
|
3782
|
+
*
|
|
3783
|
+
* @param {WebSocket} websocket The WebSocket instance
|
|
3784
|
+
* @private
|
|
3785
|
+
*/
|
|
3786
|
+
function autoPongComplete(websocket) {
|
|
3787
|
+
websocket._pendingAutoPongs--;
|
|
3788
|
+
}
|
|
3789
|
+
/**
|
|
3769
3790
|
* The listener of the `Receiver` `'pong'` event.
|
|
3770
3791
|
*
|
|
3771
3792
|
* @param {Buffer} data The data included in the pong frame
|
|
@@ -3870,7 +3891,7 @@ var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
3870
3891
|
}
|
|
3871
3892
|
}
|
|
3872
3893
|
}));
|
|
3873
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
3894
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/stream.js
|
|
3874
3895
|
var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3875
3896
|
require_websocket();
|
|
3876
3897
|
const { Duplex } = __require("stream");
|
|
@@ -3985,7 +4006,7 @@ var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
3985
4006
|
}
|
|
3986
4007
|
module.exports = createWebSocketStream;
|
|
3987
4008
|
}));
|
|
3988
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
4009
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/subprotocol.js
|
|
3989
4010
|
var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3990
4011
|
const { tokenChars } = require_validation();
|
|
3991
4012
|
/**
|
|
@@ -4023,7 +4044,7 @@ var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
4023
4044
|
}
|
|
4024
4045
|
module.exports = { parse };
|
|
4025
4046
|
}));
|
|
4026
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
4047
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/lib/websocket-server.js
|
|
4027
4048
|
var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
4028
4049
|
const EventEmitter = __require("events");
|
|
4029
4050
|
const http = __require("http");
|
|
@@ -4068,6 +4089,8 @@ var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module)
|
|
|
4068
4089
|
* fragments
|
|
4069
4090
|
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
|
|
4070
4091
|
* size
|
|
4092
|
+
* @param {Number} [options.maxPendingAutoPongs=60] The maximum number of
|
|
4093
|
+
* pending automatic pongs
|
|
4071
4094
|
* @param {Boolean} [options.noServer=false] Enable no server mode
|
|
4072
4095
|
* @param {String} [options.path] Accept only connections matching this path
|
|
4073
4096
|
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
|
|
@@ -4090,6 +4113,7 @@ var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module)
|
|
|
4090
4113
|
maxBufferedChunks: 262144,
|
|
4091
4114
|
maxFragments: 16384,
|
|
4092
4115
|
maxPayload: 104857600,
|
|
4116
|
+
maxPendingAutoPongs: 60,
|
|
4093
4117
|
skipUTF8Validation: false,
|
|
4094
4118
|
perMessageDeflate: false,
|
|
4095
4119
|
handleProtocols: null,
|
|
@@ -4409,7 +4433,7 @@ var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module)
|
|
|
4409
4433
|
} else abortHandshake(socket, code, message, headers);
|
|
4410
4434
|
}
|
|
4411
4435
|
}));
|
|
4412
|
-
// ../../node_modules/.pnpm/ws@8.
|
|
4436
|
+
// ../../node_modules/.pnpm/ws@8.23.0/node_modules/ws/wrapper.mjs
|
|
4413
4437
|
var import_proper_lockfile = /* @__PURE__ */ __toESM(require_proper_lockfile(), 1);
|
|
4414
4438
|
require_stream();
|
|
4415
4439
|
require_extension();
|
|
@@ -4631,12 +4655,12 @@ var CodexIpc = class CodexIpc {
|
|
|
4631
4655
|
};
|
|
4632
4656
|
// src/agent-clients/codex-queue-rpc.ts
|
|
4633
4657
|
/** Use the running desktop's bundled binary, never an unrelated CLI on PATH. */
|
|
4634
|
-
async function codexQueueExecutable(context) {
|
|
4658
|
+
async function codexQueueExecutable(context, platform = process.platform) {
|
|
4635
4659
|
const options = {
|
|
4636
4660
|
timeout: 3e3,
|
|
4637
4661
|
env: hostEnvironment(context)
|
|
4638
4662
|
};
|
|
4639
|
-
const { stdout } =
|
|
4663
|
+
const { stdout } = platform === "win32" ? await promisify(execFile)("powershell.exe", [
|
|
4640
4664
|
"-NoProfile",
|
|
4641
4665
|
"-NonInteractive",
|
|
4642
4666
|
"-Command",
|
|
@@ -4645,9 +4669,17 @@ async function codexQueueExecutable(context) {
|
|
|
4645
4669
|
"-U",
|
|
4646
4670
|
String(process.getuid()),
|
|
4647
4671
|
"-o",
|
|
4648
|
-
"comm="
|
|
4672
|
+
platform === "linux" ? "pid=,comm=" : "comm="
|
|
4649
4673
|
], options);
|
|
4650
|
-
|
|
4674
|
+
let executables = stdout.split(/\r?\n/).map((path) => path.trim());
|
|
4675
|
+
if (platform === "linux") executables = await Promise.all(executables.flatMap((line) => {
|
|
4676
|
+
const match = /^(\d+)\s+codex$/.exec(line);
|
|
4677
|
+
return match ? [readlink(`/proc/${match[1]}/exe`).catch((error) => {
|
|
4678
|
+
if (error.code === "ENOENT") return "";
|
|
4679
|
+
throw error;
|
|
4680
|
+
})] : [];
|
|
4681
|
+
}));
|
|
4682
|
+
const paths = [...new Set(executables)].filter((path) => /[/\\]resources[/\\](?:codex-cli[/\\]CodexCLI\.app[/\\]Contents[/\\]MacOS[/\\])?codex(?:\.exe)?$/i.test(path));
|
|
4651
4683
|
if (paths.length !== 1) throw new Error("The running Codex desktop executable could not be identified.");
|
|
4652
4684
|
return paths[0];
|
|
4653
4685
|
}
|
|
@@ -4825,6 +4857,7 @@ async function readCodexServerQueue(conversationId, home) {
|
|
|
4825
4857
|
database.close();
|
|
4826
4858
|
}
|
|
4827
4859
|
} catch (error) {
|
|
4860
|
+
if (error.code === "ERR_UNKNOWN_BUILTIN_MODULE") throw new Error("This Codex server queue requires node:sqlite. Use Node 22.13 or later in a supported Node release line. Comments remain saved.", { cause: error });
|
|
4828
4861
|
throw new Error("The Codex server queue could not be checked. Comments remain saved.", { cause: error });
|
|
4829
4862
|
}
|
|
4830
4863
|
}
|
|
@@ -5817,6 +5850,7 @@ var CodexAppLifecycle = class {
|
|
|
5817
5850
|
}
|
|
5818
5851
|
async follow(conversationId, watch, context) {
|
|
5819
5852
|
const signal = watch.controller.signal;
|
|
5853
|
+
let retryDelay = this.retryMs;
|
|
5820
5854
|
const publish = (state) => {
|
|
5821
5855
|
if (signal.aborted) return;
|
|
5822
5856
|
const changed = JSON.stringify(watch.state) !== JSON.stringify(state);
|
|
@@ -5879,13 +5913,18 @@ var CodexAppLifecycle = class {
|
|
|
5879
5913
|
return;
|
|
5880
5914
|
}
|
|
5881
5915
|
if (message.method !== "thread-stream-state-changed") return;
|
|
5882
|
-
if (message.version !== 11)
|
|
5916
|
+
if (message.version !== 11) {
|
|
5917
|
+
retryDelay = Math.min(retryDelay * 2, 6e4);
|
|
5918
|
+
end();
|
|
5919
|
+
return;
|
|
5920
|
+
}
|
|
5883
5921
|
const change = object(params.change);
|
|
5884
5922
|
if (!Number.isSafeInteger(change.revision)) throw new Error("Invalid Codex stream revision.");
|
|
5885
5923
|
if (change.type === "snapshot") {
|
|
5886
5924
|
if (revision !== void 0 && change.revision < revision) return;
|
|
5887
5925
|
turns = new CodexTurnState(change.conversationState, conversationId);
|
|
5888
5926
|
const state = turns.state();
|
|
5927
|
+
retryDelay = this.retryMs;
|
|
5889
5928
|
clearTimeout(timer);
|
|
5890
5929
|
awaitingSnapshot = false;
|
|
5891
5930
|
revision = change.revision;
|
|
@@ -5924,7 +5963,7 @@ var CodexAppLifecycle = class {
|
|
|
5924
5963
|
connection?.close();
|
|
5925
5964
|
publish();
|
|
5926
5965
|
}
|
|
5927
|
-
if (!signal.aborted) await setTimeout$1(
|
|
5966
|
+
if (!signal.aborted) await setTimeout$1(retryDelay, void 0, { signal }).catch(() => {});
|
|
5928
5967
|
}
|
|
5929
5968
|
}
|
|
5930
5969
|
close() {
|
|
@@ -5932,19 +5971,6 @@ var CodexAppLifecycle = class {
|
|
|
5932
5971
|
this.retain(/* @__PURE__ */ new Set());
|
|
5933
5972
|
}
|
|
5934
5973
|
};
|
|
5935
|
-
// src/legacy-extension.ts
|
|
5936
|
-
function extensionUpgradeRequired() {
|
|
5937
|
-
return Object.assign(/* @__PURE__ */ new Error("This operation requires a current TemPad Dev extension compatible with this Hub. Update the extension in Chrome, then reload the Figma tab and reconnect Agent integration. Until then, get_code, get_screenshot, and node-based get_structure remain available without a design task."), { code: TEMPAD_MCP_ERROR_CODES.EXTENSION_UPGRADE_REQUIRED });
|
|
5938
|
-
}
|
|
5939
|
-
function legacyToolPayload(name, args) {
|
|
5940
|
-
const result = LegacyToolCallPayloadSchema.safeParse({
|
|
5941
|
-
name,
|
|
5942
|
-
args
|
|
5943
|
-
});
|
|
5944
|
-
if (!result.success) throw extensionUpgradeRequired();
|
|
5945
|
-
if (result.data.name === "get_code" && result.data.args?.resolveTokens) throw Object.assign(/* @__PURE__ */ new Error("resolveTokens requires matching current Hub and extension builds. Update the extension, then reload the Figma tab and reconnect Agent integration. Older extensions flatten token definitions and cannot return consumer-aware code with preserved aliases."), { code: TEMPAD_MCP_ERROR_CODES.EXTENSION_UPGRADE_REQUIRED });
|
|
5946
|
-
return result.data;
|
|
5947
|
-
}
|
|
5948
5974
|
// src/design-tasks.ts
|
|
5949
5975
|
const ENDED_STATUSES = ["completed", "cancelled"];
|
|
5950
5976
|
const RUNNING_STATUSES = ["active", "stopping"];
|
|
@@ -5952,6 +5978,13 @@ const RUNNING_STATUSES = ["active", "stopping"];
|
|
|
5952
5978
|
function getVerifiedTaskClient(record) {
|
|
5953
5979
|
return record.requestId ? record.task.client : void 0;
|
|
5954
5980
|
}
|
|
5981
|
+
/** A public session ID alone cannot prove that the original edge survived a Hub switch. */
|
|
5982
|
+
function managedEdgeOwner(sessionId, token) {
|
|
5983
|
+
return `edge:${createHash("sha256").update(`${sessionId}/${token}`).digest("hex")}`;
|
|
5984
|
+
}
|
|
5985
|
+
function isGenericEdge(ownerId, client) {
|
|
5986
|
+
return ownerId.startsWith("edge:") && client?.kind === "other" && !client.sessionId;
|
|
5987
|
+
}
|
|
5955
5988
|
function fail(code, message) {
|
|
5956
5989
|
throw Object.assign(new Error(message), { code });
|
|
5957
5990
|
}
|
|
@@ -5959,7 +5992,6 @@ function resolveDesignTarget(tasks, extensions, activeExtensionId, ownerId, task
|
|
|
5959
5992
|
const record = taskId ? tasks.owned(taskId, ownerId, active) : void 0;
|
|
5960
5993
|
if (record && explicitSessionId && explicitSessionId !== record.task.target.sessionId) fail("DESIGN_TARGET_CHANGED", "The requested Figma session does not match this task.");
|
|
5961
5994
|
const extension = extensions.find((value) => explicitSessionId && !record ? value.sessions?.sessions.some((session) => session.sessionId === explicitSessionId) : value.id === (record?.extensionId ?? activeExtensionId)) ?? (!active && record ? extensions.find((value) => value.sessions?.sessions.some((session) => session.sessionId === record.task.target.sessionId && session.fileKey === record.task.target.fileKey)) : void 0);
|
|
5962
|
-
if (extension?.legacy) throw extensionUpgradeRequired();
|
|
5963
5995
|
const sessionId = explicitSessionId ?? record?.task.target.sessionId ?? extension?.sessions?.activeSessionId;
|
|
5964
5996
|
const session = extension?.sessions?.sessions.find((value) => value.sessionId === sessionId);
|
|
5965
5997
|
if (!extension || !session) fail("NO_ACTIVE_EXTENSION", record ? "The bound Figma session is unavailable. Begin a new task after reconnecting; no other tab was selected." : explicitSessionId ? `Figma session ${explicitSessionId} is unavailable. Call list_design_sessions for a current sessionId.` : "No active Figma session. Activate the intended file with its TemPad Dev MCP badge.");
|
|
@@ -6020,6 +6052,7 @@ var DesignTasks = class {
|
|
|
6020
6052
|
const { busy: _busy, tabId, documentId, ...target } = session;
|
|
6021
6053
|
const record = {
|
|
6022
6054
|
ownerId,
|
|
6055
|
+
...isGenericEdge(ownerId, client) ? { edgeOwner: ownerId } : {},
|
|
6023
6056
|
extensionId,
|
|
6024
6057
|
requestId,
|
|
6025
6058
|
ready: false,
|
|
@@ -6073,11 +6106,13 @@ var DesignTasks = class {
|
|
|
6073
6106
|
if (active && record.task.status !== "active") fail("DESIGN_TASK_INACTIVE", `Design task is ${record.task.status}. ${record.task.status === "cancelled" ? "Begin a new task with a fresh requestId before writing." : "Use manage_design_task with action \"resume\" and reread the target before writing; do not replay an old write."}`);
|
|
6074
6107
|
return record;
|
|
6075
6108
|
}
|
|
6076
|
-
/**
|
|
6109
|
+
/** Reconnect an exact native conversation or its original transport-only edge. */
|
|
6077
6110
|
attachClient(ownerId, client, capabilities, hostContext) {
|
|
6078
6111
|
const mismatched = [];
|
|
6079
|
-
|
|
6112
|
+
const transport = !client.sessionId || ["other", "unknown"].includes(client.kind);
|
|
6113
|
+
if (transport && !isGenericEdge(ownerId, client)) return mismatched;
|
|
6080
6114
|
for (const record of this.records.values()) {
|
|
6115
|
+
if (transport && record.edgeOwner !== ownerId) continue;
|
|
6081
6116
|
const verified = getVerifiedTaskClient(record);
|
|
6082
6117
|
if (verified?.kind !== client.kind || verified.sessionId !== client.sessionId) continue;
|
|
6083
6118
|
if (RUNNING_STATUSES.includes(record.task.status) && record.ownerId !== ownerId) continue;
|
|
@@ -6641,13 +6676,14 @@ var DesignTasks = class {
|
|
|
6641
6676
|
...this.filesNeedingRead.size ? { filesNeedingRead: [...this.filesNeedingRead.keys()] } : {},
|
|
6642
6677
|
current: Object.fromEntries(this.currentTaskIds),
|
|
6643
6678
|
...this.fileFences.size ? { fileFences: Object.fromEntries(this.fileFences) } : {},
|
|
6644
|
-
records: [...this.records.values()].map(({ task, requestId, browser, resultNodeIds, retiredAt, hostContext, claudeStopNotice }) => ({
|
|
6679
|
+
records: [...this.records.values()].map(({ task, requestId, edgeOwner, browser, resultNodeIds, retiredAt, hostContext, claudeStopNotice }) => ({
|
|
6645
6680
|
task: {
|
|
6646
6681
|
...task,
|
|
6647
6682
|
capabilities: void 0,
|
|
6648
6683
|
operation: null
|
|
6649
6684
|
},
|
|
6650
6685
|
requestId,
|
|
6686
|
+
edgeOwner,
|
|
6651
6687
|
browser,
|
|
6652
6688
|
resultNodeIds,
|
|
6653
6689
|
retiredAt,
|
|
@@ -6831,6 +6867,7 @@ var AgentClients = class {
|
|
|
6831
6867
|
this.pendingClaudeBindings.delete(connectionId);
|
|
6832
6868
|
this.publishBinding(connectionId, next);
|
|
6833
6869
|
this.bindings.set(ownerId, next);
|
|
6870
|
+
delete record.edgeOwner;
|
|
6834
6871
|
record.ownerId = ownerId;
|
|
6835
6872
|
record.task.client = next.client;
|
|
6836
6873
|
this.tasks.attachClient(ownerId, next.client, { ...record.task.capabilities ?? CANVAS_ONLY }, next.hostContext);
|
|
@@ -6896,6 +6933,7 @@ var AgentClients = class {
|
|
|
6896
6933
|
const previous = this.bindings.get(ownerId);
|
|
6897
6934
|
if (previous?.client.kind === binding.client.kind) binding.turnId ??= previous.turnId;
|
|
6898
6935
|
this.bindings.set(ownerId, binding);
|
|
6936
|
+
if (previous?.client.kind === binding.client.kind && !binding.client.sessionId) return ownerId;
|
|
6899
6937
|
const mismatchedTasks = this.tasks.attachClient(ownerId, binding.client, void 0, binding.hostContext);
|
|
6900
6938
|
if (mismatchedTasks.length) log.warn({
|
|
6901
6939
|
ownerId,
|
|
@@ -7168,24 +7206,6 @@ var AgentClients = class {
|
|
|
7168
7206
|
}
|
|
7169
7207
|
}
|
|
7170
7208
|
};
|
|
7171
|
-
// src/asset-data-url.ts
|
|
7172
|
-
const IMAGE_DATA_URL_PATTERN = /^data:(image\/(?:png|jpeg|gif));base64,([A-Za-z0-9+/]+={0,2})$/;
|
|
7173
|
-
function decodeImageDataUrl(dataUrl, maxBytes = MCP_MAX_ASSET_BYTES) {
|
|
7174
|
-
const match = IMAGE_DATA_URL_PATTERN.exec(dataUrl);
|
|
7175
|
-
if (!match) throw new Error("Expected a base64 PNG, JPEG, or GIF data URL.");
|
|
7176
|
-
const mimeType = match[1];
|
|
7177
|
-
const encoded = match[2];
|
|
7178
|
-
if (encoded.length % 4 !== 0) throw new Error("Image data URL contains invalid base64 padding.");
|
|
7179
|
-
const bytes = Buffer.from(encoded, "base64");
|
|
7180
|
-
if (!bytes.length) throw new Error("Generated image is empty.");
|
|
7181
|
-
if (bytes.length > maxBytes) throw new Error(`Generated image exceeds the ${maxBytes}-byte asset limit.`);
|
|
7182
|
-
if (bytes.toString("base64") !== encoded) throw new Error("Image data URL contains invalid base64 data.");
|
|
7183
|
-
return {
|
|
7184
|
-
bytes,
|
|
7185
|
-
hash: createHash("sha256").update(bytes).digest("hex"),
|
|
7186
|
-
mimeType
|
|
7187
|
-
};
|
|
7188
|
-
}
|
|
7189
7209
|
// ../../node_modules/.pnpm/nanoid@6.0.2/node_modules/nanoid/url-alphabet/index.js
|
|
7190
7210
|
let urlAlphabet = "57X6y3wQZNzYjJB2L_10pxbackgroundhimselfUTF-8DEMOGRAPHICSVqvt4KW9";
|
|
7191
7211
|
// ../../node_modules/.pnpm/nanoid@6.0.2/node_modules/nanoid/index.js
|
|
@@ -7281,6 +7301,24 @@ function customAlphabet(alphabet, defaultSize = 21) {
|
|
|
7281
7301
|
};
|
|
7282
7302
|
}
|
|
7283
7303
|
const nanoid = customAlphabet(urlAlphabet);
|
|
7304
|
+
// src/asset-data-url.ts
|
|
7305
|
+
const IMAGE_DATA_URL_PATTERN = /^data:(image\/(?:png|jpeg|gif));base64,([A-Za-z0-9+/]+={0,2})$/;
|
|
7306
|
+
function decodeImageDataUrl(dataUrl, maxBytes = MCP_MAX_ASSET_BYTES) {
|
|
7307
|
+
const match = IMAGE_DATA_URL_PATTERN.exec(dataUrl);
|
|
7308
|
+
if (!match) throw new Error("Expected a base64 PNG, JPEG, or GIF data URL.");
|
|
7309
|
+
const mimeType = match[1];
|
|
7310
|
+
const encoded = match[2];
|
|
7311
|
+
if (encoded.length % 4 !== 0) throw new Error("Image data URL contains invalid base64 padding.");
|
|
7312
|
+
const bytes = Buffer.from(encoded, "base64");
|
|
7313
|
+
if (!bytes.length) throw new Error("Generated image is empty.");
|
|
7314
|
+
if (bytes.length > maxBytes) throw new Error(`Generated image exceeds the ${maxBytes}-byte asset limit.`);
|
|
7315
|
+
if (bytes.toString("base64") !== encoded) throw new Error("Image data URL contains invalid base64 data.");
|
|
7316
|
+
return {
|
|
7317
|
+
bytes,
|
|
7318
|
+
hash: createHash("sha256").update(bytes).digest("hex"),
|
|
7319
|
+
mimeType
|
|
7320
|
+
};
|
|
7321
|
+
}
|
|
7284
7322
|
// src/asset-utils.ts
|
|
7285
7323
|
const HASH_FILENAME_PATTERN = new RegExp(`^([a-f0-9]{64}|[a-f0-9]{8})(?:\\.[a-z0-9-]+)?$`);
|
|
7286
7324
|
const SAFE_IMAGE_EXTENSION_PATTERN = /^[a-z0-9-]+$/;
|
|
@@ -7306,6 +7344,207 @@ function buildAssetFilename(hash, mimeType) {
|
|
|
7306
7344
|
function getHashFromAssetFilename(filename) {
|
|
7307
7345
|
return HASH_FILENAME_PATTERN.exec(filename)?.[1] ?? null;
|
|
7308
7346
|
}
|
|
7347
|
+
// src/asset-store.ts
|
|
7348
|
+
const INDEX_FILENAME = "assets.json";
|
|
7349
|
+
const DEFAULT_INDEX_PATH = join(ASSET_DIR, INDEX_FILENAME);
|
|
7350
|
+
const IMAGE_MIME_TYPES = {
|
|
7351
|
+
png: "image/png",
|
|
7352
|
+
jpg: "image/jpeg",
|
|
7353
|
+
jpeg: "image/jpeg",
|
|
7354
|
+
svg: "image/svg+xml",
|
|
7355
|
+
gif: "image/gif",
|
|
7356
|
+
webp: "image/webp",
|
|
7357
|
+
avif: "image/avif"
|
|
7358
|
+
};
|
|
7359
|
+
function pruneExpiredAssets(store, ttlMs, pressure) {
|
|
7360
|
+
const now = Date.now();
|
|
7361
|
+
let checked = 0;
|
|
7362
|
+
let removed = 0;
|
|
7363
|
+
let reclaimed = 0;
|
|
7364
|
+
for (const record of store.list()) {
|
|
7365
|
+
checked++;
|
|
7366
|
+
const lastAccess = Number.isFinite(record.lastAccess) ? record.lastAccess : record.uploadedAt;
|
|
7367
|
+
if (record.hash !== pressure?.preserveHash && lastAccess && now - lastAccess > ttlMs) {
|
|
7368
|
+
store.remove(record.hash);
|
|
7369
|
+
if (!store.has(record.hash)) {
|
|
7370
|
+
removed++;
|
|
7371
|
+
if (Number.isFinite(record.size) && record.size > 0) reclaimed += record.size;
|
|
7372
|
+
if (pressure && reclaimed >= pressure.bytesNeeded) break;
|
|
7373
|
+
}
|
|
7374
|
+
}
|
|
7375
|
+
}
|
|
7376
|
+
return {
|
|
7377
|
+
checked,
|
|
7378
|
+
removed
|
|
7379
|
+
};
|
|
7380
|
+
}
|
|
7381
|
+
function readIndex(indexPath) {
|
|
7382
|
+
if (!existsSync(indexPath)) return [];
|
|
7383
|
+
try {
|
|
7384
|
+
const raw = readFileSync(indexPath, "utf8").trim();
|
|
7385
|
+
if (!raw) return [];
|
|
7386
|
+
const parsed = JSON.parse(raw);
|
|
7387
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
7388
|
+
} catch (error) {
|
|
7389
|
+
log.warn({
|
|
7390
|
+
error,
|
|
7391
|
+
indexPath
|
|
7392
|
+
}, "Failed to read asset catalog; starting fresh.");
|
|
7393
|
+
return [];
|
|
7394
|
+
}
|
|
7395
|
+
}
|
|
7396
|
+
function writeIndex(indexPath, values) {
|
|
7397
|
+
const payload = JSON.stringify(values, null, 2);
|
|
7398
|
+
const temporary = `${indexPath}.tmp.${process.pid}`;
|
|
7399
|
+
writeFileSync(temporary, payload, {
|
|
7400
|
+
encoding: "utf8",
|
|
7401
|
+
mode: 384
|
|
7402
|
+
});
|
|
7403
|
+
renameSync(temporary, indexPath);
|
|
7404
|
+
}
|
|
7405
|
+
function createAssetStore(options = {}) {
|
|
7406
|
+
ensureDir(ASSET_DIR);
|
|
7407
|
+
const indexPath = options.indexPath ?? DEFAULT_INDEX_PATH;
|
|
7408
|
+
ensureFile(indexPath);
|
|
7409
|
+
const records = /* @__PURE__ */ new Map();
|
|
7410
|
+
let persistTimer = null;
|
|
7411
|
+
function loadExisting() {
|
|
7412
|
+
const list = readIndex(indexPath);
|
|
7413
|
+
for (const record of list) if (record?.hash && record?.filePath) records.set(record.hash, record);
|
|
7414
|
+
}
|
|
7415
|
+
function persist() {
|
|
7416
|
+
if (persistTimer) return;
|
|
7417
|
+
persistTimer = setTimeout(() => {
|
|
7418
|
+
persistTimer = null;
|
|
7419
|
+
try {
|
|
7420
|
+
writeIndex(indexPath, [...records.values()]);
|
|
7421
|
+
} catch (error) {
|
|
7422
|
+
log.warn({
|
|
7423
|
+
error,
|
|
7424
|
+
indexPath
|
|
7425
|
+
}, "Could not persist asset catalog; retrying.");
|
|
7426
|
+
persist();
|
|
7427
|
+
}
|
|
7428
|
+
}, 5e3);
|
|
7429
|
+
if (typeof persistTimer.unref === "function") persistTimer.unref();
|
|
7430
|
+
}
|
|
7431
|
+
function flush() {
|
|
7432
|
+
if (persistTimer) {
|
|
7433
|
+
clearTimeout(persistTimer);
|
|
7434
|
+
persistTimer = null;
|
|
7435
|
+
}
|
|
7436
|
+
writeIndex(indexPath, [...records.values()]);
|
|
7437
|
+
}
|
|
7438
|
+
function list() {
|
|
7439
|
+
return [...records.values()];
|
|
7440
|
+
}
|
|
7441
|
+
function has(hash) {
|
|
7442
|
+
return records.has(hash);
|
|
7443
|
+
}
|
|
7444
|
+
function get(hash) {
|
|
7445
|
+
return records.get(hash);
|
|
7446
|
+
}
|
|
7447
|
+
function upsert(input) {
|
|
7448
|
+
const now = Date.now();
|
|
7449
|
+
const record = {
|
|
7450
|
+
...input,
|
|
7451
|
+
uploadedAt: input.uploadedAt ?? now,
|
|
7452
|
+
lastAccess: input.lastAccess ?? now
|
|
7453
|
+
};
|
|
7454
|
+
records.set(record.hash, record);
|
|
7455
|
+
persist();
|
|
7456
|
+
return record;
|
|
7457
|
+
}
|
|
7458
|
+
function touch(hash) {
|
|
7459
|
+
const existing = records.get(hash);
|
|
7460
|
+
if (!existing) return void 0;
|
|
7461
|
+
existing.lastAccess = Date.now();
|
|
7462
|
+
persist();
|
|
7463
|
+
return existing;
|
|
7464
|
+
}
|
|
7465
|
+
function remove(hash, { removeFile = true } = {}) {
|
|
7466
|
+
const record = records.get(hash);
|
|
7467
|
+
if (!record) return;
|
|
7468
|
+
if (removeFile) try {
|
|
7469
|
+
rmSync(record.filePath, { force: true });
|
|
7470
|
+
} catch (error) {
|
|
7471
|
+
log.warn({
|
|
7472
|
+
hash,
|
|
7473
|
+
error
|
|
7474
|
+
}, "Failed to remove asset file on delete.");
|
|
7475
|
+
return;
|
|
7476
|
+
}
|
|
7477
|
+
records.delete(hash);
|
|
7478
|
+
persist();
|
|
7479
|
+
}
|
|
7480
|
+
function reconcile() {
|
|
7481
|
+
let changed = false;
|
|
7482
|
+
for (const [hash, record] of records) if (!existsSync(record.filePath)) {
|
|
7483
|
+
records.delete(hash);
|
|
7484
|
+
changed = true;
|
|
7485
|
+
}
|
|
7486
|
+
try {
|
|
7487
|
+
const files = readdirSync(ASSET_DIR);
|
|
7488
|
+
const now = Date.now();
|
|
7489
|
+
for (const file of files) {
|
|
7490
|
+
if (file === INDEX_FILENAME) continue;
|
|
7491
|
+
if (file.includes(".tmp.")) {
|
|
7492
|
+
try {
|
|
7493
|
+
const filePath = join(ASSET_DIR, file);
|
|
7494
|
+
if (now - statSync(filePath).mtimeMs > 36e5) {
|
|
7495
|
+
rmSync(filePath, { force: true });
|
|
7496
|
+
log.info({ file }, "Cleaned up stale temp file.");
|
|
7497
|
+
}
|
|
7498
|
+
} catch (e) {
|
|
7499
|
+
log.debug({
|
|
7500
|
+
error: e,
|
|
7501
|
+
file
|
|
7502
|
+
}, "Failed to cleanup stale temp file.");
|
|
7503
|
+
}
|
|
7504
|
+
continue;
|
|
7505
|
+
}
|
|
7506
|
+
const hash = getHashFromAssetFilename(file);
|
|
7507
|
+
if (!hash) continue;
|
|
7508
|
+
if (!records.has(hash)) {
|
|
7509
|
+
const filePath = join(ASSET_DIR, file);
|
|
7510
|
+
try {
|
|
7511
|
+
const stat = statSync(filePath);
|
|
7512
|
+
records.set(hash, {
|
|
7513
|
+
hash,
|
|
7514
|
+
filePath,
|
|
7515
|
+
mimeType: IMAGE_MIME_TYPES[file.split(".").at(-1) ?? ""] ?? "application/octet-stream",
|
|
7516
|
+
size: stat.size,
|
|
7517
|
+
uploadedAt: stat.birthtimeMs,
|
|
7518
|
+
lastAccess: stat.atimeMs
|
|
7519
|
+
});
|
|
7520
|
+
changed = true;
|
|
7521
|
+
log.info({ hash }, "Recovered orphan asset file.");
|
|
7522
|
+
} catch (e) {
|
|
7523
|
+
log.warn({
|
|
7524
|
+
error: e,
|
|
7525
|
+
file
|
|
7526
|
+
}, "Failed to stat orphan file.");
|
|
7527
|
+
}
|
|
7528
|
+
}
|
|
7529
|
+
}
|
|
7530
|
+
} catch (error) {
|
|
7531
|
+
log.warn({ error }, "Failed to scan asset directory for orphans.");
|
|
7532
|
+
}
|
|
7533
|
+
if (changed) flush();
|
|
7534
|
+
}
|
|
7535
|
+
loadExisting();
|
|
7536
|
+
reconcile();
|
|
7537
|
+
return {
|
|
7538
|
+
list,
|
|
7539
|
+
has,
|
|
7540
|
+
get,
|
|
7541
|
+
upsert,
|
|
7542
|
+
touch,
|
|
7543
|
+
remove,
|
|
7544
|
+
reconcile,
|
|
7545
|
+
flush
|
|
7546
|
+
};
|
|
7547
|
+
}
|
|
7309
7548
|
// src/security.ts
|
|
7310
7549
|
const CHROME_EXTENSION_ORIGIN_PATTERN = /^chrome-extension:\/\/[a-p]{32}$/;
|
|
7311
7550
|
function createCapabilityToken() {
|
|
@@ -7357,7 +7596,6 @@ const ASSET_MAX_CONCURRENT_DOWNLOADS = 128;
|
|
|
7357
7596
|
function createAssetHttpServer(store, options = {}) {
|
|
7358
7597
|
const config = getMcpServerConfig();
|
|
7359
7598
|
const accessToken = options.accessToken ?? createCapabilityToken();
|
|
7360
|
-
const legacyAccessToken = options.legacyAccessToken ?? createCapabilityToken();
|
|
7361
7599
|
const maxAssetSizeBytes = options.maxAssetSizeBytes ?? config.maxAssetSizeBytes;
|
|
7362
7600
|
const maxAssetStoreBytes = options.maxAssetStoreBytes ?? config.maxAssetStoreBytes;
|
|
7363
7601
|
const maxConcurrentUploads = options.maxConcurrentUploads ?? config.maxConcurrentAssetUploads;
|
|
@@ -7398,9 +7636,9 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
7398
7636
|
server.close();
|
|
7399
7637
|
port = null;
|
|
7400
7638
|
}
|
|
7401
|
-
function getBaseUrl(
|
|
7639
|
+
function getBaseUrl() {
|
|
7402
7640
|
if (port === null) throw new Error("Asset HTTP server is not running.");
|
|
7403
|
-
return `http://${LOOPBACK_HOST}:${port}/${
|
|
7641
|
+
return `http://${LOOPBACK_HOST}:${port}/${accessToken}`;
|
|
7404
7642
|
}
|
|
7405
7643
|
function handleRequest(req, res) {
|
|
7406
7644
|
const startedAt = Date.now();
|
|
@@ -7434,8 +7672,7 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
7434
7672
|
return;
|
|
7435
7673
|
}
|
|
7436
7674
|
const segments = url.pathname.split("/").filter(Boolean);
|
|
7437
|
-
|
|
7438
|
-
if (segments.length !== 3 || !legacy && !secretsEqual(segments[0] ?? "", accessToken) || segments[1] !== "assets") {
|
|
7675
|
+
if (segments.length !== 3 || !secretsEqual(segments[0] ?? "", accessToken) || segments[1] !== "assets") {
|
|
7439
7676
|
sendError(res, 404, "Not Found");
|
|
7440
7677
|
return;
|
|
7441
7678
|
}
|
|
@@ -7466,7 +7703,7 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
7466
7703
|
return;
|
|
7467
7704
|
}
|
|
7468
7705
|
if (req.method === "POST") {
|
|
7469
|
-
if (
|
|
7706
|
+
if (hash.length !== 64) {
|
|
7470
7707
|
sendError(res, 400, "Legacy Asset Hashes Are Read-Only");
|
|
7471
7708
|
return;
|
|
7472
7709
|
}
|
|
@@ -7549,8 +7786,6 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
7549
7786
|
return;
|
|
7550
7787
|
}
|
|
7551
7788
|
const mimeType = normalizeMimeType(getHeader(req, "content-type"));
|
|
7552
|
-
const filename = buildAssetFilename(hash, mimeType);
|
|
7553
|
-
const filePath = join(ASSET_DIR, filename);
|
|
7554
7789
|
const width = parseInt(getHeader(req, "x-asset-width") ?? "", 10);
|
|
7555
7790
|
const height = parseInt(getHeader(req, "x-asset-height") ?? "", 10);
|
|
7556
7791
|
const themeable = getHeader(req, "x-asset-themeable") === "true";
|
|
@@ -7558,7 +7793,41 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
7558
7793
|
if (Number.isFinite(width) && width > 0) metadata.width = width;
|
|
7559
7794
|
if (Number.isFinite(height) && height > 0) metadata.height = height;
|
|
7560
7795
|
if (themeable) metadata.themeable = true;
|
|
7561
|
-
|
|
7796
|
+
upload(req, {
|
|
7797
|
+
hash,
|
|
7798
|
+
mimeType,
|
|
7799
|
+
declaredSize,
|
|
7800
|
+
assetMetadata: Object.keys(metadata).length ? metadata : void 0
|
|
7801
|
+
}, (status, payload) => {
|
|
7802
|
+
if (status === 429) res.setHeader("Connection", "close");
|
|
7803
|
+
if (status !== 500 || !res.headersSent) sendJson(res, status, payload);
|
|
7804
|
+
});
|
|
7805
|
+
}
|
|
7806
|
+
async function importImage(dataUrl, signal) {
|
|
7807
|
+
signal.throwIfAborted();
|
|
7808
|
+
if (options.admit && !options.admit()) throw new Error("Runtime recovery is in progress; request was not admitted.");
|
|
7809
|
+
const { hash, mimeType, bytes } = decodeImageDataUrl(dataUrl, maxAssetSizeBytes);
|
|
7810
|
+
const stream = Readable.from([bytes]);
|
|
7811
|
+
await new Promise((resolve, reject) => {
|
|
7812
|
+
upload(stream, {
|
|
7813
|
+
hash,
|
|
7814
|
+
mimeType,
|
|
7815
|
+
declaredSize: bytes.length,
|
|
7816
|
+
localImport: signal
|
|
7817
|
+
}, (status, payload) => {
|
|
7818
|
+
if (status < 300) resolve();
|
|
7819
|
+
else reject(/* @__PURE__ */ new Error(`Hub asset import failed (${status}): ${JSON.stringify(payload)}`));
|
|
7820
|
+
});
|
|
7821
|
+
});
|
|
7822
|
+
signal.throwIfAborted();
|
|
7823
|
+
return {
|
|
7824
|
+
assetHash: hash,
|
|
7825
|
+
mimeType,
|
|
7826
|
+
size: bytes.length
|
|
7827
|
+
};
|
|
7828
|
+
}
|
|
7829
|
+
function upload(stream, { hash, mimeType, declaredSize, assetMetadata, localImport }, reply) {
|
|
7830
|
+
const filePath = join(ASSET_DIR, buildAssetFilename(hash, mimeType));
|
|
7562
7831
|
const reuseExisting = (record) => {
|
|
7563
7832
|
if (assetMetadata) record.metadata = {
|
|
7564
7833
|
...record.metadata,
|
|
@@ -7567,36 +7836,54 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
7567
7836
|
if (record.mimeType !== mimeType) record.mimeType = mimeType;
|
|
7568
7837
|
record.lastAccess = Date.now();
|
|
7569
7838
|
store.upsert(record);
|
|
7570
|
-
|
|
7839
|
+
reply(200, { message: "Asset Already Exists" });
|
|
7571
7840
|
};
|
|
7572
7841
|
const existing = store.get(hash);
|
|
7573
|
-
if (existing
|
|
7842
|
+
if (existing) {
|
|
7574
7843
|
let existingPath = existing.filePath;
|
|
7575
7844
|
if (!existsSync(existingPath) && existsSync(filePath)) {
|
|
7576
7845
|
existing.filePath = filePath;
|
|
7577
7846
|
existingPath = filePath;
|
|
7578
7847
|
}
|
|
7579
7848
|
if (existsSync(existingPath)) {
|
|
7580
|
-
|
|
7849
|
+
stream.resume();
|
|
7581
7850
|
reuseExisting(existing);
|
|
7582
7851
|
return;
|
|
7583
7852
|
}
|
|
7584
7853
|
}
|
|
7585
7854
|
if (activeUploads >= maxConcurrentUploads) {
|
|
7586
|
-
|
|
7587
|
-
|
|
7588
|
-
sendError(res, 429, "Too Many Concurrent Uploads");
|
|
7855
|
+
stream.resume();
|
|
7856
|
+
reply(429, { error: "Too Many Concurrent Uploads" });
|
|
7589
7857
|
return;
|
|
7590
7858
|
}
|
|
7591
7859
|
const reservationBytes = declaredSize ?? maxAssetSizeBytes;
|
|
7592
|
-
|
|
7593
|
-
|
|
7594
|
-
|
|
7860
|
+
const quota = (incomingBytes) => {
|
|
7861
|
+
const available = maxAssetStoreBytes - reservedUploadBytes - incomingBytes;
|
|
7862
|
+
let storedBytes = getStoredAssetBytes(store, hash);
|
|
7863
|
+
if (storedBytes > available && available >= 0 && config.assetTtlMs > 0) {
|
|
7864
|
+
const pressure = {
|
|
7865
|
+
preserveHash: hash,
|
|
7866
|
+
bytesNeeded: storedBytes - available
|
|
7867
|
+
};
|
|
7868
|
+
if (pruneExpiredAssets(store, config.assetTtlMs, pressure).removed) storedBytes = getStoredAssetBytes(store, hash);
|
|
7869
|
+
}
|
|
7870
|
+
return storedBytes > available ? {
|
|
7871
|
+
error: "Asset Store Quota Exceeded",
|
|
7872
|
+
storedBytes,
|
|
7873
|
+
reservedBytes: reservedUploadBytes,
|
|
7874
|
+
incomingBytes,
|
|
7875
|
+
limitBytes: maxAssetStoreBytes
|
|
7876
|
+
} : void 0;
|
|
7877
|
+
};
|
|
7878
|
+
const denied = quota(reservationBytes);
|
|
7879
|
+
if (denied) {
|
|
7880
|
+
stream.resume();
|
|
7881
|
+
reply(507, denied);
|
|
7595
7882
|
return;
|
|
7596
7883
|
}
|
|
7597
7884
|
const tmpPath = `${filePath}.tmp.${nanoid()}`;
|
|
7598
7885
|
const writeStream = createWriteStream(tmpPath);
|
|
7599
|
-
const hasher = createHash("sha256");
|
|
7886
|
+
const hasher = localImport ? void 0 : createHash("sha256");
|
|
7600
7887
|
let size = 0;
|
|
7601
7888
|
activeUploads += 1;
|
|
7602
7889
|
options.onActivity?.();
|
|
@@ -7617,62 +7904,52 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
7617
7904
|
callback(/* @__PURE__ */ new Error("PayloadTooLarge"));
|
|
7618
7905
|
return;
|
|
7619
7906
|
}
|
|
7620
|
-
hasher
|
|
7907
|
+
hasher?.update(chunk);
|
|
7621
7908
|
callback(null, chunk);
|
|
7622
7909
|
} });
|
|
7623
|
-
|
|
7910
|
+
const abort = () => stream.destroy();
|
|
7911
|
+
localImport?.addEventListener("abort", abort, { once: true });
|
|
7912
|
+
pipeline(stream, monitor, writeStream, (err) => {
|
|
7913
|
+
localImport?.removeEventListener("abort", abort);
|
|
7624
7914
|
activeUploads -= 1;
|
|
7625
7915
|
options.onActivity?.();
|
|
7626
7916
|
reservedUploadBytes -= reservationBytes;
|
|
7627
7917
|
if (err) {
|
|
7628
7918
|
cleanup();
|
|
7629
|
-
if (err.message === "PayloadTooLarge")
|
|
7919
|
+
if (err.message === "PayloadTooLarge") reply(413, { error: "Payload Too Large" });
|
|
7630
7920
|
else if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
|
7631
7921
|
log.warn({ hash }, "Upload request closed prematurely.");
|
|
7632
|
-
|
|
7922
|
+
reply(400, { error: "Upload Incomplete" });
|
|
7633
7923
|
} else {
|
|
7634
7924
|
log.error({
|
|
7635
7925
|
error: err,
|
|
7636
7926
|
hash
|
|
7637
7927
|
}, "Upload pipeline failed.");
|
|
7638
|
-
|
|
7928
|
+
reply(500, { error: "Internal Server Error" });
|
|
7639
7929
|
}
|
|
7640
7930
|
return;
|
|
7641
7931
|
}
|
|
7642
|
-
|
|
7643
|
-
|
|
7932
|
+
if (localImport?.aborted) {
|
|
7933
|
+
cleanup();
|
|
7934
|
+
reply(400, { error: "Upload Incomplete" });
|
|
7935
|
+
return;
|
|
7936
|
+
}
|
|
7937
|
+
if (hasher && hasher.digest("hex") !== hash) {
|
|
7644
7938
|
cleanup();
|
|
7645
|
-
|
|
7939
|
+
reply(400, { error: "Hash Mismatch" });
|
|
7646
7940
|
return;
|
|
7647
7941
|
}
|
|
7648
|
-
|
|
7942
|
+
const denied = quota(size);
|
|
7943
|
+
if (denied) {
|
|
7649
7944
|
cleanup();
|
|
7650
|
-
|
|
7945
|
+
reply(507, denied);
|
|
7651
7946
|
return;
|
|
7652
7947
|
}
|
|
7653
7948
|
try {
|
|
7654
7949
|
const previous = store.get(hash);
|
|
7655
7950
|
if (previous && existsSync(previous.filePath)) {
|
|
7656
|
-
if (hash.length === 64) {
|
|
7657
|
-
cleanup();
|
|
7658
|
-
reuseExisting(previous);
|
|
7659
|
-
return;
|
|
7660
|
-
}
|
|
7661
|
-
const previousHash = createHash("sha256").update(readFileSync(previous.filePath)).digest("hex");
|
|
7662
7951
|
cleanup();
|
|
7663
|
-
|
|
7664
|
-
sendError(res, 409, "Legacy Asset Hash Collision; update the TemPad Dev extension");
|
|
7665
|
-
return;
|
|
7666
|
-
}
|
|
7667
|
-
store.upsert({
|
|
7668
|
-
...previous,
|
|
7669
|
-
metadata: {
|
|
7670
|
-
...previous.metadata,
|
|
7671
|
-
...assetMetadata
|
|
7672
|
-
},
|
|
7673
|
-
lastAccess: Date.now()
|
|
7674
|
-
});
|
|
7675
|
-
sendJson(res, 200, { message: "Asset Already Exists" });
|
|
7952
|
+
reuseExisting(previous);
|
|
7676
7953
|
return;
|
|
7677
7954
|
}
|
|
7678
7955
|
renameSync(tmpPath, filePath);
|
|
@@ -7682,7 +7959,7 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
7682
7959
|
hash
|
|
7683
7960
|
}, "Failed to rename temp file to asset.");
|
|
7684
7961
|
cleanup();
|
|
7685
|
-
|
|
7962
|
+
reply(500, { error: "Internal Server Error" });
|
|
7686
7963
|
return;
|
|
7687
7964
|
}
|
|
7688
7965
|
store.upsert({
|
|
@@ -7695,8 +7972,8 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
7695
7972
|
log.info({
|
|
7696
7973
|
hash,
|
|
7697
7974
|
size
|
|
7698
|
-
}, "Stored uploaded asset
|
|
7699
|
-
|
|
7975
|
+
}, "Stored uploaded asset.");
|
|
7976
|
+
reply(201, {
|
|
7700
7977
|
message: "Created",
|
|
7701
7978
|
hash,
|
|
7702
7979
|
size
|
|
@@ -7707,7 +7984,7 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
7707
7984
|
if (!requestUrl) return requestUrl;
|
|
7708
7985
|
try {
|
|
7709
7986
|
const segments = new URL$1(requestUrl, `http://${LOOPBACK_HOST}`).pathname.split("/").filter(Boolean);
|
|
7710
|
-
if (segments
|
|
7987
|
+
if (segments[0]) segments[0] = "<capability>";
|
|
7711
7988
|
return `/${segments.join("/")}`;
|
|
7712
7989
|
} catch {
|
|
7713
7990
|
return "<invalid>";
|
|
@@ -7724,6 +8001,7 @@ function createAssetHttpServer(store, options = {}) {
|
|
|
7724
8001
|
res.end(JSON.stringify(payload));
|
|
7725
8002
|
}
|
|
7726
8003
|
return {
|
|
8004
|
+
importImage,
|
|
7727
8005
|
start,
|
|
7728
8006
|
stop,
|
|
7729
8007
|
getBaseUrl,
|
|
@@ -7749,185 +8027,6 @@ function getStoredAssetBytes(store, excludeHash) {
|
|
|
7749
8027
|
return Number.isFinite(record.size) && record.size > 0 ? total + record.size : total;
|
|
7750
8028
|
}, 0);
|
|
7751
8029
|
}
|
|
7752
|
-
// src/asset-store.ts
|
|
7753
|
-
const INDEX_FILENAME = "assets.json";
|
|
7754
|
-
const DEFAULT_INDEX_PATH = join(ASSET_DIR, INDEX_FILENAME);
|
|
7755
|
-
const IMAGE_MIME_TYPES = {
|
|
7756
|
-
png: "image/png",
|
|
7757
|
-
jpg: "image/jpeg",
|
|
7758
|
-
jpeg: "image/jpeg",
|
|
7759
|
-
svg: "image/svg+xml",
|
|
7760
|
-
gif: "image/gif",
|
|
7761
|
-
webp: "image/webp",
|
|
7762
|
-
avif: "image/avif"
|
|
7763
|
-
};
|
|
7764
|
-
function readIndex(indexPath) {
|
|
7765
|
-
if (!existsSync(indexPath)) return [];
|
|
7766
|
-
try {
|
|
7767
|
-
const raw = readFileSync(indexPath, "utf8").trim();
|
|
7768
|
-
if (!raw) return [];
|
|
7769
|
-
const parsed = JSON.parse(raw);
|
|
7770
|
-
return Array.isArray(parsed) ? parsed : [];
|
|
7771
|
-
} catch (error) {
|
|
7772
|
-
log.warn({
|
|
7773
|
-
error,
|
|
7774
|
-
indexPath
|
|
7775
|
-
}, "Failed to read asset catalog; starting fresh.");
|
|
7776
|
-
return [];
|
|
7777
|
-
}
|
|
7778
|
-
}
|
|
7779
|
-
function writeIndex(indexPath, values) {
|
|
7780
|
-
const payload = JSON.stringify(values, null, 2);
|
|
7781
|
-
const temporary = `${indexPath}.tmp.${process.pid}`;
|
|
7782
|
-
writeFileSync(temporary, payload, {
|
|
7783
|
-
encoding: "utf8",
|
|
7784
|
-
mode: 384
|
|
7785
|
-
});
|
|
7786
|
-
renameSync(temporary, indexPath);
|
|
7787
|
-
}
|
|
7788
|
-
function createAssetStore(options = {}) {
|
|
7789
|
-
ensureDir(ASSET_DIR);
|
|
7790
|
-
const indexPath = options.indexPath ?? DEFAULT_INDEX_PATH;
|
|
7791
|
-
ensureFile(indexPath);
|
|
7792
|
-
const records = /* @__PURE__ */ new Map();
|
|
7793
|
-
let persistTimer = null;
|
|
7794
|
-
function loadExisting() {
|
|
7795
|
-
const list = readIndex(indexPath);
|
|
7796
|
-
for (const record of list) if (record?.hash && record?.filePath) records.set(record.hash, record);
|
|
7797
|
-
}
|
|
7798
|
-
function persist() {
|
|
7799
|
-
if (persistTimer) return;
|
|
7800
|
-
persistTimer = setTimeout(() => {
|
|
7801
|
-
persistTimer = null;
|
|
7802
|
-
try {
|
|
7803
|
-
writeIndex(indexPath, [...records.values()]);
|
|
7804
|
-
} catch (error) {
|
|
7805
|
-
log.warn({
|
|
7806
|
-
error,
|
|
7807
|
-
indexPath
|
|
7808
|
-
}, "Could not persist asset catalog; retrying.");
|
|
7809
|
-
persist();
|
|
7810
|
-
}
|
|
7811
|
-
}, 5e3);
|
|
7812
|
-
if (typeof persistTimer.unref === "function") persistTimer.unref();
|
|
7813
|
-
}
|
|
7814
|
-
function flush() {
|
|
7815
|
-
if (persistTimer) {
|
|
7816
|
-
clearTimeout(persistTimer);
|
|
7817
|
-
persistTimer = null;
|
|
7818
|
-
}
|
|
7819
|
-
writeIndex(indexPath, [...records.values()]);
|
|
7820
|
-
}
|
|
7821
|
-
function list() {
|
|
7822
|
-
return [...records.values()];
|
|
7823
|
-
}
|
|
7824
|
-
function has(hash) {
|
|
7825
|
-
return records.has(hash);
|
|
7826
|
-
}
|
|
7827
|
-
function get(hash) {
|
|
7828
|
-
return records.get(hash);
|
|
7829
|
-
}
|
|
7830
|
-
function upsert(input) {
|
|
7831
|
-
const now = Date.now();
|
|
7832
|
-
const record = {
|
|
7833
|
-
...input,
|
|
7834
|
-
uploadedAt: input.uploadedAt ?? now,
|
|
7835
|
-
lastAccess: input.lastAccess ?? now
|
|
7836
|
-
};
|
|
7837
|
-
records.set(record.hash, record);
|
|
7838
|
-
persist();
|
|
7839
|
-
return record;
|
|
7840
|
-
}
|
|
7841
|
-
function touch(hash) {
|
|
7842
|
-
const existing = records.get(hash);
|
|
7843
|
-
if (!existing) return void 0;
|
|
7844
|
-
existing.lastAccess = Date.now();
|
|
7845
|
-
persist();
|
|
7846
|
-
return existing;
|
|
7847
|
-
}
|
|
7848
|
-
function remove(hash, { removeFile = true } = {}) {
|
|
7849
|
-
const record = records.get(hash);
|
|
7850
|
-
if (!record) return;
|
|
7851
|
-
if (removeFile) try {
|
|
7852
|
-
rmSync(record.filePath, { force: true });
|
|
7853
|
-
} catch (error) {
|
|
7854
|
-
log.warn({
|
|
7855
|
-
hash,
|
|
7856
|
-
error
|
|
7857
|
-
}, "Failed to remove asset file on delete.");
|
|
7858
|
-
return;
|
|
7859
|
-
}
|
|
7860
|
-
records.delete(hash);
|
|
7861
|
-
persist();
|
|
7862
|
-
}
|
|
7863
|
-
function reconcile() {
|
|
7864
|
-
let changed = false;
|
|
7865
|
-
for (const [hash, record] of records) if (!existsSync(record.filePath)) {
|
|
7866
|
-
records.delete(hash);
|
|
7867
|
-
changed = true;
|
|
7868
|
-
}
|
|
7869
|
-
try {
|
|
7870
|
-
const files = readdirSync(ASSET_DIR);
|
|
7871
|
-
const now = Date.now();
|
|
7872
|
-
for (const file of files) {
|
|
7873
|
-
if (file === INDEX_FILENAME) continue;
|
|
7874
|
-
if (file.includes(".tmp.")) {
|
|
7875
|
-
try {
|
|
7876
|
-
const filePath = join(ASSET_DIR, file);
|
|
7877
|
-
if (now - statSync(filePath).mtimeMs > 36e5) {
|
|
7878
|
-
rmSync(filePath, { force: true });
|
|
7879
|
-
log.info({ file }, "Cleaned up stale temp file.");
|
|
7880
|
-
}
|
|
7881
|
-
} catch (e) {
|
|
7882
|
-
log.debug({
|
|
7883
|
-
error: e,
|
|
7884
|
-
file
|
|
7885
|
-
}, "Failed to cleanup stale temp file.");
|
|
7886
|
-
}
|
|
7887
|
-
continue;
|
|
7888
|
-
}
|
|
7889
|
-
const hash = getHashFromAssetFilename(file);
|
|
7890
|
-
if (!hash) continue;
|
|
7891
|
-
if (!records.has(hash)) {
|
|
7892
|
-
const filePath = join(ASSET_DIR, file);
|
|
7893
|
-
try {
|
|
7894
|
-
const stat = statSync(filePath);
|
|
7895
|
-
records.set(hash, {
|
|
7896
|
-
hash,
|
|
7897
|
-
filePath,
|
|
7898
|
-
mimeType: IMAGE_MIME_TYPES[file.split(".").at(-1) ?? ""] ?? "application/octet-stream",
|
|
7899
|
-
size: stat.size,
|
|
7900
|
-
uploadedAt: stat.birthtimeMs,
|
|
7901
|
-
lastAccess: stat.atimeMs
|
|
7902
|
-
});
|
|
7903
|
-
changed = true;
|
|
7904
|
-
log.info({ hash }, "Recovered orphan asset file.");
|
|
7905
|
-
} catch (e) {
|
|
7906
|
-
log.warn({
|
|
7907
|
-
error: e,
|
|
7908
|
-
file
|
|
7909
|
-
}, "Failed to stat orphan file.");
|
|
7910
|
-
}
|
|
7911
|
-
}
|
|
7912
|
-
}
|
|
7913
|
-
} catch (error) {
|
|
7914
|
-
log.warn({ error }, "Failed to scan asset directory for orphans.");
|
|
7915
|
-
}
|
|
7916
|
-
if (changed) flush();
|
|
7917
|
-
}
|
|
7918
|
-
loadExisting();
|
|
7919
|
-
reconcile();
|
|
7920
|
-
return {
|
|
7921
|
-
list,
|
|
7922
|
-
has,
|
|
7923
|
-
get,
|
|
7924
|
-
upsert,
|
|
7925
|
-
touch,
|
|
7926
|
-
remove,
|
|
7927
|
-
reconcile,
|
|
7928
|
-
flush
|
|
7929
|
-
};
|
|
7930
|
-
}
|
|
7931
8030
|
// src/extension-registry.ts
|
|
7932
8031
|
var ExtensionRegistry = class {
|
|
7933
8032
|
#autoActivateGraceMs;
|
|
@@ -8000,22 +8099,18 @@ function unrefTimer(timer) {
|
|
|
8000
8099
|
if (typeof handle.unref === "function") handle.unref();
|
|
8001
8100
|
}
|
|
8002
8101
|
// src/extension-socket.ts
|
|
8003
|
-
const
|
|
8102
|
+
const HANDSHAKE_TIMEOUT_MS = 5e3;
|
|
8103
|
+
const BRIDGE_UPGRADE_MESSAGE = "Update to TemPad Dev extension 1.0 or later and reload Figma.";
|
|
8004
8104
|
function attachExtensionSocket(ws, options) {
|
|
8005
8105
|
const extension = {
|
|
8006
8106
|
id: options.createId(),
|
|
8007
8107
|
origin: options.origin.toLowerCase(),
|
|
8008
8108
|
connectedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
8009
|
-
legacy: ws.protocol !== TEMPAD_MCP_BRIDGE_SUBPROTOCOL,
|
|
8010
8109
|
ws
|
|
8011
8110
|
};
|
|
8012
8111
|
const checkout = options.runtimeProfile?.kind === "checkout";
|
|
8013
|
-
const handshakeTimer =
|
|
8014
|
-
handshakeTimer
|
|
8015
|
-
if (!checkout) {
|
|
8016
|
-
options.registry.add(extension);
|
|
8017
|
-
options.onConnected?.(extension.id);
|
|
8018
|
-
}
|
|
8112
|
+
const handshakeTimer = setTimeout(() => ws.close(1008, "Runtime handshake timed out."), HANDSHAKE_TIMEOUT_MS);
|
|
8113
|
+
handshakeTimer.unref();
|
|
8019
8114
|
const registered = {
|
|
8020
8115
|
id: extension.id,
|
|
8021
8116
|
protocolVersion: 15,
|
|
@@ -8027,14 +8122,12 @@ function attachExtensionSocket(ws, options) {
|
|
|
8027
8122
|
} : {},
|
|
8028
8123
|
type: "registered"
|
|
8029
8124
|
};
|
|
8030
|
-
ws.send(JSON.stringify(
|
|
8031
|
-
|
|
8032
|
-
|
|
8033
|
-
|
|
8034
|
-
|
|
8035
|
-
|
|
8036
|
-
scheduleAutoActivation(options);
|
|
8037
|
-
}
|
|
8125
|
+
ws.send(JSON.stringify(registered));
|
|
8126
|
+
if (!checkout) ws.send(JSON.stringify({
|
|
8127
|
+
type: "state",
|
|
8128
|
+
activeId: null,
|
|
8129
|
+
assetServerUrl: options.assetServerUrl
|
|
8130
|
+
}));
|
|
8038
8131
|
ws.on("message", (raw, isBinary) => {
|
|
8039
8132
|
if (ws.readyState !== import_websocket.default.OPEN) return;
|
|
8040
8133
|
if (isBinary) {
|
|
@@ -8055,9 +8148,15 @@ function attachExtensionSocket(ws, options) {
|
|
|
8055
8148
|
});
|
|
8056
8149
|
return;
|
|
8057
8150
|
}
|
|
8058
|
-
const parseResult =
|
|
8151
|
+
const parseResult = MessageFromExtensionSchema.safeParse(parsedJson);
|
|
8059
8152
|
if (!parseResult.success) {
|
|
8060
|
-
|
|
8153
|
+
const type = getRecordProperty(parsedJson, "type");
|
|
8154
|
+
if (type === "runtimeHello") {
|
|
8155
|
+
ws.close(1008, `Invalid runtime handshake. ${BRIDGE_UPGRADE_MESSAGE}`);
|
|
8156
|
+
return;
|
|
8157
|
+
}
|
|
8158
|
+
const requestId = getRecordProperty(parsedJson, "id");
|
|
8159
|
+
if (type === "toolResult" && typeof requestId === "string") options.onToolError(requestId, extension.id, {
|
|
8061
8160
|
code: "EXTENSION_DISCONNECTED",
|
|
8062
8161
|
message: "The extension returned an invalid result. A canvas write may have completed; inspect the canvas before retrying."
|
|
8063
8162
|
});
|
|
@@ -8069,11 +8168,7 @@ function attachExtensionSocket(ws, options) {
|
|
|
8069
8168
|
return;
|
|
8070
8169
|
}
|
|
8071
8170
|
const message = parseResult.data;
|
|
8072
|
-
if (
|
|
8073
|
-
ws.close(1008, "Checkout runtime handshake required.");
|
|
8074
|
-
return;
|
|
8075
|
-
}
|
|
8076
|
-
if (!extension.legacy && !extension.runtime && (message.type === "sessions" || message.type === "designAction" || message.type === "toolCompletion")) {
|
|
8171
|
+
if (!extension.runtime && message.type !== "runtimeHello") {
|
|
8077
8172
|
ws.close(1008, "Runtime handshake required.");
|
|
8078
8173
|
return;
|
|
8079
8174
|
}
|
|
@@ -8130,12 +8225,11 @@ function attachExtensionSocket(ws, options) {
|
|
|
8130
8225
|
ws.close(1008, "Terminal receipts are unavailable.");
|
|
8131
8226
|
return;
|
|
8132
8227
|
}
|
|
8133
|
-
|
|
8134
|
-
|
|
8135
|
-
ws.close(1008, "Unsupported extension bridge protocol.");
|
|
8228
|
+
if (!TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS.includes(message.protocolVersion)) {
|
|
8229
|
+
ws.close(1008, `Unsupported protocol. ${BRIDGE_UPGRADE_MESSAGE}`);
|
|
8136
8230
|
break;
|
|
8137
8231
|
}
|
|
8138
|
-
if (extension.runtime && (extension.runtime.version !== message.extensionVersion || extension.runtime.fingerprint !== message.extensionRuntimeFingerprint || extension.runtime.
|
|
8232
|
+
if (extension.runtime && (extension.runtime.version !== message.extensionVersion || extension.runtime.fingerprint !== message.extensionRuntimeFingerprint || extension.runtime.terminalReceipts !== message.terminalReceipts || extension.runtime.durableTerminalReceipts !== message.durableTerminalReceipts)) {
|
|
8139
8233
|
options.onProtocolWarning?.({
|
|
8140
8234
|
error: /* @__PURE__ */ new Error("Extension changed runtime identity on an open connection."),
|
|
8141
8235
|
extensionId: extension.id,
|
|
@@ -8147,13 +8241,12 @@ function attachExtensionSocket(ws, options) {
|
|
|
8147
8241
|
const firstHello = !extension.runtime;
|
|
8148
8242
|
clearTimeout(handshakeTimer);
|
|
8149
8243
|
extension.runtime = {
|
|
8150
|
-
protocolVersion,
|
|
8151
8244
|
version: message.extensionVersion,
|
|
8152
8245
|
fingerprint: message.extensionRuntimeFingerprint,
|
|
8153
8246
|
...message.terminalReceipts ? { terminalReceipts: true } : {},
|
|
8154
8247
|
...message.terminalReceipts && message.durableTerminalReceipts ? { durableTerminalReceipts: true } : {}
|
|
8155
8248
|
};
|
|
8156
|
-
if (
|
|
8249
|
+
if (firstHello) {
|
|
8157
8250
|
options.registry.add(extension);
|
|
8158
8251
|
options.onConnected?.(extension.id);
|
|
8159
8252
|
options.onStateChange();
|
|
@@ -8179,7 +8272,6 @@ function attachExtensionSocket(ws, options) {
|
|
|
8179
8272
|
options.onStateChange();
|
|
8180
8273
|
scheduleAutoActivation(options);
|
|
8181
8274
|
});
|
|
8182
|
-
if (checkout && extension.legacy) ws.close(1008, "Checkout runtime identity required.");
|
|
8183
8275
|
return extension;
|
|
8184
8276
|
}
|
|
8185
8277
|
function scheduleAutoActivation(options) {
|
|
@@ -8195,7 +8287,7 @@ function rawDataToBuffer(raw) {
|
|
|
8195
8287
|
return Buffer.concat(raw);
|
|
8196
8288
|
}
|
|
8197
8289
|
// src/instructions.md?raw
|
|
8198
|
-
var instructions_default = "You are connected to Figma through TemPad Dev. An active MCP badge selects the default file;\nbrowser focus does not. When the target is unclear, call `list_design_sessions` and pass the exact\n`sessionId` to `manage_design_task` with action `begin` or an independent read. Task targets never follow browser focus;\ntask-bound reads stay on their task's session. Independent reads need no task. Run calls against\nthe same file sequentially, including reads.\n\nFor new design work, call `manage_design_task` with action `begin` before research or writing,\nthen carry its `taskId`.\nChoose
|
|
8290
|
+
var instructions_default = "You are connected to Figma through TemPad Dev. An active MCP badge selects the default file;\nbrowser focus does not. When the target is unclear, call `list_design_sessions` and pass the exact\n`sessionId` to `manage_design_task` with action `begin` or an independent read. Task targets never follow browser focus;\ntask-bound reads stay on their task's session. Independent reads need no task. Run calls against\nthe same file sequentially, including reads.\n\nFor new design work, call `manage_design_task` with action `begin` before research or writing,\nthen carry its `taskId`.\nChoose an existing region with `set_design_anchor` once the region is clear; otherwise the first new\ntop-level Frame anchors automatically. Reads, selections, and later writes never change the anchor\nunless `set_design_anchor` does. Task identity survives turns. A pause or idle lease expiry releases\ncanvas ownership without cancelling the task;\nuse action `resume` with the current `epoch`, carry its returned `epoch` as `taskEpoch`, and reread the\nbound canvas with `get_structure` or `get_code` before writing. Use `get_design_task` for recovery,\nnot routine polling. Never replay a stale write or queue a write against an occupied file.\nActions `complete` and `cancel` require the current `epoch` and end a verified pass or explicitly\nabandon it; they are not for a wait for input.\nCompletion releases ownership but keeps the review and same task open for comments until the user\nclicks Done; resume that task for follow-up comments. Cancelled, closed, or replaced tasks cannot\nresume. The Figma Stop control permanently cancels the current task after its running operation\nsettles; do not resume or automatically replace it. If further work is necessary or requested,\nuse action `begin` with a fresh requestId; no separate\nFigma unlock or user turn is required. No progress or heartbeat calls are needed.\n\nFeedback drafts contain individually numbered elements captured when saved. Reread each exact node\nbefore acting; do not substitute the current selection. Supported hosts deliver submitted feedback\nthrough native conversation messages. Do not poll, launch helpers, or configure a control endpoint.\n\nTreat tool outputs as file-scoped facts. Never invent node IDs, resource refs, library keys, token\norigins, or design-system intent. Tool descriptions give mechanical affordances; the applicable host\nskill governs workflow, representation, and design judgment. For Figma-to-code, use `get_code` as\nvisible implementation evidence. Use `get_structure` only for hierarchy, geometry, managed-key\nuncertainty, or targeted mask, IMAGE paint, layout-grid, and frame-guide read-back via\n`options.native`.\n\nFor canvas authoring, choose the native representation through the skill, then describe one desired\nresult with `apply_canvas`. Canvas HTML serializes ordinary layers; typed fields carry selected\nnative state, resources, and bindings. Never send raw Plugin API operations or arbitrary JavaScript.\n`get_design_system` is optional when existing-resource reuse is relevant and permitted; new local\nresources do not require it. `scope: \"fonts\"` independently reads environment availability.\nFor large files, `scope: \"pages\"` finds a relevant component page before `pageId`-scoped discovery;\nvariables, styles, and shaders remain file-wide. Use catalog CSS names or a call-scoped `theme` for\nvariable utilities and native text-style classes. Load skill references only after choosing a\nnative concept.\n\nWhen design evidence is limited to the current page or an independent system without reuse, stay\non the Direct path: do not discover resource catalogs, inspect other pages, or use catalog refs.\n`scope: \"fonts\"` remains available. Local variables and styles remain file-wide Figma resources,\nand the extension may still check file-wide identities internally for safe reconciliation.\n\nCreates add and automatically place one root. Updates use exact node identity: omission preserves\nlive state; explicit removal removes managed content. Read structural verification and resolve\nwarnings before claiming completion. Use `get_screenshot` when pixels affect a decision and open\nits image before claiming visual verification. Use `asset.localPath` when present, otherwise\n`asset.url`; native media hashes identify assets within one Figma file, not preview bytes. Never\nship `data-hint-*` attributes from read-tool output.\n";
|
|
8199
8291
|
// src/request.ts
|
|
8200
8292
|
const pendingCalls = /* @__PURE__ */ new Map();
|
|
8201
8293
|
const UNKNOWN_WRITE_OUTCOME = "The canvas operation outcome is unknown. Do not replay this write; inspect the canvas or reload the executing Figma tab before continuing.";
|
|
@@ -8456,7 +8548,7 @@ const CONNECTIVITY_TROUBLESHOOTING_LINES = [
|
|
|
8456
8548
|
"Troubleshooting:",
|
|
8457
8549
|
"- In Figma, open TemPad Dev panel and enable the MCP server in Preferences → Agent integration. Enabled permits connection; it does not prove that an extension is active.",
|
|
8458
8550
|
"- Badge-default reads require the intended tab's active MCP badge. Exact sessionId reads require that session in list_design_sessions; browser focus does not select a default.",
|
|
8459
|
-
"- If the connection is missing or reports a protocol mismatch, update TemPad Dev and its agent plugin, reload the same Figma tab, and reconnect. Use list_design_sessions to confirm the intended session before retrying."
|
|
8551
|
+
"- If the connection is missing or reports a protocol mismatch, update to TemPad Dev extension 1.0 or later and update its agent plugin, reload the same Figma tab, and reconnect. Use list_design_sessions to confirm the intended session before retrying."
|
|
8460
8552
|
];
|
|
8461
8553
|
const MULTI_SELECTION_TROUBLESHOOTING_LINE = "Tip: Select one or more visible nodes, or pass nodeIds (nodeId for a single node).";
|
|
8462
8554
|
const VERIFICATION_TROUBLESHOOTING_LINE = "Tip: TemPad attempts to roll verification failures back. Check the reported rollback outcome and satisfy any readback requirement. Inspect the affected nodes and resources before choosing a bounded correction that preserves unrelated design intent. Do not repeat the failed write unchanged or use Undo without confirming which edit it would reverse.";
|
|
@@ -8496,7 +8588,7 @@ const TOOL_DEFS = [
|
|
|
8496
8588
|
}),
|
|
8497
8589
|
extTool({
|
|
8498
8590
|
name: "set_design_anchor",
|
|
8499
|
-
description: "
|
|
8591
|
+
description: "Place this task’s controls on an existing design region or explicitly switch regions. The first created top-level Frame binds automatically. Reads, selections, and later writes never switch the anchor. This only places task UI and does not modify the node, page, viewport, or selection.",
|
|
8500
8592
|
annotations: ASSET_WRITE_ANNOTATIONS,
|
|
8501
8593
|
parameters: SetDesignAnchorParametersSchema,
|
|
8502
8594
|
target: "extension",
|
|
@@ -8671,6 +8763,45 @@ function createInlineBudgetExceededToolResponse(toolName, actualBytes) {
|
|
|
8671
8763
|
}]
|
|
8672
8764
|
};
|
|
8673
8765
|
}
|
|
8766
|
+
/** OpenCode's model adapter reads content. Since 1.17.12 an empty list selects its JSON fallback. */
|
|
8767
|
+
function presentClientToolResult(name, client, result, preserveNotices = false) {
|
|
8768
|
+
if (client?.name !== "opencode" || ![
|
|
8769
|
+
"get_code",
|
|
8770
|
+
"get_structure",
|
|
8771
|
+
"get_design_system",
|
|
8772
|
+
"apply_canvas"
|
|
8773
|
+
].includes(name) || result.isError || !result.structuredContent || result.content.some((item) => item.type !== "text")) return result;
|
|
8774
|
+
let payload = result.structuredContent;
|
|
8775
|
+
if (name === "apply_canvas") {
|
|
8776
|
+
const { rootNodeId, rootRemoved, nodeIdsByKey } = payload;
|
|
8777
|
+
if (!rootNodeId || rootRemoved || !isRecord(nodeIdsByKey) || !Object.keys(nodeIdsByKey).length) return result;
|
|
8778
|
+
payload = { nodeIdsByKey };
|
|
8779
|
+
} else if (!preserveNotices) {
|
|
8780
|
+
const version = VersionSchema.safeParse(client.version);
|
|
8781
|
+
if (version.success && version.data.startsWith("1.") && compareVersions(version.data, "1.17.12") >= 0) return {
|
|
8782
|
+
...result,
|
|
8783
|
+
content: []
|
|
8784
|
+
};
|
|
8785
|
+
}
|
|
8786
|
+
const text = {
|
|
8787
|
+
type: "text",
|
|
8788
|
+
text: JSON.stringify(payload)
|
|
8789
|
+
};
|
|
8790
|
+
const mirrored = {
|
|
8791
|
+
...result,
|
|
8792
|
+
content: [...result.content, text]
|
|
8793
|
+
};
|
|
8794
|
+
if (measureCallToolResultBytes(mirrored) <= 65536) return mirrored;
|
|
8795
|
+
const guidance = {
|
|
8796
|
+
type: "text",
|
|
8797
|
+
text: name === "apply_canvas" ? "Read the reported root with get_structure for node IDs before continuing. Do not replay this write." : getBudgetRetryGuidance(name)
|
|
8798
|
+
};
|
|
8799
|
+
const retry = {
|
|
8800
|
+
...result,
|
|
8801
|
+
content: [...result.content, guidance]
|
|
8802
|
+
};
|
|
8803
|
+
return measureCallToolResultBytes(retry) <= 65536 ? retry : result;
|
|
8804
|
+
}
|
|
8674
8805
|
function toCallToolResult(result) {
|
|
8675
8806
|
return result;
|
|
8676
8807
|
}
|
|
@@ -8684,29 +8815,10 @@ function getBudgetRetryGuidance(toolName) {
|
|
|
8684
8815
|
case "get_code": return "Reduce selection size or request a smaller nodeId subtree and retry.";
|
|
8685
8816
|
case "get_design_system": return "Continue from another catalog cursor or avoid the oversized exact definition.";
|
|
8686
8817
|
case "get_structure": return "Reduce selection size or pass a smaller depth and retry.";
|
|
8687
|
-
case "get_token_defs": return "Reduce requested names or split them into smaller batches and retry.";
|
|
8688
8818
|
case "get_screenshot": return "Pass a smaller nodeId and retry.";
|
|
8689
|
-
case "get_assets": return "Request fewer hashes in a single call and retry.";
|
|
8690
8819
|
case "upload_asset": return "Generate a smaller PNG, JPEG, or GIF and retry without printing its data URL.";
|
|
8691
8820
|
}
|
|
8692
8821
|
}
|
|
8693
|
-
// src/versioned-extension.ts
|
|
8694
|
-
const NODE_READS = /* @__PURE__ */ new Set([
|
|
8695
|
-
"get_code",
|
|
8696
|
-
"get_screenshot",
|
|
8697
|
-
"get_structure"
|
|
8698
|
-
]);
|
|
8699
|
-
/** Preserve protocol 13's wire arguments; never silently strip a newer read option. */
|
|
8700
|
-
function assertVersionedToolSupport(protocolVersion, name, args) {
|
|
8701
|
-
if (protocolVersion !== 13) return;
|
|
8702
|
-
if (!(NODE_READS.has(name) && getRecordProperty(args, "nodeIds") !== void 0 || name === "get_structure" && getRecordProperty(getRecordProperty(args, "options"), "depth") === 0 || name === "get_code" && getRecordProperty(args, "resolveTokens") === true)) return;
|
|
8703
|
-
throw Object.assign(/* @__PURE__ */ new Error("This read option requires TemPad Dev extension 0.23.0 or later. Update the extension and reload the Figma tab. Until then, use individual nodeId reads, positive structure depths, and unresolved token references. Existing sessions, design tasks, and canvas writes remain available."), { code: TEMPAD_MCP_ERROR_CODES.EXTENSION_UPGRADE_REQUIRED });
|
|
8704
|
-
}
|
|
8705
|
-
function versionedReadNotice(protocolVersion, name) {
|
|
8706
|
-
if (protocolVersion !== 13) return void 0;
|
|
8707
|
-
if (name === "get_code" || name === "get_token_defs") return "Protocol 13 compatibility: token metadata uses the installed extension’s original semantics; complete modes and alias dependencies are not guaranteed. Use exact nodeId reads for code. Upgrade the extension and reload Figma for consumer-aware resolution and complete definitions.";
|
|
8708
|
-
if (name === "get_structure" || name === "get_screenshot") return "Protocol 13 compatibility: omitted nodeId uses the installed extension’s original selection behavior; structure may use a common ancestor. Use exact nodeId reads to preserve each requested root.";
|
|
8709
|
-
}
|
|
8710
8822
|
// src/websocket-server.ts
|
|
8711
8823
|
async function startExtensionWebSocketServer({ maxPayloadBytes, maxConnections, originPolicy, portCandidates, onPortInUse, onConnectionLimit, onRejectedHandshake }) {
|
|
8712
8824
|
for (const candidate of portCandidates) {
|
|
@@ -8721,7 +8833,7 @@ async function startExtensionWebSocketServer({ maxPayloadBytes, maxConnections,
|
|
|
8721
8833
|
return false;
|
|
8722
8834
|
}
|
|
8723
8835
|
const protocol = info.req.headers["sec-websocket-protocol"];
|
|
8724
|
-
const allowed = isAllowedWebSocketRequest(info.origin, info.req.url, originPolicy) &&
|
|
8836
|
+
const allowed = isAllowedWebSocketRequest(info.origin, info.req.url, originPolicy) && !!protocol?.split(",").some((value) => value.trim() === "tempad-mcp");
|
|
8725
8837
|
if (!allowed) onRejectedHandshake?.(info.origin, info.req.url);
|
|
8726
8838
|
return allowed;
|
|
8727
8839
|
}
|
|
@@ -8784,7 +8896,7 @@ async function startHub(options = {}) {
|
|
|
8784
8896
|
"get_screenshot",
|
|
8785
8897
|
"get_design_system"
|
|
8786
8898
|
]);
|
|
8787
|
-
const { wsPortCandidates, toolTimeoutMs, getCodeTimeoutMs, getDesignSystemTimeoutMs, pageStructureTimeoutMs, applyCanvasTimeoutMs, maxPayloadBytes,
|
|
8899
|
+
const { wsPortCandidates, toolTimeoutMs, getCodeTimeoutMs, getDesignSystemTimeoutMs, pageStructureTimeoutMs, applyCanvasTimeoutMs, maxPayloadBytes, maxExtensionConnections, autoActivateGraceMs, assetTtlMs, allowedExtensionOrigins } = getMcpServerConfig(RUNTIME_PROFILE);
|
|
8788
8900
|
const extensionOriginPolicy = createExtensionOriginPolicy(allowedExtensionOrigins);
|
|
8789
8901
|
const runtimeControl = options.prototype ? new HubControl(options.prototype.secret, void 0, {
|
|
8790
8902
|
paused: options.prototype.paused,
|
|
@@ -9069,7 +9181,6 @@ async function startHub(options = {}) {
|
|
|
9069
9181
|
...tool,
|
|
9070
9182
|
handler: async () => {
|
|
9071
9183
|
const result = { sessions: extensionRegistry.list().flatMap((value) => value.sessions?.sessions ?? []) };
|
|
9072
|
-
if (!result.sessions.length && extensionRegistry.list().some((value) => value.legacy)) throw extensionUpgradeRequired();
|
|
9073
9184
|
return {
|
|
9074
9185
|
content: [{
|
|
9075
9186
|
type: "text",
|
|
@@ -9124,36 +9235,22 @@ async function startHub(options = {}) {
|
|
|
9124
9235
|
log.info("Asset TTL cleanup disabled (TEMPAD_MCP_ASSET_TTL_MS=0).");
|
|
9125
9236
|
return;
|
|
9126
9237
|
}
|
|
9127
|
-
|
|
9238
|
+
const sweep = () => {
|
|
9239
|
+
const result = pruneExpiredAssets(assetStore, assetTtlMs);
|
|
9240
|
+
log.info({
|
|
9241
|
+
...result,
|
|
9242
|
+
ttlMs: assetTtlMs
|
|
9243
|
+
}, "Asset TTL sweep completed.");
|
|
9244
|
+
};
|
|
9245
|
+
sweep();
|
|
9128
9246
|
const intervalMs = Math.min(assetTtlMs, 864e5);
|
|
9129
|
-
assetCleanupTimer = setInterval(
|
|
9130
|
-
pruneExpiredAssets(assetTtlMs);
|
|
9131
|
-
}, intervalMs);
|
|
9247
|
+
assetCleanupTimer = setInterval(sweep, intervalMs);
|
|
9132
9248
|
unrefTimer(assetCleanupTimer);
|
|
9133
9249
|
log.info({
|
|
9134
9250
|
ttlMs: assetTtlMs,
|
|
9135
9251
|
intervalMs
|
|
9136
9252
|
}, "Asset TTL cleanup enabled.");
|
|
9137
9253
|
}
|
|
9138
|
-
function pruneExpiredAssets(ttlMs) {
|
|
9139
|
-
const now = Date.now();
|
|
9140
|
-
let removed = 0;
|
|
9141
|
-
let checked = 0;
|
|
9142
|
-
for (const record of assetStore.list()) {
|
|
9143
|
-
checked += 1;
|
|
9144
|
-
const lastAccess = Number.isFinite(record.lastAccess) ? record.lastAccess : record.uploadedAt;
|
|
9145
|
-
if (!lastAccess) continue;
|
|
9146
|
-
if (now - lastAccess > ttlMs) {
|
|
9147
|
-
assetStore.remove(record.hash);
|
|
9148
|
-
removed += 1;
|
|
9149
|
-
}
|
|
9150
|
-
}
|
|
9151
|
-
log.info({
|
|
9152
|
-
checked,
|
|
9153
|
-
removed,
|
|
9154
|
-
ttlMs
|
|
9155
|
-
}, "Asset TTL sweep completed.");
|
|
9156
|
-
}
|
|
9157
9254
|
function publishDesignTask({ task, extensionId }) {
|
|
9158
9255
|
const message = JSON.stringify({
|
|
9159
9256
|
type: "designTaskState",
|
|
@@ -9306,19 +9403,18 @@ async function startHub(options = {}) {
|
|
|
9306
9403
|
const schema = tool.parameters;
|
|
9307
9404
|
const connectionId = ownerId;
|
|
9308
9405
|
const isCanvasWrite = tool.name === "apply_canvas";
|
|
9406
|
+
const present = (result, preserveNotices = false) => presentClientToolResult(tool.name, mcp.server.getClientVersion(), result, preserveNotices);
|
|
9309
9407
|
const handler = async (args, extra) => {
|
|
9310
9408
|
const activity = Symbol();
|
|
9311
9409
|
let requestId;
|
|
9312
9410
|
let readTarget;
|
|
9313
9411
|
try {
|
|
9314
|
-
if (runtimeControl && !runtimeControl.admitting()) throw unavailable();
|
|
9315
9412
|
noteActivity();
|
|
9316
9413
|
activeCalls.set(activity, Date.now() + Math.max(toolTimeoutMs, getCodeTimeoutMs, getDesignSystemTimeoutMs, pageStructureTimeoutMs, applyCanvasTimeoutMs * 2) + MCP_NODE_READ_BATCH_WORK_BUDGET_MS);
|
|
9317
9414
|
extra.signal.throwIfAborted();
|
|
9318
9415
|
const ownerId = await agentClients.owner(connectionId, extra._meta, mcp.server.getClientVersion());
|
|
9319
9416
|
extra.signal.throwIfAborted();
|
|
9320
|
-
const
|
|
9321
|
-
const { taskId, taskEpoch, ...parsedArgs } = parsed;
|
|
9417
|
+
const { taskId, taskEpoch, ...parsedArgs } = schema.parse(args);
|
|
9322
9418
|
const readSessionId = EXACT_SESSION_READ_TOOLS.has(tool.name) ? getRecordProperty(parsedArgs, "sessionId") : void 0;
|
|
9323
9419
|
const explicitSessionId = typeof readSessionId === "string" ? readSessionId : void 0;
|
|
9324
9420
|
if (explicitSessionId) delete parsedArgs.sessionId;
|
|
@@ -9330,22 +9426,6 @@ async function startHub(options = {}) {
|
|
|
9330
9426
|
else if (isCanvasWrite) timeoutMs = applyCanvasTimeoutMs;
|
|
9331
9427
|
if ((tool.name === "get_code" || tool.name === "get_screenshot") && !getRecordProperty(parsedArgs, "nodeId")) timeoutMs += MCP_NODE_READ_BATCH_WORK_BUDGET_MS;
|
|
9332
9428
|
activeCalls.set(activity, Date.now() + timeoutMs * (isCanvasWrite ? 2 : 1));
|
|
9333
|
-
const legacy = !taskId && !explicitSessionId ? extensionRegistry.getActive() : void 0;
|
|
9334
|
-
if (legacy?.legacy) {
|
|
9335
|
-
const payload = legacyToolPayload(tool.name, parsed);
|
|
9336
|
-
const registration = register(legacy.id, timeoutMs, { signal: extra.signal });
|
|
9337
|
-
requestId = registration.requestId;
|
|
9338
|
-
try {
|
|
9339
|
-
legacy.ws.send(JSON.stringify({
|
|
9340
|
-
type: "toolCall",
|
|
9341
|
-
id: requestId,
|
|
9342
|
-
payload
|
|
9343
|
-
}));
|
|
9344
|
-
} catch (error) {
|
|
9345
|
-
reject(requestId, legacy.id, coerceToolError(error));
|
|
9346
|
-
}
|
|
9347
|
-
return createToolResponse(tool, await registration.promise);
|
|
9348
|
-
}
|
|
9349
9429
|
const { extension: activeExt, session } = resolveDesignRoute(ownerId, taskId, true, explicitSessionId);
|
|
9350
9430
|
readTarget = {
|
|
9351
9431
|
fileKey: session.fileKey,
|
|
@@ -9354,8 +9434,6 @@ async function startHub(options = {}) {
|
|
|
9354
9434
|
const runtimeIssues = getExtensionRuntimeIssues(activeExt.runtime);
|
|
9355
9435
|
if (runtimeIssues.length) throw createCodedError(TEMPAD_MCP_ERROR_CODES.RUNTIME_IDENTITY_MISMATCH, `${runtimeIssues.join("; ")}. Rebuild/reload the extension and start a fresh agent task.`);
|
|
9356
9436
|
const runtime = isCanvasWrite ? buildAuthoringRuntimeEvidence(activeExt) : void 0;
|
|
9357
|
-
const protocolVersion = activeExt.runtime.protocolVersion;
|
|
9358
|
-
assertVersionedToolSupport(protocolVersion, tool.name, parsedArgs);
|
|
9359
9437
|
if (runtime && utf8Bytes({ runtime }) > 2048) throw createCodedError(TEMPAD_MCP_ERROR_CODES.RUNTIME_IDENTITY_MISMATCH, "Runtime evidence exceeds the reserved response budget. No canvas write was dispatched.");
|
|
9360
9438
|
designTasks.checkOperation(ownerId, session, taskId, isCanvasWrite);
|
|
9361
9439
|
const registration = register(activeExt.id, timeoutMs, {
|
|
@@ -9419,16 +9497,14 @@ async function startHub(options = {}) {
|
|
|
9419
9497
|
}
|
|
9420
9498
|
}
|
|
9421
9499
|
const readEvidence = hasCanvasReadEvidence(tool.name, payload);
|
|
9422
|
-
const response = createToolResponse(tool, payload, {
|
|
9423
|
-
runtime,
|
|
9424
|
-
notice: versionedReadNotice(protocolVersion, tool.name)
|
|
9425
|
-
});
|
|
9500
|
+
const response = createToolResponse(tool, payload, { runtime });
|
|
9426
9501
|
if (!response.isError && readGeneration !== void 0) designTasks.acknowledgeFileRead(session.fileKey, readGeneration);
|
|
9427
9502
|
if (!response.isError && readEvidence) {
|
|
9428
9503
|
if (taskId) designTasks.acknowledgeRead(taskId, ownerId, taskEpoch);
|
|
9429
9504
|
designTasks.acknowledgeFileRead(session.fileKey);
|
|
9430
9505
|
}
|
|
9431
|
-
|
|
9506
|
+
const final = withCanvasReadNotice(tool.name, response, readTarget);
|
|
9507
|
+
return present(final, final !== response);
|
|
9432
9508
|
} catch (error) {
|
|
9433
9509
|
const normalized = coerceToolError(error);
|
|
9434
9510
|
log.error({
|
|
@@ -9476,7 +9552,6 @@ async function startHub(options = {}) {
|
|
|
9476
9552
|
const registerHandler = async (args, extra) => {
|
|
9477
9553
|
const activity = Symbol();
|
|
9478
9554
|
try {
|
|
9479
|
-
if (runtimeControl && !runtimeControl.admitting()) throw unavailable();
|
|
9480
9555
|
noteActivity();
|
|
9481
9556
|
activeCalls.set(activity, Date.now() + toolTimeoutMs);
|
|
9482
9557
|
extra.signal.throwIfAborted();
|
|
@@ -9524,7 +9599,7 @@ async function startHub(options = {}) {
|
|
|
9524
9599
|
});
|
|
9525
9600
|
});
|
|
9526
9601
|
}
|
|
9527
|
-
function createToolResponse(tool, payload, { runtime, includeLocalAssetPaths = true
|
|
9602
|
+
function createToolResponse(tool, payload, { runtime, includeLocalAssetPaths = true } = {}) {
|
|
9528
9603
|
const toolName = tool.name;
|
|
9529
9604
|
const enrichedPayload = (() => {
|
|
9530
9605
|
if (includeLocalAssetPaths && (toolName === "get_code" || toolName === "get_screenshot")) {
|
|
@@ -9561,18 +9636,10 @@ async function startHub(options = {}) {
|
|
|
9561
9636
|
}]
|
|
9562
9637
|
};
|
|
9563
9638
|
}
|
|
9564
|
-
if (notice) rawResult = {
|
|
9565
|
-
...rawResult,
|
|
9566
|
-
content: [{
|
|
9567
|
-
type: "text",
|
|
9568
|
-
text: notice
|
|
9569
|
-
}, ...rawResult.content]
|
|
9570
|
-
};
|
|
9571
9639
|
const resultBytes = measureCallToolResultBytes(rawResult);
|
|
9572
9640
|
if (resultBytes > 65536) {
|
|
9573
9641
|
if (includeLocalAssetPaths && (toolName === "get_code" || toolName === "get_screenshot")) return createToolResponse(tool, payload, {
|
|
9574
9642
|
runtime,
|
|
9575
|
-
notice,
|
|
9576
9643
|
includeLocalAssetPaths: false
|
|
9577
9644
|
});
|
|
9578
9645
|
log.warn({
|
|
@@ -9623,31 +9690,7 @@ async function startHub(options = {}) {
|
|
|
9623
9690
|
} : asset;
|
|
9624
9691
|
}
|
|
9625
9692
|
async function handleUploadAsset({ dataUrl }, _ownerId, signal) {
|
|
9626
|
-
|
|
9627
|
-
const filename = buildAssetFilename(decoded.hash, decoded.mimeType);
|
|
9628
|
-
const response = await fetch(`${assetHttpServer.getBaseUrl()}/assets/${filename}`, {
|
|
9629
|
-
signal,
|
|
9630
|
-
method: "POST",
|
|
9631
|
-
headers: {
|
|
9632
|
-
"Content-Length": String(decoded.bytes.length),
|
|
9633
|
-
"Content-Type": decoded.mimeType
|
|
9634
|
-
},
|
|
9635
|
-
body: new Uint8Array(decoded.bytes)
|
|
9636
|
-
});
|
|
9637
|
-
try {
|
|
9638
|
-
if (!response.ok) {
|
|
9639
|
-
const detail = (await response.text()).slice(0, 500);
|
|
9640
|
-
throw new Error(`Hub asset import failed (${response.status}): ${detail}`);
|
|
9641
|
-
}
|
|
9642
|
-
signal.throwIfAborted();
|
|
9643
|
-
return createUploadAssetToolResponse({
|
|
9644
|
-
assetHash: decoded.hash,
|
|
9645
|
-
mimeType: decoded.mimeType,
|
|
9646
|
-
size: decoded.bytes.length
|
|
9647
|
-
});
|
|
9648
|
-
} finally {
|
|
9649
|
-
await response.body?.cancel().catch(() => {});
|
|
9650
|
-
}
|
|
9693
|
+
return createUploadAssetToolResponse(await assetHttpServer.importImage(dataUrl, signal));
|
|
9651
9694
|
}
|
|
9652
9695
|
function unrefTimer(timer) {
|
|
9653
9696
|
if (typeof timer === "object" && timer !== null) {
|
|
@@ -9662,7 +9705,7 @@ async function startHub(options = {}) {
|
|
|
9662
9705
|
const message = {
|
|
9663
9706
|
type: "state",
|
|
9664
9707
|
activeId,
|
|
9665
|
-
assetServerUrl: assetHttpServer.getBaseUrl(
|
|
9708
|
+
assetServerUrl: assetHttpServer.getBaseUrl()
|
|
9666
9709
|
};
|
|
9667
9710
|
extension.ws.send(JSON.stringify(message));
|
|
9668
9711
|
}
|
|
@@ -9735,9 +9778,9 @@ async function startHub(options = {}) {
|
|
|
9735
9778
|
}, SHUTDOWN_TIMEOUT));
|
|
9736
9779
|
}
|
|
9737
9780
|
function attachConsumer(sock, registration) {
|
|
9738
|
-
const ownerId = registration
|
|
9781
|
+
const ownerId = registration ? managedEdgeOwner(registration.sessionId, registration.token) : randomUUID();
|
|
9739
9782
|
if (registration) {
|
|
9740
|
-
runtimeDataSockets.set(
|
|
9783
|
+
runtimeDataSockets.set(registration.sessionId, sock);
|
|
9741
9784
|
agentClients.registerContext(ownerId, registration.context);
|
|
9742
9785
|
}
|
|
9743
9786
|
const mcp = createMcpServer(ownerId);
|
|
@@ -9748,7 +9791,7 @@ async function startHub(options = {}) {
|
|
|
9748
9791
|
log.info(`Consumer connected. Total: ${consumerCount}`);
|
|
9749
9792
|
const transport = registration && runtimeControl ? new RuntimeDataTransport(new SocketTransport(sock), {
|
|
9750
9793
|
generation: () => runtimeControl.currentGeneration,
|
|
9751
|
-
admit: (generation, method) => runtimeControl.admits(
|
|
9794
|
+
admit: (generation, method) => runtimeControl.admits(registration.sessionId, generation, method),
|
|
9752
9795
|
role: "hub"
|
|
9753
9796
|
}) : new ConsumerTransport(sock, sock);
|
|
9754
9797
|
mcp.connect(transport).catch((err) => {
|
|
@@ -9764,8 +9807,10 @@ async function startHub(options = {}) {
|
|
|
9764
9807
|
});
|
|
9765
9808
|
const closeConsumer = async () => {
|
|
9766
9809
|
agentClients.disconnect(ownerId);
|
|
9767
|
-
|
|
9768
|
-
|
|
9810
|
+
if (registration) {
|
|
9811
|
+
runtimeDataSockets.delete(registration.sessionId);
|
|
9812
|
+
runtimeControl?.forget(registration.sessionId);
|
|
9813
|
+
}
|
|
9769
9814
|
await transport.close().catch((closeErr) => log.warn({ err: closeErr }, "Transport close failed."));
|
|
9770
9815
|
await mcp.close().catch((closeErr) => log.warn({ err: closeErr }, "MCP session close failed."));
|
|
9771
9816
|
consumerSessions.delete(mcp);
|
|
@@ -9896,7 +9941,7 @@ async function startHub(options = {}) {
|
|
|
9896
9941
|
onActivity: noteActivity,
|
|
9897
9942
|
...runtimeControl ? {
|
|
9898
9943
|
admit: () => runtimeControl.admitting(),
|
|
9899
|
-
|
|
9944
|
+
accessToken: endpointTokens?.accessToken,
|
|
9900
9945
|
port: endpoints?.httpPort
|
|
9901
9946
|
} : {},
|
|
9902
9947
|
authorizeExtensionOrigin: (origin) => extensionRegistry.getActive()?.origin === origin.toLowerCase()
|
|
@@ -9973,6 +10018,7 @@ async function startHub(options = {}) {
|
|
|
9973
10018
|
});
|
|
9974
10019
|
activeWss.on("connection", (ws, request) => {
|
|
9975
10020
|
attachExtensionSocket(ws, {
|
|
10021
|
+
assetServerUrl: assetHttpServer.getBaseUrl(),
|
|
9976
10022
|
runtimeProfile: RUNTIME_PROFILE,
|
|
9977
10023
|
terminalReceiptGeneration: terminalReceipts.generation,
|
|
9978
10024
|
onToolCompletion: (message, extension) => {
|
|
@@ -10143,4 +10189,4 @@ async function startHub(options = {}) {
|
|
|
10143
10189
|
}
|
|
10144
10190
|
export { startHub as t };
|
|
10145
10191
|
|
|
10146
|
-
//# sourceMappingURL=hub-runtime-
|
|
10192
|
+
//# sourceMappingURL=hub-runtime-ApgbrLQI.mjs.map
|