@tempad-dev/mcp 1.0.5 → 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.
Files changed (102) hide show
  1. package/README.md +23 -9
  2. package/README.zh-Hans.md +21 -8
  3. package/dist/{acquire-DK4Fg36-.mjs → acquire-CCPjn86-.mjs} +3 -3
  4. package/dist/acquire-CCPjn86-.mjs.map +1 -0
  5. package/dist/{acquire-C1v5UQB2.mjs → acquire-C_qsbxdV.mjs} +1 -1
  6. package/dist/{bootstrap-CNJpiOAm.mjs → bootstrap-BkZ1dGkI.mjs} +32 -26
  7. package/dist/bootstrap-BkZ1dGkI.mjs.map +1 -0
  8. package/dist/cli.mjs +6 -6
  9. package/dist/cli.mjs.map +1 -1
  10. package/dist/client-binding-CvSSv9JC.mjs.map +1 -1
  11. package/dist/{cold-start-DeFnhN3x.mjs → cold-start-Cv4OAoez.mjs} +1 -1
  12. package/dist/{cold-start-BOLlW_0n.mjs → cold-start-qMVT1cNu.mjs} +93 -46
  13. package/dist/cold-start-qMVT1cNu.mjs.map +1 -0
  14. package/dist/{config-Busa_Dqv.mjs → config-Qvh73WBD.mjs} +20 -73
  15. package/dist/config-Qvh73WBD.mjs.map +1 -0
  16. package/dist/{design-task-store-BHR54v8-.mjs → design-task-store-BQy2SO7l.mjs} +4 -3
  17. package/dist/design-task-store-BQy2SO7l.mjs.map +1 -0
  18. package/dist/durable-json-_WKesGDj.mjs.map +1 -1
  19. package/dist/{edge-m9VuTeju.mjs → edge-DO3aAdn1.mjs} +8 -8
  20. package/dist/edge-DO3aAdn1.mjs.map +1 -0
  21. package/dist/{edge-DP-CwLYS.mjs → edge-DdEimtG9.mjs} +1 -1
  22. package/dist/{hook-receipts-QJU3AMoY.mjs → hook-receipts-BIUk86RJ.mjs} +2 -2
  23. package/dist/hook-receipts-BIUk86RJ.mjs.map +1 -0
  24. package/dist/host-context-9TVtjsSm.mjs.map +1 -1
  25. package/dist/{hub-control-UlA4Fncg.mjs → hub-control-C2jNTi3G.mjs} +3 -3
  26. package/dist/hub-control-C2jNTi3G.mjs.map +1 -0
  27. package/dist/{hub-runtime-BBnfo1yd.mjs → hub-runtime-ApgbrLQI.mjs} +453 -431
  28. package/dist/hub-runtime-ApgbrLQI.mjs.map +1 -0
  29. package/dist/{hub-runtime-U3Set0EC.mjs → hub-runtime-BZ6Nrold.mjs} +1 -1
  30. package/dist/hub.mjs +2 -2
  31. package/dist/hub.mjs.map +1 -1
  32. package/dist/{identity-CCaDEwgc.mjs → identity-C80lcT6j.mjs} +2 -2
  33. package/dist/identity-C80lcT6j.mjs.map +1 -0
  34. package/dist/indexes-zYqwqnU6.mjs.map +1 -1
  35. package/dist/log-transport.mjs.map +1 -1
  36. package/dist/managed-runtime.mjs +9 -9
  37. package/dist/managed-runtime.mjs.map +1 -1
  38. package/dist/on-exit-leak-free-By20-eFK.mjs.map +1 -1
  39. package/dist/pino-BiEyUxFF.mjs.map +1 -1
  40. package/dist/pino-abstract-transport-BBwCGDga.mjs.map +1 -1
  41. package/dist/pino-file.mjs.map +1 -1
  42. package/dist/pino-worker.mjs.map +1 -1
  43. package/dist/{probe-CqjOWdnP.mjs → probe-BBGkIAHT.mjs} +5 -13
  44. package/dist/probe-BBGkIAHT.mjs.map +1 -0
  45. package/dist/process-environment-DRRIdoL8.mjs.map +1 -1
  46. package/dist/{processes-BnvaDi81.mjs → processes-BL7g1Hvw.mjs} +1 -1
  47. package/dist/{processes-DOmrri5n.mjs → processes-BX-yLfvZ.mjs} +65 -34
  48. package/dist/processes-BX-yLfvZ.mjs.map +1 -0
  49. package/dist/proper-lockfile-BgKrOq5D.mjs.map +1 -1
  50. package/dist/{protocol-7m-E_iFu.mjs → protocol-DlkrVyMK.mjs} +2 -2
  51. package/dist/protocol-DlkrVyMK.mjs.map +1 -0
  52. package/dist/{protocol-COK3rM6m.mjs → protocol-G4tyEGD3.mjs} +1 -1
  53. package/dist/runtime-identity-D9V-g5M-.mjs.map +1 -1
  54. package/dist/runtime-installer.mjs +2 -2
  55. package/dist/runtime-installer.mjs.map +1 -1
  56. package/dist/runtime-manifest.json +93 -94
  57. package/dist/runtime-platform-CpunJOI4.mjs.map +1 -1
  58. package/dist/{runtime-recovery-DaRaQ8qY.mjs → runtime-recovery-CPfCb3rY.mjs} +2 -2
  59. package/dist/runtime-recovery-CPfCb3rY.mjs.map +1 -0
  60. package/dist/{runtime-recovery-DAYSaVV2.mjs → runtime-recovery-CexhaHl_.mjs} +1 -1
  61. package/dist/runtime-verification.mjs +5 -5
  62. package/dist/schemas-ZDdPV7RQ.mjs.map +1 -1
  63. package/dist/{server-CsCpY0Ft.mjs → server-CyzfkzoZ.mjs} +2 -2
  64. package/dist/server-CyzfkzoZ.mjs.map +1 -0
  65. package/dist/{shared-Bvmw_Pv0.mjs → shared-BRxN9qqm.mjs} +1 -1
  66. package/dist/{shared-8_j_xlsJ.mjs → shared-avqQD-kX.mjs} +4 -4
  67. package/dist/shared-avqQD-kX.mjs.map +1 -0
  68. package/dist/src-BSnzZMvK.mjs.map +1 -1
  69. package/dist/{stable-edge-VAAxSYSS.mjs → stable-edge-C5C0Rx5t.mjs} +3 -3
  70. package/dist/stable-edge-C5C0Rx5t.mjs.map +1 -0
  71. package/dist/{startup-log-BI24ryBR.mjs → startup-log-CVOxFwjV.mjs} +2 -2
  72. package/dist/startup-log-CVOxFwjV.mjs.map +1 -0
  73. package/dist/{startup-log-isQ9Wv18.mjs → startup-log-DUPFFTwJ.mjs} +1 -1
  74. package/dist/state-4Dz7r-_n.mjs.map +1 -1
  75. package/dist/stdio-20SBFdww.mjs.map +1 -1
  76. package/dist/{supervisor-Cu-xRt1k.mjs → supervisor-IWbA-VOB.mjs} +38 -40
  77. package/dist/supervisor-IWbA-VOB.mjs.map +1 -0
  78. package/dist/{task-storage-recovery-fSo2eskS.mjs → task-storage-recovery-CabVFMUg.mjs} +3 -3
  79. package/dist/task-storage-recovery-CabVFMUg.mjs.map +1 -0
  80. package/dist/thread-stream-worker.mjs.map +1 -1
  81. package/dist/types-kNTSQOnR.mjs.map +1 -1
  82. package/package.json +1 -1
  83. package/dist/acquire-DK4Fg36-.mjs.map +0 -1
  84. package/dist/bootstrap-CNJpiOAm.mjs.map +0 -1
  85. package/dist/cold-start-BOLlW_0n.mjs.map +0 -1
  86. package/dist/config-Busa_Dqv.mjs.map +0 -1
  87. package/dist/design-task-store-BHR54v8-.mjs.map +0 -1
  88. package/dist/edge-m9VuTeju.mjs.map +0 -1
  89. package/dist/hook-receipts-QJU3AMoY.mjs.map +0 -1
  90. package/dist/hub-control-UlA4Fncg.mjs.map +0 -1
  91. package/dist/hub-runtime-BBnfo1yd.mjs.map +0 -1
  92. package/dist/identity-CCaDEwgc.mjs.map +0 -1
  93. package/dist/probe-CqjOWdnP.mjs.map +0 -1
  94. package/dist/processes-DOmrri5n.mjs.map +0 -1
  95. package/dist/protocol-7m-E_iFu.mjs.map +0 -1
  96. package/dist/runtime-recovery-DaRaQ8qY.mjs.map +0 -1
  97. package/dist/server-CsCpY0Ft.mjs.map +0 -1
  98. package/dist/shared-8_j_xlsJ.mjs.map +0 -1
  99. package/dist/stable-edge-VAAxSYSS.mjs.map +0 -1
  100. package/dist/startup-log-BI24ryBR.mjs.map +0 -1
  101. package/dist/supervisor-Cu-xRt1k.mjs.map +0 -1
  102. package/dist/task-storage-recovery-fSo2eskS.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-CsCpY0Ft.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, h as unavailable, w as isSchemaOptional, x as getObjectShape, y as toJsonSchemaCompat } from "./protocol-7m-E_iFu.mjs";
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 { A as TEMPAD_MCP_ERROR_CODES, B as RESUMABLE_DESIGN_TASK_STATUSES, C as measureCallToolResultBytes, E as MessageFromExtensionSchema, F as DesignTaskIdSchema, G as MCP_NODE_READ_BATCH_WORK_BUDGET_MS, H as formatDesignFeedback, I as DesignTaskSchema, J as TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS, K as MCP_TOOL_INLINE_BUDGET_BYTES, L as FigmaSessionSchema, O as sameRuntimeProfile, P as DesignAnchorSchema, S as buildUploadAssetToolResult, T as LegacyMessageFromExtensionSchema, V as SetDesignAnchorParametersSchema, W as MCP_MAX_ASSET_BYTES, _ as buildApplyCanvasToolResult, a as ClientHookRequestSchema, b as buildGetScreenshotToolResult, c as GetDesignSystemResultSchema, d as UploadAssetParametersSchema, f as UploadAssetResultSchema, h as CanvasPageSnapshotSchema, i as ClientHookParamsSchema, j as AGENT_CLIENTS, k as LegacyToolCallPayloadSchema, l as GetScreenshotParametersSchema, m as ApplyCanvasResultSchema, o as GetCodeParametersSchema, p as ApplyCanvasParametersSchema, q as TEMPAD_MCP_BRIDGE_SUBPROTOCOL, s as GetDesignSystemParametersSchema, t as getMcpServerConfig, u as GetStructureParametersSchema, v as buildGetCodeToolResult, w as utf8Bytes, x as buildGetStructureToolResult, y as buildGetDesignSystemToolResult, z as ManageDesignTaskParametersSchema } from "./config-Busa_Dqv.mjs";
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-UlA4Fncg.mjs";
18
- import { n as bindRequestMetadata, r as clientDescriptor, t as ClientEventSchema } from "./identity-CCaDEwgc.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-QJU3AMoY.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-8_j_xlsJ.mjs";
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-BHR54v8-.mjs";
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 { o as listenPrivate } from "./processes-DOmrri5n.mjs";
24
+ import { F as VersionSchema, a as listenPrivate, z as compareVersions } from "./processes-BX-yLfvZ.mjs";
25
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-DaRaQ8qY.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";
@@ -4655,12 +4655,12 @@ var CodexIpc = class CodexIpc {
4655
4655
  };
4656
4656
  // src/agent-clients/codex-queue-rpc.ts
4657
4657
  /** Use the running desktop's bundled binary, never an unrelated CLI on PATH. */
4658
- async function codexQueueExecutable(context) {
4658
+ async function codexQueueExecutable(context, platform = process.platform) {
4659
4659
  const options = {
4660
4660
  timeout: 3e3,
4661
4661
  env: hostEnvironment(context)
4662
4662
  };
4663
- const { stdout } = process.platform === "win32" ? await promisify(execFile)("powershell.exe", [
4663
+ const { stdout } = platform === "win32" ? await promisify(execFile)("powershell.exe", [
4664
4664
  "-NoProfile",
4665
4665
  "-NonInteractive",
4666
4666
  "-Command",
@@ -4669,9 +4669,17 @@ async function codexQueueExecutable(context) {
4669
4669
  "-U",
4670
4670
  String(process.getuid()),
4671
4671
  "-o",
4672
- "comm="
4672
+ platform === "linux" ? "pid=,comm=" : "comm="
4673
4673
  ], options);
4674
- const paths = [...new Set(stdout.split(/\r?\n/).map((path) => path.trim()))].filter((path) => /[/\\]resources[/\\](?:codex-cli[/\\]CodexCLI\.app[/\\]Contents[/\\]MacOS[/\\])?codex(?:\.exe)?$/i.test(path));
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));
4675
4683
  if (paths.length !== 1) throw new Error("The running Codex desktop executable could not be identified.");
4676
4684
  return paths[0];
4677
4685
  }
@@ -4849,6 +4857,7 @@ async function readCodexServerQueue(conversationId, home) {
4849
4857
  database.close();
4850
4858
  }
4851
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 });
4852
4861
  throw new Error("The Codex server queue could not be checked. Comments remain saved.", { cause: error });
4853
4862
  }
4854
4863
  }
@@ -5841,6 +5850,7 @@ var CodexAppLifecycle = class {
5841
5850
  }
5842
5851
  async follow(conversationId, watch, context) {
5843
5852
  const signal = watch.controller.signal;
5853
+ let retryDelay = this.retryMs;
5844
5854
  const publish = (state) => {
5845
5855
  if (signal.aborted) return;
5846
5856
  const changed = JSON.stringify(watch.state) !== JSON.stringify(state);
@@ -5903,13 +5913,18 @@ var CodexAppLifecycle = class {
5903
5913
  return;
5904
5914
  }
5905
5915
  if (message.method !== "thread-stream-state-changed") return;
5906
- if (message.version !== 11) throw new Error("Unsupported Codex stream version.");
5916
+ if (message.version !== 11) {
5917
+ retryDelay = Math.min(retryDelay * 2, 6e4);
5918
+ end();
5919
+ return;
5920
+ }
5907
5921
  const change = object(params.change);
5908
5922
  if (!Number.isSafeInteger(change.revision)) throw new Error("Invalid Codex stream revision.");
5909
5923
  if (change.type === "snapshot") {
5910
5924
  if (revision !== void 0 && change.revision < revision) return;
5911
5925
  turns = new CodexTurnState(change.conversationState, conversationId);
5912
5926
  const state = turns.state();
5927
+ retryDelay = this.retryMs;
5913
5928
  clearTimeout(timer);
5914
5929
  awaitingSnapshot = false;
5915
5930
  revision = change.revision;
@@ -5948,7 +5963,7 @@ var CodexAppLifecycle = class {
5948
5963
  connection?.close();
5949
5964
  publish();
5950
5965
  }
5951
- if (!signal.aborted) await setTimeout$1(this.retryMs, void 0, { signal }).catch(() => {});
5966
+ if (!signal.aborted) await setTimeout$1(retryDelay, void 0, { signal }).catch(() => {});
5952
5967
  }
5953
5968
  }
5954
5969
  close() {
@@ -5956,19 +5971,6 @@ var CodexAppLifecycle = class {
5956
5971
  this.retain(/* @__PURE__ */ new Set());
5957
5972
  }
5958
5973
  };
5959
- // src/legacy-extension.ts
5960
- function extensionUpgradeRequired() {
5961
- 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 });
5962
- }
5963
- function legacyToolPayload(name, args) {
5964
- const result = LegacyToolCallPayloadSchema.safeParse({
5965
- name,
5966
- args
5967
- });
5968
- if (!result.success) throw extensionUpgradeRequired();
5969
- 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 });
5970
- return result.data;
5971
- }
5972
5974
  // src/design-tasks.ts
5973
5975
  const ENDED_STATUSES = ["completed", "cancelled"];
5974
5976
  const RUNNING_STATUSES = ["active", "stopping"];
@@ -5976,6 +5978,13 @@ const RUNNING_STATUSES = ["active", "stopping"];
5976
5978
  function getVerifiedTaskClient(record) {
5977
5979
  return record.requestId ? record.task.client : void 0;
5978
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
+ }
5979
5988
  function fail(code, message) {
5980
5989
  throw Object.assign(new Error(message), { code });
5981
5990
  }
@@ -5983,7 +5992,6 @@ function resolveDesignTarget(tasks, extensions, activeExtensionId, ownerId, task
5983
5992
  const record = taskId ? tasks.owned(taskId, ownerId, active) : void 0;
5984
5993
  if (record && explicitSessionId && explicitSessionId !== record.task.target.sessionId) fail("DESIGN_TARGET_CHANGED", "The requested Figma session does not match this task.");
5985
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);
5986
- if (extension?.legacy) throw extensionUpgradeRequired();
5987
5995
  const sessionId = explicitSessionId ?? record?.task.target.sessionId ?? extension?.sessions?.activeSessionId;
5988
5996
  const session = extension?.sessions?.sessions.find((value) => value.sessionId === sessionId);
5989
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.");
@@ -6044,6 +6052,7 @@ var DesignTasks = class {
6044
6052
  const { busy: _busy, tabId, documentId, ...target } = session;
6045
6053
  const record = {
6046
6054
  ownerId,
6055
+ ...isGenericEdge(ownerId, client) ? { edgeOwner: ownerId } : {},
6047
6056
  extensionId,
6048
6057
  requestId,
6049
6058
  ready: false,
@@ -6097,11 +6106,13 @@ var DesignTasks = class {
6097
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."}`);
6098
6107
  return record;
6099
6108
  }
6100
- /** Runtime identity may reconnect the same conversation, never a focused/last caller. */
6109
+ /** Reconnect an exact native conversation or its original transport-only edge. */
6101
6110
  attachClient(ownerId, client, capabilities, hostContext) {
6102
6111
  const mismatched = [];
6103
- if (!client.sessionId || ["other", "unknown"].includes(client.kind)) return mismatched;
6112
+ const transport = !client.sessionId || ["other", "unknown"].includes(client.kind);
6113
+ if (transport && !isGenericEdge(ownerId, client)) return mismatched;
6104
6114
  for (const record of this.records.values()) {
6115
+ if (transport && record.edgeOwner !== ownerId) continue;
6105
6116
  const verified = getVerifiedTaskClient(record);
6106
6117
  if (verified?.kind !== client.kind || verified.sessionId !== client.sessionId) continue;
6107
6118
  if (RUNNING_STATUSES.includes(record.task.status) && record.ownerId !== ownerId) continue;
@@ -6665,13 +6676,14 @@ var DesignTasks = class {
6665
6676
  ...this.filesNeedingRead.size ? { filesNeedingRead: [...this.filesNeedingRead.keys()] } : {},
6666
6677
  current: Object.fromEntries(this.currentTaskIds),
6667
6678
  ...this.fileFences.size ? { fileFences: Object.fromEntries(this.fileFences) } : {},
6668
- 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 }) => ({
6669
6680
  task: {
6670
6681
  ...task,
6671
6682
  capabilities: void 0,
6672
6683
  operation: null
6673
6684
  },
6674
6685
  requestId,
6686
+ edgeOwner,
6675
6687
  browser,
6676
6688
  resultNodeIds,
6677
6689
  retiredAt,
@@ -6855,6 +6867,7 @@ var AgentClients = class {
6855
6867
  this.pendingClaudeBindings.delete(connectionId);
6856
6868
  this.publishBinding(connectionId, next);
6857
6869
  this.bindings.set(ownerId, next);
6870
+ delete record.edgeOwner;
6858
6871
  record.ownerId = ownerId;
6859
6872
  record.task.client = next.client;
6860
6873
  this.tasks.attachClient(ownerId, next.client, { ...record.task.capabilities ?? CANVAS_ONLY }, next.hostContext);
@@ -6920,6 +6933,7 @@ var AgentClients = class {
6920
6933
  const previous = this.bindings.get(ownerId);
6921
6934
  if (previous?.client.kind === binding.client.kind) binding.turnId ??= previous.turnId;
6922
6935
  this.bindings.set(ownerId, binding);
6936
+ if (previous?.client.kind === binding.client.kind && !binding.client.sessionId) return ownerId;
6923
6937
  const mismatchedTasks = this.tasks.attachClient(ownerId, binding.client, void 0, binding.hostContext);
6924
6938
  if (mismatchedTasks.length) log.warn({
6925
6939
  ownerId,
@@ -7192,24 +7206,6 @@ var AgentClients = class {
7192
7206
  }
7193
7207
  }
7194
7208
  };
7195
- // src/asset-data-url.ts
7196
- const IMAGE_DATA_URL_PATTERN = /^data:(image\/(?:png|jpeg|gif));base64,([A-Za-z0-9+/]+={0,2})$/;
7197
- function decodeImageDataUrl(dataUrl, maxBytes = MCP_MAX_ASSET_BYTES) {
7198
- const match = IMAGE_DATA_URL_PATTERN.exec(dataUrl);
7199
- if (!match) throw new Error("Expected a base64 PNG, JPEG, or GIF data URL.");
7200
- const mimeType = match[1];
7201
- const encoded = match[2];
7202
- if (encoded.length % 4 !== 0) throw new Error("Image data URL contains invalid base64 padding.");
7203
- const bytes = Buffer.from(encoded, "base64");
7204
- if (!bytes.length) throw new Error("Generated image is empty.");
7205
- if (bytes.length > maxBytes) throw new Error(`Generated image exceeds the ${maxBytes}-byte asset limit.`);
7206
- if (bytes.toString("base64") !== encoded) throw new Error("Image data URL contains invalid base64 data.");
7207
- return {
7208
- bytes,
7209
- hash: createHash("sha256").update(bytes).digest("hex"),
7210
- mimeType
7211
- };
7212
- }
7213
7209
  // ../../node_modules/.pnpm/nanoid@6.0.2/node_modules/nanoid/url-alphabet/index.js
7214
7210
  let urlAlphabet = "57X6y3wQZNzYjJB2L_10pxbackgroundhimselfUTF-8DEMOGRAPHICSVqvt4KW9";
7215
7211
  // ../../node_modules/.pnpm/nanoid@6.0.2/node_modules/nanoid/index.js
@@ -7305,6 +7301,24 @@ function customAlphabet(alphabet, defaultSize = 21) {
7305
7301
  };
7306
7302
  }
7307
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
+ }
7308
7322
  // src/asset-utils.ts
7309
7323
  const HASH_FILENAME_PATTERN = new RegExp(`^([a-f0-9]{64}|[a-f0-9]{8})(?:\\.[a-z0-9-]+)?$`);
7310
7324
  const SAFE_IMAGE_EXTENSION_PATTERN = /^[a-z0-9-]+$/;
@@ -7330,6 +7344,207 @@ function buildAssetFilename(hash, mimeType) {
7330
7344
  function getHashFromAssetFilename(filename) {
7331
7345
  return HASH_FILENAME_PATTERN.exec(filename)?.[1] ?? null;
7332
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
+ }
7333
7548
  // src/security.ts
7334
7549
  const CHROME_EXTENSION_ORIGIN_PATTERN = /^chrome-extension:\/\/[a-p]{32}$/;
7335
7550
  function createCapabilityToken() {
@@ -7381,7 +7596,6 @@ const ASSET_MAX_CONCURRENT_DOWNLOADS = 128;
7381
7596
  function createAssetHttpServer(store, options = {}) {
7382
7597
  const config = getMcpServerConfig();
7383
7598
  const accessToken = options.accessToken ?? createCapabilityToken();
7384
- const legacyAccessToken = options.legacyAccessToken ?? createCapabilityToken();
7385
7599
  const maxAssetSizeBytes = options.maxAssetSizeBytes ?? config.maxAssetSizeBytes;
7386
7600
  const maxAssetStoreBytes = options.maxAssetStoreBytes ?? config.maxAssetStoreBytes;
7387
7601
  const maxConcurrentUploads = options.maxConcurrentUploads ?? config.maxConcurrentAssetUploads;
@@ -7422,9 +7636,9 @@ function createAssetHttpServer(store, options = {}) {
7422
7636
  server.close();
7423
7637
  port = null;
7424
7638
  }
7425
- function getBaseUrl(legacy = false) {
7639
+ function getBaseUrl() {
7426
7640
  if (port === null) throw new Error("Asset HTTP server is not running.");
7427
- return `http://${LOOPBACK_HOST}:${port}/${legacy ? legacyAccessToken : accessToken}`;
7641
+ return `http://${LOOPBACK_HOST}:${port}/${accessToken}`;
7428
7642
  }
7429
7643
  function handleRequest(req, res) {
7430
7644
  const startedAt = Date.now();
@@ -7458,8 +7672,7 @@ function createAssetHttpServer(store, options = {}) {
7458
7672
  return;
7459
7673
  }
7460
7674
  const segments = url.pathname.split("/").filter(Boolean);
7461
- const legacy = secretsEqual(segments[0] ?? "", legacyAccessToken);
7462
- if (segments.length !== 3 || !legacy && !secretsEqual(segments[0] ?? "", accessToken) || segments[1] !== "assets") {
7675
+ if (segments.length !== 3 || !secretsEqual(segments[0] ?? "", accessToken) || segments[1] !== "assets") {
7463
7676
  sendError(res, 404, "Not Found");
7464
7677
  return;
7465
7678
  }
@@ -7490,7 +7703,7 @@ function createAssetHttpServer(store, options = {}) {
7490
7703
  return;
7491
7704
  }
7492
7705
  if (req.method === "POST") {
7493
- if (!legacy && hash.length !== 64) {
7706
+ if (hash.length !== 64) {
7494
7707
  sendError(res, 400, "Legacy Asset Hashes Are Read-Only");
7495
7708
  return;
7496
7709
  }
@@ -7573,8 +7786,6 @@ function createAssetHttpServer(store, options = {}) {
7573
7786
  return;
7574
7787
  }
7575
7788
  const mimeType = normalizeMimeType(getHeader(req, "content-type"));
7576
- const filename = buildAssetFilename(hash, mimeType);
7577
- const filePath = join(ASSET_DIR, filename);
7578
7789
  const width = parseInt(getHeader(req, "x-asset-width") ?? "", 10);
7579
7790
  const height = parseInt(getHeader(req, "x-asset-height") ?? "", 10);
7580
7791
  const themeable = getHeader(req, "x-asset-themeable") === "true";
@@ -7582,7 +7793,41 @@ function createAssetHttpServer(store, options = {}) {
7582
7793
  if (Number.isFinite(width) && width > 0) metadata.width = width;
7583
7794
  if (Number.isFinite(height) && height > 0) metadata.height = height;
7584
7795
  if (themeable) metadata.themeable = true;
7585
- const assetMetadata = Object.keys(metadata).length ? metadata : void 0;
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));
7586
7831
  const reuseExisting = (record) => {
7587
7832
  if (assetMetadata) record.metadata = {
7588
7833
  ...record.metadata,
@@ -7591,36 +7836,54 @@ function createAssetHttpServer(store, options = {}) {
7591
7836
  if (record.mimeType !== mimeType) record.mimeType = mimeType;
7592
7837
  record.lastAccess = Date.now();
7593
7838
  store.upsert(record);
7594
- sendJson(res, 200, { message: "Asset Already Exists" });
7839
+ reply(200, { message: "Asset Already Exists" });
7595
7840
  };
7596
7841
  const existing = store.get(hash);
7597
- if (existing && hash.length === 64) {
7842
+ if (existing) {
7598
7843
  let existingPath = existing.filePath;
7599
7844
  if (!existsSync(existingPath) && existsSync(filePath)) {
7600
7845
  existing.filePath = filePath;
7601
7846
  existingPath = filePath;
7602
7847
  }
7603
7848
  if (existsSync(existingPath)) {
7604
- req.resume();
7849
+ stream.resume();
7605
7850
  reuseExisting(existing);
7606
7851
  return;
7607
7852
  }
7608
7853
  }
7609
7854
  if (activeUploads >= maxConcurrentUploads) {
7610
- req.resume();
7611
- res.setHeader("Connection", "close");
7612
- sendError(res, 429, "Too Many Concurrent Uploads");
7855
+ stream.resume();
7856
+ reply(429, { error: "Too Many Concurrent Uploads" });
7613
7857
  return;
7614
7858
  }
7615
7859
  const reservationBytes = declaredSize ?? maxAssetSizeBytes;
7616
- if (getStoredAssetBytes(store, hash) + reservedUploadBytes + reservationBytes > maxAssetStoreBytes) {
7617
- req.resume();
7618
- sendError(res, 507, "Asset Store Quota Exceeded");
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);
7619
7882
  return;
7620
7883
  }
7621
7884
  const tmpPath = `${filePath}.tmp.${nanoid()}`;
7622
7885
  const writeStream = createWriteStream(tmpPath);
7623
- const hasher = createHash("sha256");
7886
+ const hasher = localImport ? void 0 : createHash("sha256");
7624
7887
  let size = 0;
7625
7888
  activeUploads += 1;
7626
7889
  options.onActivity?.();
@@ -7641,62 +7904,52 @@ function createAssetHttpServer(store, options = {}) {
7641
7904
  callback(/* @__PURE__ */ new Error("PayloadTooLarge"));
7642
7905
  return;
7643
7906
  }
7644
- hasher.update(chunk);
7907
+ hasher?.update(chunk);
7645
7908
  callback(null, chunk);
7646
7909
  } });
7647
- pipeline(req, monitor, writeStream, (err) => {
7910
+ const abort = () => stream.destroy();
7911
+ localImport?.addEventListener("abort", abort, { once: true });
7912
+ pipeline(stream, monitor, writeStream, (err) => {
7913
+ localImport?.removeEventListener("abort", abort);
7648
7914
  activeUploads -= 1;
7649
7915
  options.onActivity?.();
7650
7916
  reservedUploadBytes -= reservationBytes;
7651
7917
  if (err) {
7652
7918
  cleanup();
7653
- if (err.message === "PayloadTooLarge") sendError(res, 413, "Payload Too Large");
7919
+ if (err.message === "PayloadTooLarge") reply(413, { error: "Payload Too Large" });
7654
7920
  else if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
7655
7921
  log.warn({ hash }, "Upload request closed prematurely.");
7656
- sendError(res, 400, "Upload Incomplete");
7922
+ reply(400, { error: "Upload Incomplete" });
7657
7923
  } else {
7658
7924
  log.error({
7659
7925
  error: err,
7660
7926
  hash
7661
7927
  }, "Upload pipeline failed.");
7662
- if (!res.headersSent) sendError(res, 500, "Internal Server Error");
7928
+ reply(500, { error: "Internal Server Error" });
7663
7929
  }
7664
7930
  return;
7665
7931
  }
7666
- const computedHash = hasher.digest("hex");
7667
- if (computedHash.slice(0, hash.length) !== hash) {
7932
+ if (localImport?.aborted) {
7933
+ cleanup();
7934
+ reply(400, { error: "Upload Incomplete" });
7935
+ return;
7936
+ }
7937
+ if (hasher && hasher.digest("hex") !== hash) {
7668
7938
  cleanup();
7669
- sendError(res, 400, "Hash Mismatch");
7939
+ reply(400, { error: "Hash Mismatch" });
7670
7940
  return;
7671
7941
  }
7672
- if (getStoredAssetBytes(store, hash) + reservedUploadBytes + size > maxAssetStoreBytes) {
7942
+ const denied = quota(size);
7943
+ if (denied) {
7673
7944
  cleanup();
7674
- sendError(res, 507, "Asset Store Quota Exceeded");
7945
+ reply(507, denied);
7675
7946
  return;
7676
7947
  }
7677
7948
  try {
7678
7949
  const previous = store.get(hash);
7679
7950
  if (previous && existsSync(previous.filePath)) {
7680
- if (hash.length === 64) {
7681
- cleanup();
7682
- reuseExisting(previous);
7683
- return;
7684
- }
7685
- const previousHash = createHash("sha256").update(readFileSync(previous.filePath)).digest("hex");
7686
7951
  cleanup();
7687
- if (previousHash !== computedHash) {
7688
- sendError(res, 409, "Legacy Asset Hash Collision; update the TemPad Dev extension");
7689
- return;
7690
- }
7691
- store.upsert({
7692
- ...previous,
7693
- metadata: {
7694
- ...previous.metadata,
7695
- ...assetMetadata
7696
- },
7697
- lastAccess: Date.now()
7698
- });
7699
- sendJson(res, 200, { message: "Asset Already Exists" });
7952
+ reuseExisting(previous);
7700
7953
  return;
7701
7954
  }
7702
7955
  renameSync(tmpPath, filePath);
@@ -7706,7 +7959,7 @@ function createAssetHttpServer(store, options = {}) {
7706
7959
  hash
7707
7960
  }, "Failed to rename temp file to asset.");
7708
7961
  cleanup();
7709
- sendError(res, 500, "Internal Server Error");
7962
+ reply(500, { error: "Internal Server Error" });
7710
7963
  return;
7711
7964
  }
7712
7965
  store.upsert({
@@ -7719,8 +7972,8 @@ function createAssetHttpServer(store, options = {}) {
7719
7972
  log.info({
7720
7973
  hash,
7721
7974
  size
7722
- }, "Stored uploaded asset via HTTP.");
7723
- sendJson(res, 201, {
7975
+ }, "Stored uploaded asset.");
7976
+ reply(201, {
7724
7977
  message: "Created",
7725
7978
  hash,
7726
7979
  size
@@ -7731,7 +7984,7 @@ function createAssetHttpServer(store, options = {}) {
7731
7984
  if (!requestUrl) return requestUrl;
7732
7985
  try {
7733
7986
  const segments = new URL$1(requestUrl, `http://${LOOPBACK_HOST}`).pathname.split("/").filter(Boolean);
7734
- if (segments.length >= 1 && (secretsEqual(segments[0] ?? "", accessToken) || secretsEqual(segments[0] ?? "", legacyAccessToken))) segments[0] = "<capability>";
7987
+ if (segments[0]) segments[0] = "<capability>";
7735
7988
  return `/${segments.join("/")}`;
7736
7989
  } catch {
7737
7990
  return "<invalid>";
@@ -7748,6 +8001,7 @@ function createAssetHttpServer(store, options = {}) {
7748
8001
  res.end(JSON.stringify(payload));
7749
8002
  }
7750
8003
  return {
8004
+ importImage,
7751
8005
  start,
7752
8006
  stop,
7753
8007
  getBaseUrl,
@@ -7773,185 +8027,6 @@ function getStoredAssetBytes(store, excludeHash) {
7773
8027
  return Number.isFinite(record.size) && record.size > 0 ? total + record.size : total;
7774
8028
  }, 0);
7775
8029
  }
7776
- // src/asset-store.ts
7777
- const INDEX_FILENAME = "assets.json";
7778
- const DEFAULT_INDEX_PATH = join(ASSET_DIR, INDEX_FILENAME);
7779
- const IMAGE_MIME_TYPES = {
7780
- png: "image/png",
7781
- jpg: "image/jpeg",
7782
- jpeg: "image/jpeg",
7783
- svg: "image/svg+xml",
7784
- gif: "image/gif",
7785
- webp: "image/webp",
7786
- avif: "image/avif"
7787
- };
7788
- function readIndex(indexPath) {
7789
- if (!existsSync(indexPath)) return [];
7790
- try {
7791
- const raw = readFileSync(indexPath, "utf8").trim();
7792
- if (!raw) return [];
7793
- const parsed = JSON.parse(raw);
7794
- return Array.isArray(parsed) ? parsed : [];
7795
- } catch (error) {
7796
- log.warn({
7797
- error,
7798
- indexPath
7799
- }, "Failed to read asset catalog; starting fresh.");
7800
- return [];
7801
- }
7802
- }
7803
- function writeIndex(indexPath, values) {
7804
- const payload = JSON.stringify(values, null, 2);
7805
- const temporary = `${indexPath}.tmp.${process.pid}`;
7806
- writeFileSync(temporary, payload, {
7807
- encoding: "utf8",
7808
- mode: 384
7809
- });
7810
- renameSync(temporary, indexPath);
7811
- }
7812
- function createAssetStore(options = {}) {
7813
- ensureDir(ASSET_DIR);
7814
- const indexPath = options.indexPath ?? DEFAULT_INDEX_PATH;
7815
- ensureFile(indexPath);
7816
- const records = /* @__PURE__ */ new Map();
7817
- let persistTimer = null;
7818
- function loadExisting() {
7819
- const list = readIndex(indexPath);
7820
- for (const record of list) if (record?.hash && record?.filePath) records.set(record.hash, record);
7821
- }
7822
- function persist() {
7823
- if (persistTimer) return;
7824
- persistTimer = setTimeout(() => {
7825
- persistTimer = null;
7826
- try {
7827
- writeIndex(indexPath, [...records.values()]);
7828
- } catch (error) {
7829
- log.warn({
7830
- error,
7831
- indexPath
7832
- }, "Could not persist asset catalog; retrying.");
7833
- persist();
7834
- }
7835
- }, 5e3);
7836
- if (typeof persistTimer.unref === "function") persistTimer.unref();
7837
- }
7838
- function flush() {
7839
- if (persistTimer) {
7840
- clearTimeout(persistTimer);
7841
- persistTimer = null;
7842
- }
7843
- writeIndex(indexPath, [...records.values()]);
7844
- }
7845
- function list() {
7846
- return [...records.values()];
7847
- }
7848
- function has(hash) {
7849
- return records.has(hash);
7850
- }
7851
- function get(hash) {
7852
- return records.get(hash);
7853
- }
7854
- function upsert(input) {
7855
- const now = Date.now();
7856
- const record = {
7857
- ...input,
7858
- uploadedAt: input.uploadedAt ?? now,
7859
- lastAccess: input.lastAccess ?? now
7860
- };
7861
- records.set(record.hash, record);
7862
- persist();
7863
- return record;
7864
- }
7865
- function touch(hash) {
7866
- const existing = records.get(hash);
7867
- if (!existing) return void 0;
7868
- existing.lastAccess = Date.now();
7869
- persist();
7870
- return existing;
7871
- }
7872
- function remove(hash, { removeFile = true } = {}) {
7873
- const record = records.get(hash);
7874
- if (!record) return;
7875
- if (removeFile) try {
7876
- rmSync(record.filePath, { force: true });
7877
- } catch (error) {
7878
- log.warn({
7879
- hash,
7880
- error
7881
- }, "Failed to remove asset file on delete.");
7882
- return;
7883
- }
7884
- records.delete(hash);
7885
- persist();
7886
- }
7887
- function reconcile() {
7888
- let changed = false;
7889
- for (const [hash, record] of records) if (!existsSync(record.filePath)) {
7890
- records.delete(hash);
7891
- changed = true;
7892
- }
7893
- try {
7894
- const files = readdirSync(ASSET_DIR);
7895
- const now = Date.now();
7896
- for (const file of files) {
7897
- if (file === INDEX_FILENAME) continue;
7898
- if (file.includes(".tmp.")) {
7899
- try {
7900
- const filePath = join(ASSET_DIR, file);
7901
- if (now - statSync(filePath).mtimeMs > 36e5) {
7902
- rmSync(filePath, { force: true });
7903
- log.info({ file }, "Cleaned up stale temp file.");
7904
- }
7905
- } catch (e) {
7906
- log.debug({
7907
- error: e,
7908
- file
7909
- }, "Failed to cleanup stale temp file.");
7910
- }
7911
- continue;
7912
- }
7913
- const hash = getHashFromAssetFilename(file);
7914
- if (!hash) continue;
7915
- if (!records.has(hash)) {
7916
- const filePath = join(ASSET_DIR, file);
7917
- try {
7918
- const stat = statSync(filePath);
7919
- records.set(hash, {
7920
- hash,
7921
- filePath,
7922
- mimeType: IMAGE_MIME_TYPES[file.split(".").at(-1) ?? ""] ?? "application/octet-stream",
7923
- size: stat.size,
7924
- uploadedAt: stat.birthtimeMs,
7925
- lastAccess: stat.atimeMs
7926
- });
7927
- changed = true;
7928
- log.info({ hash }, "Recovered orphan asset file.");
7929
- } catch (e) {
7930
- log.warn({
7931
- error: e,
7932
- file
7933
- }, "Failed to stat orphan file.");
7934
- }
7935
- }
7936
- }
7937
- } catch (error) {
7938
- log.warn({ error }, "Failed to scan asset directory for orphans.");
7939
- }
7940
- if (changed) flush();
7941
- }
7942
- loadExisting();
7943
- reconcile();
7944
- return {
7945
- list,
7946
- has,
7947
- get,
7948
- upsert,
7949
- touch,
7950
- remove,
7951
- reconcile,
7952
- flush
7953
- };
7954
- }
7955
8030
  // src/extension-registry.ts
7956
8031
  var ExtensionRegistry = class {
7957
8032
  #autoActivateGraceMs;
@@ -8024,22 +8099,18 @@ function unrefTimer(timer) {
8024
8099
  if (typeof handle.unref === "function") handle.unref();
8025
8100
  }
8026
8101
  // src/extension-socket.ts
8027
- const CHECKOUT_HANDSHAKE_TIMEOUT_MS = 5e3;
8102
+ const HANDSHAKE_TIMEOUT_MS = 5e3;
8103
+ const BRIDGE_UPGRADE_MESSAGE = "Update to TemPad Dev extension 1.0 or later and reload Figma.";
8028
8104
  function attachExtensionSocket(ws, options) {
8029
8105
  const extension = {
8030
8106
  id: options.createId(),
8031
8107
  origin: options.origin.toLowerCase(),
8032
8108
  connectedAt: (/* @__PURE__ */ new Date()).toISOString(),
8033
- legacy: ws.protocol !== TEMPAD_MCP_BRIDGE_SUBPROTOCOL,
8034
8109
  ws
8035
8110
  };
8036
8111
  const checkout = options.runtimeProfile?.kind === "checkout";
8037
- const handshakeTimer = checkout ? setTimeout(() => ws.close(1008, "Checkout runtime handshake timed out."), CHECKOUT_HANDSHAKE_TIMEOUT_MS) : void 0;
8038
- handshakeTimer?.unref();
8039
- if (!checkout) {
8040
- options.registry.add(extension);
8041
- options.onConnected?.(extension.id);
8042
- }
8112
+ const handshakeTimer = setTimeout(() => ws.close(1008, "Runtime handshake timed out."), HANDSHAKE_TIMEOUT_MS);
8113
+ handshakeTimer.unref();
8043
8114
  const registered = {
8044
8115
  id: extension.id,
8045
8116
  protocolVersion: 15,
@@ -8051,14 +8122,12 @@ function attachExtensionSocket(ws, options) {
8051
8122
  } : {},
8052
8123
  type: "registered"
8053
8124
  };
8054
- ws.send(JSON.stringify(extension.legacy ? {
8055
- type: "registered",
8056
- id: extension.id
8057
- } : registered));
8058
- if (!checkout) {
8059
- options.onStateChange();
8060
- scheduleAutoActivation(options);
8061
- }
8125
+ ws.send(JSON.stringify(registered));
8126
+ if (!checkout) ws.send(JSON.stringify({
8127
+ type: "state",
8128
+ activeId: null,
8129
+ assetServerUrl: options.assetServerUrl
8130
+ }));
8062
8131
  ws.on("message", (raw, isBinary) => {
8063
8132
  if (ws.readyState !== import_websocket.default.OPEN) return;
8064
8133
  if (isBinary) {
@@ -8079,9 +8148,15 @@ function attachExtensionSocket(ws, options) {
8079
8148
  });
8080
8149
  return;
8081
8150
  }
8082
- const parseResult = (extension.legacy ? LegacyMessageFromExtensionSchema : MessageFromExtensionSchema).safeParse(parsedJson);
8151
+ const parseResult = MessageFromExtensionSchema.safeParse(parsedJson);
8083
8152
  if (!parseResult.success) {
8084
- if (parsedJson && typeof parsedJson === "object" && "type" in parsedJson && parsedJson.type === "toolResult" && "id" in parsedJson && typeof parsedJson.id === "string") options.onToolError(parsedJson.id, extension.id, {
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, {
8085
8160
  code: "EXTENSION_DISCONNECTED",
8086
8161
  message: "The extension returned an invalid result. A canvas write may have completed; inspect the canvas before retrying."
8087
8162
  });
@@ -8093,11 +8168,7 @@ function attachExtensionSocket(ws, options) {
8093
8168
  return;
8094
8169
  }
8095
8170
  const message = parseResult.data;
8096
- if (checkout && !extension.runtime && message.type !== "runtimeHello") {
8097
- ws.close(1008, "Checkout runtime handshake required.");
8098
- return;
8099
- }
8100
- if (!extension.legacy && !extension.runtime && (message.type === "sessions" || message.type === "designAction" || message.type === "toolCompletion")) {
8171
+ if (!extension.runtime && message.type !== "runtimeHello") {
8101
8172
  ws.close(1008, "Runtime handshake required.");
8102
8173
  return;
8103
8174
  }
@@ -8154,12 +8225,11 @@ function attachExtensionSocket(ws, options) {
8154
8225
  ws.close(1008, "Terminal receipts are unavailable.");
8155
8226
  return;
8156
8227
  }
8157
- const protocolVersion = message.protocolVersion ?? 13;
8158
- if (!TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) {
8159
- 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}`);
8160
8230
  break;
8161
8231
  }
8162
- if (extension.runtime && (extension.runtime.version !== message.extensionVersion || extension.runtime.fingerprint !== message.extensionRuntimeFingerprint || extension.runtime.protocolVersion !== protocolVersion || extension.runtime.terminalReceipts !== message.terminalReceipts || extension.runtime.durableTerminalReceipts !== message.durableTerminalReceipts)) {
8232
+ if (extension.runtime && (extension.runtime.version !== message.extensionVersion || extension.runtime.fingerprint !== message.extensionRuntimeFingerprint || extension.runtime.terminalReceipts !== message.terminalReceipts || extension.runtime.durableTerminalReceipts !== message.durableTerminalReceipts)) {
8163
8233
  options.onProtocolWarning?.({
8164
8234
  error: /* @__PURE__ */ new Error("Extension changed runtime identity on an open connection."),
8165
8235
  extensionId: extension.id,
@@ -8171,13 +8241,12 @@ function attachExtensionSocket(ws, options) {
8171
8241
  const firstHello = !extension.runtime;
8172
8242
  clearTimeout(handshakeTimer);
8173
8243
  extension.runtime = {
8174
- protocolVersion,
8175
8244
  version: message.extensionVersion,
8176
8245
  fingerprint: message.extensionRuntimeFingerprint,
8177
8246
  ...message.terminalReceipts ? { terminalReceipts: true } : {},
8178
8247
  ...message.terminalReceipts && message.durableTerminalReceipts ? { durableTerminalReceipts: true } : {}
8179
8248
  };
8180
- if (checkout && firstHello) {
8249
+ if (firstHello) {
8181
8250
  options.registry.add(extension);
8182
8251
  options.onConnected?.(extension.id);
8183
8252
  options.onStateChange();
@@ -8203,7 +8272,6 @@ function attachExtensionSocket(ws, options) {
8203
8272
  options.onStateChange();
8204
8273
  scheduleAutoActivation(options);
8205
8274
  });
8206
- if (checkout && extension.legacy) ws.close(1008, "Checkout runtime identity required.");
8207
8275
  return extension;
8208
8276
  }
8209
8277
  function scheduleAutoActivation(options) {
@@ -8219,7 +8287,7 @@ function rawDataToBuffer(raw) {
8219
8287
  return Buffer.concat(raw);
8220
8288
  }
8221
8289
  // src/instructions.md?raw
8222
- 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 a known Frame 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";
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";
8223
8291
  // src/request.ts
8224
8292
  const pendingCalls = /* @__PURE__ */ new Map();
8225
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.";
@@ -8480,7 +8548,7 @@ const CONNECTIVITY_TROUBLESHOOTING_LINES = [
8480
8548
  "Troubleshooting:",
8481
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.",
8482
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.",
8483
- "- 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."
8484
8552
  ];
8485
8553
  const MULTI_SELECTION_TROUBLESHOOTING_LINE = "Tip: Select one or more visible nodes, or pass nodeIds (nodeId for a single node).";
8486
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.";
@@ -8520,7 +8588,7 @@ const TOOL_DEFS = [
8520
8588
  }),
8521
8589
  extTool({
8522
8590
  name: "set_design_anchor",
8523
- description: "Choose an existing Frame as this task’s stable design region once its scope is known, or explicitly switch to a different region. Beginning a task does not require an anchor; 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 frame, page, viewport, or selection.",
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.",
8524
8592
  annotations: ASSET_WRITE_ANNOTATIONS,
8525
8593
  parameters: SetDesignAnchorParametersSchema,
8526
8594
  target: "extension",
@@ -8695,6 +8763,45 @@ function createInlineBudgetExceededToolResponse(toolName, actualBytes) {
8695
8763
  }]
8696
8764
  };
8697
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
+ }
8698
8805
  function toCallToolResult(result) {
8699
8806
  return result;
8700
8807
  }
@@ -8708,29 +8815,10 @@ function getBudgetRetryGuidance(toolName) {
8708
8815
  case "get_code": return "Reduce selection size or request a smaller nodeId subtree and retry.";
8709
8816
  case "get_design_system": return "Continue from another catalog cursor or avoid the oversized exact definition.";
8710
8817
  case "get_structure": return "Reduce selection size or pass a smaller depth and retry.";
8711
- case "get_token_defs": return "Reduce requested names or split them into smaller batches and retry.";
8712
8818
  case "get_screenshot": return "Pass a smaller nodeId and retry.";
8713
- case "get_assets": return "Request fewer hashes in a single call and retry.";
8714
8819
  case "upload_asset": return "Generate a smaller PNG, JPEG, or GIF and retry without printing its data URL.";
8715
8820
  }
8716
8821
  }
8717
- // src/versioned-extension.ts
8718
- const NODE_READS = /* @__PURE__ */ new Set([
8719
- "get_code",
8720
- "get_screenshot",
8721
- "get_structure"
8722
- ]);
8723
- /** Preserve protocol 13's wire arguments; never silently strip a newer read option. */
8724
- function assertVersionedToolSupport(protocolVersion, name, args) {
8725
- if (protocolVersion !== 13) return;
8726
- 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;
8727
- 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 });
8728
- }
8729
- function versionedReadNotice(protocolVersion, name) {
8730
- if (protocolVersion !== 13) return void 0;
8731
- 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.";
8732
- 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.";
8733
- }
8734
8822
  // src/websocket-server.ts
8735
8823
  async function startExtensionWebSocketServer({ maxPayloadBytes, maxConnections, originPolicy, portCandidates, onPortInUse, onConnectionLimit, onRejectedHandshake }) {
8736
8824
  for (const candidate of portCandidates) {
@@ -8745,7 +8833,7 @@ async function startExtensionWebSocketServer({ maxPayloadBytes, maxConnections,
8745
8833
  return false;
8746
8834
  }
8747
8835
  const protocol = info.req.headers["sec-websocket-protocol"];
8748
- const allowed = isAllowedWebSocketRequest(info.origin, info.req.url, originPolicy) && (!protocol || protocol.split(",").some((value) => value.trim() === "tempad-mcp"));
8836
+ const allowed = isAllowedWebSocketRequest(info.origin, info.req.url, originPolicy) && !!protocol?.split(",").some((value) => value.trim() === "tempad-mcp");
8749
8837
  if (!allowed) onRejectedHandshake?.(info.origin, info.req.url);
8750
8838
  return allowed;
8751
8839
  }
@@ -8808,7 +8896,7 @@ async function startHub(options = {}) {
8808
8896
  "get_screenshot",
8809
8897
  "get_design_system"
8810
8898
  ]);
8811
- const { wsPortCandidates, toolTimeoutMs, getCodeTimeoutMs, getDesignSystemTimeoutMs, pageStructureTimeoutMs, applyCanvasTimeoutMs, maxPayloadBytes, maxAssetSizeBytes, maxExtensionConnections, autoActivateGraceMs, assetTtlMs, allowedExtensionOrigins } = getMcpServerConfig(RUNTIME_PROFILE);
8899
+ const { wsPortCandidates, toolTimeoutMs, getCodeTimeoutMs, getDesignSystemTimeoutMs, pageStructureTimeoutMs, applyCanvasTimeoutMs, maxPayloadBytes, maxExtensionConnections, autoActivateGraceMs, assetTtlMs, allowedExtensionOrigins } = getMcpServerConfig(RUNTIME_PROFILE);
8812
8900
  const extensionOriginPolicy = createExtensionOriginPolicy(allowedExtensionOrigins);
8813
8901
  const runtimeControl = options.prototype ? new HubControl(options.prototype.secret, void 0, {
8814
8902
  paused: options.prototype.paused,
@@ -9093,7 +9181,6 @@ async function startHub(options = {}) {
9093
9181
  ...tool,
9094
9182
  handler: async () => {
9095
9183
  const result = { sessions: extensionRegistry.list().flatMap((value) => value.sessions?.sessions ?? []) };
9096
- if (!result.sessions.length && extensionRegistry.list().some((value) => value.legacy)) throw extensionUpgradeRequired();
9097
9184
  return {
9098
9185
  content: [{
9099
9186
  type: "text",
@@ -9148,36 +9235,22 @@ async function startHub(options = {}) {
9148
9235
  log.info("Asset TTL cleanup disabled (TEMPAD_MCP_ASSET_TTL_MS=0).");
9149
9236
  return;
9150
9237
  }
9151
- pruneExpiredAssets(assetTtlMs);
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();
9152
9246
  const intervalMs = Math.min(assetTtlMs, 864e5);
9153
- assetCleanupTimer = setInterval(() => {
9154
- pruneExpiredAssets(assetTtlMs);
9155
- }, intervalMs);
9247
+ assetCleanupTimer = setInterval(sweep, intervalMs);
9156
9248
  unrefTimer(assetCleanupTimer);
9157
9249
  log.info({
9158
9250
  ttlMs: assetTtlMs,
9159
9251
  intervalMs
9160
9252
  }, "Asset TTL cleanup enabled.");
9161
9253
  }
9162
- function pruneExpiredAssets(ttlMs) {
9163
- const now = Date.now();
9164
- let removed = 0;
9165
- let checked = 0;
9166
- for (const record of assetStore.list()) {
9167
- checked += 1;
9168
- const lastAccess = Number.isFinite(record.lastAccess) ? record.lastAccess : record.uploadedAt;
9169
- if (!lastAccess) continue;
9170
- if (now - lastAccess > ttlMs) {
9171
- assetStore.remove(record.hash);
9172
- removed += 1;
9173
- }
9174
- }
9175
- log.info({
9176
- checked,
9177
- removed,
9178
- ttlMs
9179
- }, "Asset TTL sweep completed.");
9180
- }
9181
9254
  function publishDesignTask({ task, extensionId }) {
9182
9255
  const message = JSON.stringify({
9183
9256
  type: "designTaskState",
@@ -9330,19 +9403,18 @@ async function startHub(options = {}) {
9330
9403
  const schema = tool.parameters;
9331
9404
  const connectionId = ownerId;
9332
9405
  const isCanvasWrite = tool.name === "apply_canvas";
9406
+ const present = (result, preserveNotices = false) => presentClientToolResult(tool.name, mcp.server.getClientVersion(), result, preserveNotices);
9333
9407
  const handler = async (args, extra) => {
9334
9408
  const activity = Symbol();
9335
9409
  let requestId;
9336
9410
  let readTarget;
9337
9411
  try {
9338
- if (runtimeControl && !runtimeControl.admitting()) throw unavailable();
9339
9412
  noteActivity();
9340
9413
  activeCalls.set(activity, Date.now() + Math.max(toolTimeoutMs, getCodeTimeoutMs, getDesignSystemTimeoutMs, pageStructureTimeoutMs, applyCanvasTimeoutMs * 2) + MCP_NODE_READ_BATCH_WORK_BUDGET_MS);
9341
9414
  extra.signal.throwIfAborted();
9342
9415
  const ownerId = await agentClients.owner(connectionId, extra._meta, mcp.server.getClientVersion());
9343
9416
  extra.signal.throwIfAborted();
9344
- const parsed = schema.parse(args);
9345
- const { taskId, taskEpoch, ...parsedArgs } = parsed;
9417
+ const { taskId, taskEpoch, ...parsedArgs } = schema.parse(args);
9346
9418
  const readSessionId = EXACT_SESSION_READ_TOOLS.has(tool.name) ? getRecordProperty(parsedArgs, "sessionId") : void 0;
9347
9419
  const explicitSessionId = typeof readSessionId === "string" ? readSessionId : void 0;
9348
9420
  if (explicitSessionId) delete parsedArgs.sessionId;
@@ -9354,22 +9426,6 @@ async function startHub(options = {}) {
9354
9426
  else if (isCanvasWrite) timeoutMs = applyCanvasTimeoutMs;
9355
9427
  if ((tool.name === "get_code" || tool.name === "get_screenshot") && !getRecordProperty(parsedArgs, "nodeId")) timeoutMs += MCP_NODE_READ_BATCH_WORK_BUDGET_MS;
9356
9428
  activeCalls.set(activity, Date.now() + timeoutMs * (isCanvasWrite ? 2 : 1));
9357
- const legacy = !taskId && !explicitSessionId ? extensionRegistry.getActive() : void 0;
9358
- if (legacy?.legacy) {
9359
- const payload = legacyToolPayload(tool.name, parsed);
9360
- const registration = register(legacy.id, timeoutMs, { signal: extra.signal });
9361
- requestId = registration.requestId;
9362
- try {
9363
- legacy.ws.send(JSON.stringify({
9364
- type: "toolCall",
9365
- id: requestId,
9366
- payload
9367
- }));
9368
- } catch (error) {
9369
- reject(requestId, legacy.id, coerceToolError(error));
9370
- }
9371
- return createToolResponse(tool, await registration.promise);
9372
- }
9373
9429
  const { extension: activeExt, session } = resolveDesignRoute(ownerId, taskId, true, explicitSessionId);
9374
9430
  readTarget = {
9375
9431
  fileKey: session.fileKey,
@@ -9378,8 +9434,6 @@ async function startHub(options = {}) {
9378
9434
  const runtimeIssues = getExtensionRuntimeIssues(activeExt.runtime);
9379
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.`);
9380
9436
  const runtime = isCanvasWrite ? buildAuthoringRuntimeEvidence(activeExt) : void 0;
9381
- const protocolVersion = activeExt.runtime.protocolVersion;
9382
- assertVersionedToolSupport(protocolVersion, tool.name, parsedArgs);
9383
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.");
9384
9438
  designTasks.checkOperation(ownerId, session, taskId, isCanvasWrite);
9385
9439
  const registration = register(activeExt.id, timeoutMs, {
@@ -9443,16 +9497,14 @@ async function startHub(options = {}) {
9443
9497
  }
9444
9498
  }
9445
9499
  const readEvidence = hasCanvasReadEvidence(tool.name, payload);
9446
- const response = createToolResponse(tool, payload, {
9447
- runtime,
9448
- notice: versionedReadNotice(protocolVersion, tool.name)
9449
- });
9500
+ const response = createToolResponse(tool, payload, { runtime });
9450
9501
  if (!response.isError && readGeneration !== void 0) designTasks.acknowledgeFileRead(session.fileKey, readGeneration);
9451
9502
  if (!response.isError && readEvidence) {
9452
9503
  if (taskId) designTasks.acknowledgeRead(taskId, ownerId, taskEpoch);
9453
9504
  designTasks.acknowledgeFileRead(session.fileKey);
9454
9505
  }
9455
- return withCanvasReadNotice(tool.name, response, readTarget);
9506
+ const final = withCanvasReadNotice(tool.name, response, readTarget);
9507
+ return present(final, final !== response);
9456
9508
  } catch (error) {
9457
9509
  const normalized = coerceToolError(error);
9458
9510
  log.error({
@@ -9500,7 +9552,6 @@ async function startHub(options = {}) {
9500
9552
  const registerHandler = async (args, extra) => {
9501
9553
  const activity = Symbol();
9502
9554
  try {
9503
- if (runtimeControl && !runtimeControl.admitting()) throw unavailable();
9504
9555
  noteActivity();
9505
9556
  activeCalls.set(activity, Date.now() + toolTimeoutMs);
9506
9557
  extra.signal.throwIfAborted();
@@ -9548,7 +9599,7 @@ async function startHub(options = {}) {
9548
9599
  });
9549
9600
  });
9550
9601
  }
9551
- function createToolResponse(tool, payload, { runtime, includeLocalAssetPaths = true, notice } = {}) {
9602
+ function createToolResponse(tool, payload, { runtime, includeLocalAssetPaths = true } = {}) {
9552
9603
  const toolName = tool.name;
9553
9604
  const enrichedPayload = (() => {
9554
9605
  if (includeLocalAssetPaths && (toolName === "get_code" || toolName === "get_screenshot")) {
@@ -9585,18 +9636,10 @@ async function startHub(options = {}) {
9585
9636
  }]
9586
9637
  };
9587
9638
  }
9588
- if (notice) rawResult = {
9589
- ...rawResult,
9590
- content: [{
9591
- type: "text",
9592
- text: notice
9593
- }, ...rawResult.content]
9594
- };
9595
9639
  const resultBytes = measureCallToolResultBytes(rawResult);
9596
9640
  if (resultBytes > 65536) {
9597
9641
  if (includeLocalAssetPaths && (toolName === "get_code" || toolName === "get_screenshot")) return createToolResponse(tool, payload, {
9598
9642
  runtime,
9599
- notice,
9600
9643
  includeLocalAssetPaths: false
9601
9644
  });
9602
9645
  log.warn({
@@ -9647,31 +9690,7 @@ async function startHub(options = {}) {
9647
9690
  } : asset;
9648
9691
  }
9649
9692
  async function handleUploadAsset({ dataUrl }, _ownerId, signal) {
9650
- const decoded = decodeImageDataUrl(dataUrl, maxAssetSizeBytes);
9651
- const filename = buildAssetFilename(decoded.hash, decoded.mimeType);
9652
- const response = await fetch(`${assetHttpServer.getBaseUrl()}/assets/${filename}`, {
9653
- signal,
9654
- method: "POST",
9655
- headers: {
9656
- "Content-Length": String(decoded.bytes.length),
9657
- "Content-Type": decoded.mimeType
9658
- },
9659
- body: new Uint8Array(decoded.bytes)
9660
- });
9661
- try {
9662
- if (!response.ok) {
9663
- const detail = (await response.text()).slice(0, 500);
9664
- throw new Error(`Hub asset import failed (${response.status}): ${detail}`);
9665
- }
9666
- signal.throwIfAborted();
9667
- return createUploadAssetToolResponse({
9668
- assetHash: decoded.hash,
9669
- mimeType: decoded.mimeType,
9670
- size: decoded.bytes.length
9671
- });
9672
- } finally {
9673
- await response.body?.cancel().catch(() => {});
9674
- }
9693
+ return createUploadAssetToolResponse(await assetHttpServer.importImage(dataUrl, signal));
9675
9694
  }
9676
9695
  function unrefTimer(timer) {
9677
9696
  if (typeof timer === "object" && timer !== null) {
@@ -9686,7 +9705,7 @@ async function startHub(options = {}) {
9686
9705
  const message = {
9687
9706
  type: "state",
9688
9707
  activeId,
9689
- assetServerUrl: assetHttpServer.getBaseUrl(extension.legacy)
9708
+ assetServerUrl: assetHttpServer.getBaseUrl()
9690
9709
  };
9691
9710
  extension.ws.send(JSON.stringify(message));
9692
9711
  }
@@ -9759,9 +9778,9 @@ async function startHub(options = {}) {
9759
9778
  }, SHUTDOWN_TIMEOUT));
9760
9779
  }
9761
9780
  function attachConsumer(sock, registration) {
9762
- const ownerId = registration?.sessionId ?? randomUUID();
9781
+ const ownerId = registration ? managedEdgeOwner(registration.sessionId, registration.token) : randomUUID();
9763
9782
  if (registration) {
9764
- runtimeDataSockets.set(ownerId, sock);
9783
+ runtimeDataSockets.set(registration.sessionId, sock);
9765
9784
  agentClients.registerContext(ownerId, registration.context);
9766
9785
  }
9767
9786
  const mcp = createMcpServer(ownerId);
@@ -9772,7 +9791,7 @@ async function startHub(options = {}) {
9772
9791
  log.info(`Consumer connected. Total: ${consumerCount}`);
9773
9792
  const transport = registration && runtimeControl ? new RuntimeDataTransport(new SocketTransport(sock), {
9774
9793
  generation: () => runtimeControl.currentGeneration,
9775
- admit: (generation, method) => runtimeControl.admits(ownerId, generation, method),
9794
+ admit: (generation, method) => runtimeControl.admits(registration.sessionId, generation, method),
9776
9795
  role: "hub"
9777
9796
  }) : new ConsumerTransport(sock, sock);
9778
9797
  mcp.connect(transport).catch((err) => {
@@ -9788,8 +9807,10 @@ async function startHub(options = {}) {
9788
9807
  });
9789
9808
  const closeConsumer = async () => {
9790
9809
  agentClients.disconnect(ownerId);
9791
- runtimeDataSockets.delete(ownerId);
9792
- runtimeControl?.forget(ownerId);
9810
+ if (registration) {
9811
+ runtimeDataSockets.delete(registration.sessionId);
9812
+ runtimeControl?.forget(registration.sessionId);
9813
+ }
9793
9814
  await transport.close().catch((closeErr) => log.warn({ err: closeErr }, "Transport close failed."));
9794
9815
  await mcp.close().catch((closeErr) => log.warn({ err: closeErr }, "MCP session close failed."));
9795
9816
  consumerSessions.delete(mcp);
@@ -9920,7 +9941,7 @@ async function startHub(options = {}) {
9920
9941
  onActivity: noteActivity,
9921
9942
  ...runtimeControl ? {
9922
9943
  admit: () => runtimeControl.admitting(),
9923
- ...endpointTokens,
9944
+ accessToken: endpointTokens?.accessToken,
9924
9945
  port: endpoints?.httpPort
9925
9946
  } : {},
9926
9947
  authorizeExtensionOrigin: (origin) => extensionRegistry.getActive()?.origin === origin.toLowerCase()
@@ -9997,6 +10018,7 @@ async function startHub(options = {}) {
9997
10018
  });
9998
10019
  activeWss.on("connection", (ws, request) => {
9999
10020
  attachExtensionSocket(ws, {
10021
+ assetServerUrl: assetHttpServer.getBaseUrl(),
10000
10022
  runtimeProfile: RUNTIME_PROFILE,
10001
10023
  terminalReceiptGeneration: terminalReceipts.generation,
10002
10024
  onToolCompletion: (message, extension) => {
@@ -10167,4 +10189,4 @@ async function startHub(options = {}) {
10167
10189
  }
10168
10190
  export { startHub as t };
10169
10191
 
10170
- //# sourceMappingURL=hub-runtime-BBnfo1yd.mjs.map
10192
+ //# sourceMappingURL=hub-runtime-ApgbrLQI.mjs.map