@tempad-dev/mcp 0.8.0-alpha.0 → 0.9.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/dist/hub.mjs CHANGED
@@ -1,729 +1,1777 @@
1
- import { c as SOCK_PATH, d as log, i as HUB_LOCK_UPDATE_MS, l as ensureDir, n as HUB_LOCK_PATH, o as PACKAGE_VERSION, r as HUB_LOCK_STALE_MS, s as RUNTIME_DIR, t as ASSET_DIR, u as ensureFile } from "./shared-BM-k8yN9.mjs";
1
+ import { $ as SetDesignAnchorParametersSchema, A as GetDesignSystemParametersSchema, B as MCP_AUTO_ACTIVATE_GRACE_MS, C as DesignTaskIdSchema, D as GetAssetsParametersSchema, E as FigmaSessionSchema, F as LegacyMessageFromExtensionSchema, G as MCP_MAX_ASSET_STORE_BYTES, H as MCP_GET_CODE_TIMEOUT_MS, I as LegacyToolCallPayloadSchema, J as MCP_TOOL_INLINE_BUDGET_BYTES, K as MCP_MAX_PAYLOAD_BYTES, M as GetScreenshotParametersSchema, N as GetStructureParametersSchema, O as GetAssetsResultSchema, P as GetTokenDefsParametersSchema, Q as ResumeDesignParametersSchema, R as MCP_APPLY_CANVAS_TIMEOUT_MS, S as DesignAnchorSchema, T as EndDesignParametersSchema, U as MCP_GET_DESIGN_SYSTEM_TIMEOUT_MS, W as MCP_MAX_ASSET_BYTES, X as MessageFromExtensionSchema, Y as MCP_TOOL_TIMEOUT_MS, Z as RESUMABLE_DESIGN_TASK_STATUSES, a as HUB_RUNTIME_IDENTITY_PATH, at as buildApplyCanvasToolResult, b as ApplyCanvasResultSchema, c as RUNTIME_DIR, ct as buildGetDesignSystemToolResult, d as ensureFile, dt as buildGetTokenDefsToolResult, et as TEMPAD_MCP_BRIDGE_SUBPROTOCOL, f as getRecordProperty, ft as buildUploadAssetToolResult, g as clientDescriptor, h as bindRequestMetadata, ht as utf8Bytes, i as HUB_LOCK_UPDATE_MS, it as UploadAssetResultSchema, j as GetDesignSystemResultSchema, k as GetCodeParametersSchema, l as SOCK_PATH, lt as buildGetScreenshotToolResult, m as ClientEventSchema, mt as measureCallToolResultBytes, n as HUB_LOCK_PATH, nt as TEMPAD_MCP_ERROR_CODES, ot as buildGetAssetsToolResult, p as log, pt as formatDesignFeedback, q as MCP_PORT_CANDIDATES, r as HUB_LOCK_STALE_MS, rt as UploadAssetParametersSchema, s as PACKAGE_VERSION, st as buildGetCodeToolResult, t as ASSET_DIR, tt as TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS, u as ensureDir, ut as buildGetStructureToolResult, v as AGENT_CLIENTS, w as DesignTaskSchema, x as BeginDesignParametersSchema, y as ApplyCanvasParametersSchema, z as MCP_ASSET_TTL_MS } from "./shared-8rz2qWXn.mjs";
2
+ import { execFile, spawn } from "node:child_process";
2
3
  import { connect, createServer } from "node:net";
3
- import { join } from "node:path";
4
- import { URL as URL$1 } from "node:url";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { URL as URL$1, fileURLToPath } from "node:url";
5
6
  import lockfile from "proper-lockfile";
6
- import { chmodSync, createReadStream, createWriteStream, existsSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
7
+ import { z } from "zod";
8
+ import { chmodSync, createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
9
+ import { homedir, tmpdir } from "node:os";
7
10
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
8
11
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
9
- import { z } from "zod";
10
12
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
11
13
  import { WebSocketServer } from "ws";
14
+ import { lstat, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
15
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
16
+ import { isDeepStrictEqual, promisify } from "node:util";
17
+ import { createInterface } from "node:readline";
12
18
  import { nanoid } from "nanoid";
13
19
  import { createServer as createServer$1 } from "node:http";
14
20
  import { Transform, pipeline } from "node:stream";
15
- //#region ../shared/dist/index.js
16
- const MCP_PORT_CANDIDATES = [
17
- 6220,
18
- 7431,
19
- 8127
20
- ];
21
- const MCP_MAX_PAYLOAD_BYTES = 4 * 1024 * 1024;
22
- const MCP_TOOL_INLINE_BUDGET_BYTES = 64 * 1024;
23
- const MCP_TOOL_TIMEOUT_MS = 15e3;
24
- const MCP_AUTO_ACTIVATE_GRACE_MS = 1500;
25
- const MCP_MAX_ASSET_BYTES = 8 * 1024 * 1024;
26
- const MCP_MAX_ASSET_STORE_BYTES = 256 * 1024 * 1024;
27
- const MCP_ASSET_TTL_MS = 720 * 60 * 60 * 1e3;
28
- const MCP_HASH_PATTERN = new RegExp(`^[a-f0-9]{8}$`, "i");
29
- const TEMPAD_MCP_ERROR_CODES = {
30
- NO_ACTIVE_EXTENSION: "NO_ACTIVE_EXTENSION",
31
- EXTENSION_TIMEOUT: "EXTENSION_TIMEOUT",
32
- EXTENSION_DISCONNECTED: "EXTENSION_DISCONNECTED",
33
- INVALID_SELECTION: "INVALID_SELECTION",
34
- NODE_NOT_VISIBLE: "NODE_NOT_VISIBLE",
35
- CANVAS_WRITE_DISABLED: "CANVAS_WRITE_DISABLED",
36
- CANVAS_UNSUPPORTED_EDITOR: "CANVAS_UNSUPPORTED_EDITOR",
37
- CANVAS_BUSY: "CANVAS_BUSY",
38
- INVALID_CANVAS_SCOPE: "INVALID_CANVAS_SCOPE",
39
- INVALID_CANVAS_SPEC: "INVALID_CANVAS_SPEC",
40
- CANVAS_APPLY_FAILED: "CANVAS_APPLY_FAILED",
41
- ASSET_SERVER_NOT_CONFIGURED: "ASSET_SERVER_NOT_CONFIGURED",
42
- TRANSPORT_NOT_CONNECTED: "TRANSPORT_NOT_CONNECTED"
43
- };
44
- const TempadMcpErrorPayloadSchema = z.object({
45
- code: z.enum(TEMPAD_MCP_ERROR_CODES).optional(),
46
- message: z.string().min(1)
47
- }).strict();
48
- const TOOL_RESULT_OUTCOME_ERROR = "Tool results must contain exactly one defined payload or error.";
49
- function hasToolResultOutcome(result) {
50
- return result.payload !== void 0 !== (result.error !== void 0);
51
- }
52
- const TEMPAD_MCP_BROWSER_SOURCE = "tempad-dev:mcp";
53
- const MCP_MAX_ASSET_BASE64_LENGTH = 4 * Math.ceil(MCP_MAX_ASSET_BYTES / 3);
54
- const MessageBaseSchema = z.object({
55
- source: z.literal(TEMPAD_MCP_BROWSER_SOURCE),
56
- version: z.literal(1)
57
- }).strict();
58
- const PageMessageBaseSchema = MessageBaseSchema.extend({ sessionId: z.string().min(1) }).strict();
59
- function messageSchema(base, type, shape) {
60
- return base.extend({
61
- type: z.literal(type),
62
- ...shape
63
- }).strict();
64
- }
65
- const AssetMetadataSchema = z.object({
66
- height: z.number().int().positive().optional(),
67
- themeable: z.boolean().optional(),
68
- width: z.number().int().positive().optional()
69
- }).strict();
70
- const AssetUploadPayloadSchema = z.object({
71
- base64: z.string().min(1).max(MCP_MAX_ASSET_BASE64_LENGTH),
72
- hash: z.string().regex(MCP_HASH_PATTERN),
73
- metadata: AssetMetadataSchema.optional(),
74
- mimeType: z.string().min(1)
75
- }).strict();
76
- const PageEnableMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.enable", {});
77
- const PageDisableMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.disable", {});
78
- const PageActivateSessionMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.activateSession", {});
79
- const PageToolResultMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.toolResult", {
80
- callId: z.string().min(1),
81
- error: TempadMcpErrorPayloadSchema.optional(),
82
- payload: z.unknown().optional()
83
- });
84
- const PageAssetUploadMessageSchema = messageSchema(PageMessageBaseSchema, "mcp.uploadAsset", {
85
- payload: AssetUploadPayloadSchema,
86
- requestId: z.string().min(1)
87
- });
88
- z.discriminatedUnion("type", [
89
- PageEnableMessageSchema,
90
- PageDisableMessageSchema,
91
- PageActivateSessionMessageSchema,
92
- PageToolResultMessageSchema,
93
- PageAssetUploadMessageSchema
94
- ]).refine((message) => {
95
- return message.type !== "mcp.toolResult" || hasToolResultOutcome(message);
96
- }, { message: TOOL_RESULT_OUTCOME_ERROR });
97
- const McpBrowserStateStatusSchema = z.enum([
98
- "disabled",
99
- "connecting",
100
- "connected",
101
- "error"
102
- ]);
103
- const BridgeStateMessageSchema = messageSchema(MessageBaseSchema, "mcp.state", { payload: z.object({
104
- activeSessionId: z.string().nullable(),
105
- assetServerUrl: z.string().nullable().optional(),
106
- errorMessage: z.string().nullable(),
107
- sessionCount: z.number().nonnegative(),
108
- sessionId: z.string(),
109
- status: McpBrowserStateStatusSchema
110
- }).strict() });
111
- const BridgeToolCallMessageSchema = messageSchema(MessageBaseSchema, "mcp.toolCall", {
112
- callId: z.string().min(1),
113
- payload: z.object({
114
- args: z.unknown().optional(),
115
- name: z.string()
116
- }).strict()
117
- });
118
- const BridgeAssetUploadResultMessageSchema = messageSchema(MessageBaseSchema, "mcp.assetUploadResult", {
119
- error: TempadMcpErrorPayloadSchema.optional(),
120
- requestId: z.string().min(1),
121
- sessionId: z.string().min(1)
122
- });
123
- z.discriminatedUnion("type", [
124
- BridgeStateMessageSchema,
125
- BridgeToolCallMessageSchema,
126
- BridgeAssetUploadResultMessageSchema
127
- ]);
128
- const SERVER_NAME = "tempad-dev";
129
- const SERVER_COMMAND = "npx";
130
- const SERVER_ARGS = ["-y", "@tempad-dev/mcp@latest"];
131
- const REPOSITORY = "ecomfe/tempad-dev";
132
- const MARKETPLACE_NAME = "tempad-dev";
133
- const PLUGIN_NAME = "tempad-dev";
134
- const SKILL_URL = "https://github.com/ecomfe/tempad-dev/tree/main/skill";
135
- const SKILL_INSTALL_COMMAND = `npx skills add ${SKILL_URL}`;
136
- const stdioConfig = {
137
- type: "stdio",
138
- command: SERVER_COMMAND,
139
- args: [...SERVER_ARGS]
21
+ //#region src/agent-clients/codex-ipc.ts
22
+ const WINDOWS_PIPE = String.raw`\\.\pipe\codex-ipc`;
23
+ var CodexIpcError = class extends Error {
24
+ uncertain;
25
+ constructor(message, uncertain = false) {
26
+ super(message);
27
+ this.uncertain = uncertain;
28
+ }
140
29
  };
141
- const commandConfig = {
142
- command: SERVER_COMMAND,
143
- args: [...SERVER_ARGS]
30
+ var CodexDiscoveryError = class extends CodexIpcError {
31
+ constructor() {
32
+ super("Could not locate the original Codex conversation. No comments were sent. Open it in Codex and retry.");
33
+ }
144
34
  };
145
- function toBase64(input) {
146
- if (typeof globalThis.btoa === "function") return globalThis.btoa(input);
147
- const bufferLike = globalThis.Buffer;
148
- if (bufferLike) return bufferLike.from(input, "utf8").toString("base64");
149
- throw new Error("Base64 encoding not supported in this environment.");
150
- }
151
- function buildVscodeDeepLink() {
152
- return `vscode:mcp/install?${encodeURIComponent(JSON.stringify({
153
- name: SERVER_NAME,
154
- ...stdioConfig
155
- }))}`;
156
- }
157
- function buildCursorConfigBase64() {
158
- return encodeURIComponent(toBase64(JSON.stringify(commandConfig)));
159
- }
160
- function buildCursorDeepLink() {
161
- return `cursor://anysphere.cursor-deeplink/mcp/install?name=${encodeURIComponent(SERVER_NAME)}&config=${buildCursorConfigBase64()}`;
162
- }
163
- function buildTraeDeepLink(protocol) {
164
- return `${protocol}://trae.ai-ide/mcp-import?type=stdio&name=${encodeURIComponent(SERVER_NAME)}&config=${buildCursorConfigBase64()}`;
165
- }
166
- function buildCodexConfigSnippet() {
167
- return [
168
- `[mcp_servers.${SERVER_NAME}]`,
169
- `command = ${JSON.stringify(SERVER_COMMAND)}`,
170
- `args = [${SERVER_ARGS.map((arg) => JSON.stringify(arg)).join(", ")}]`
171
- ].join("\n");
172
- }
173
- function buildMcpConfigSnippet() {
174
- return JSON.stringify({ mcpServers: { [SERVER_NAME]: commandConfig } }, null, 2);
175
- }
176
- const OPENCODE_CONFIG_SNIPPET = JSON.stringify({
177
- $schema: "https://opencode.ai/config.json",
178
- mcp: { [SERVER_NAME]: {
179
- type: "local",
180
- command: [SERVER_COMMAND, ...SERVER_ARGS]
181
- } }
182
- }, null, 2);
183
- function buildCliCommand(prefix) {
184
- const args = `${SERVER_COMMAND} ${SERVER_ARGS.join(" ")}`;
185
- if (prefix === "claude") return `claude mcp add --transport stdio "${SERVER_NAME}" -- ${args}`;
186
- if (prefix === "gemini") return `gemini mcp add --scope user "${SERVER_NAME}" ${args}`;
187
- if (prefix === "vscode") return `code --add-mcp '${JSON.stringify({
188
- name: SERVER_NAME,
189
- ...commandConfig
190
- })}'`;
191
- return `codex mcp add "${SERVER_NAME}" -- ${args}`;
192
- }
193
- function buildPluginSetupCommand(prefix) {
194
- if (prefix === "claude") return [`claude plugin marketplace add ${REPOSITORY}`, `claude plugin install ${PLUGIN_NAME}@${MARKETPLACE_NAME}`].join(" && ");
195
- return [`codex plugin marketplace add ${REPOSITORY} --ref main`, `codex plugin add ${PLUGIN_NAME}@${MARKETPLACE_NAME}`].join(" && ");
196
- }
197
- function buildPluginSetupDeepLink(prefix) {
198
- const prompt = `Install the TemPad Dev agent plugin by running this command, then confirm that its MCP server plus figma-design-to-code and figma-canvas-authoring skills are available:\n\n${buildPluginSetupCommand(prefix)}`;
199
- return `${prefix === "claude" ? "claude-cli://open?q=" : "codex://new?prompt="}${encodeURIComponent(prompt)}`;
200
- }
201
- function buildSkillInstallCommand(...agents) {
202
- return `${SKILL_INSTALL_COMMAND} --global ${agents.map((agent) => `--agent ${agent}`).join(" ")}`;
203
- }
204
- [...SERVER_ARGS];
205
- JSON.stringify({ [SERVER_NAME]: commandConfig }, null, 2);
206
- buildMcpConfigSnippet();
207
- const MCP_CLIENTS_BY_ID = {
208
- vscode: {
209
- id: "vscode",
210
- name: "VS Code",
211
- brandColor: "#0098ff",
212
- supportsDeepLink: true,
213
- deepLink: buildVscodeDeepLink()
214
- },
215
- cursor: {
216
- id: "cursor",
217
- name: "Cursor",
218
- brandColor: ["#000", "#fff"],
219
- supportsDeepLink: true,
220
- deepLink: buildCursorDeepLink()
221
- },
222
- claude: {
223
- id: "claude",
224
- name: "Claude Code",
225
- brandColor: "#D97757",
226
- supportsDeepLink: false,
227
- copyText: buildCliCommand("claude"),
228
- copyKind: "command"
229
- },
230
- codex: {
231
- id: "codex",
232
- name: "Codex",
233
- brandColor: ["#0d0d0d", "#fff"],
234
- supportsDeepLink: false,
235
- copyText: buildCliCommand("codex"),
236
- copyKind: "command",
237
- alternateCopyText: buildCodexConfigSnippet(),
238
- alternateCopyKind: "config"
239
- },
240
- gemini: {
241
- id: "gemini",
242
- name: "Gemini",
243
- brandColor: "#4e6ef2",
244
- supportsDeepLink: false,
245
- copyText: buildCliCommand("gemini"),
246
- copyKind: "command",
247
- alternateCopyText: buildMcpConfigSnippet(),
248
- alternateCopyKind: "config"
249
- },
250
- opencode: {
251
- id: "opencode",
252
- name: "OpenCode",
253
- brandColor: ["#211e1e", "#f1ecec"],
254
- supportsDeepLink: false,
255
- copyText: OPENCODE_CONFIG_SNIPPET,
256
- copyKind: "config"
257
- },
258
- trae: {
259
- id: "trae",
260
- name: "TRAE",
261
- brandColor: ["#0fdc78", "#32f08c"],
262
- supportsDeepLink: true,
263
- deepLink: buildTraeDeepLink("trae"),
264
- fallbackDeepLink: buildTraeDeepLink("trae-cn")
35
+ function codexSocketPaths(env = process.env) {
36
+ if (process.platform === "win32") return [WINDOWS_PIPE];
37
+ if (!process.getuid) return [];
38
+ const uid = process.getuid();
39
+ return [join(env.CODEX_HOME || join(homedir(), ".codex"), "ipc", "ipc.sock"), join(tmpdir(), "codex-ipc", uid ? `ipc-${uid}.sock` : "ipc.sock")];
40
+ }
41
+ /** Use the host's fixed local pipe or existing current-user Unix sockets. */
42
+ async function trustedSocket(path) {
43
+ if (process.platform === "win32") return path === WINDOWS_PIPE;
44
+ try {
45
+ const [socket, parent] = await Promise.all([lstat(path), lstat(dirname(path))]);
46
+ const uid = process.getuid?.();
47
+ return uid !== void 0 && socket.isSocket() && socket.uid === uid && parent.isDirectory() && parent.uid === uid && !(parent.mode & 18);
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+ var CodexIpc = class CodexIpc {
53
+ socket;
54
+ broadcasts = /* @__PURE__ */ new Set();
55
+ disconnects = /* @__PURE__ */ new Set();
56
+ clientId = "initializing-client";
57
+ header = Buffer.alloc(4);
58
+ headerBytes = 0;
59
+ payload;
60
+ payloadBytes = 0;
61
+ pending = /* @__PURE__ */ new Map();
62
+ constructor(socket) {
63
+ this.socket = socket;
64
+ socket.on("data", (chunk) => {
65
+ let offset = 0;
66
+ while (offset < chunk.length && !socket.destroyed) {
67
+ if (!this.payload) {
68
+ const copied = chunk.copy(this.header, this.headerBytes, offset, offset + 4 - this.headerBytes);
69
+ this.headerBytes += copied;
70
+ offset += copied;
71
+ if (this.headerBytes < 4) continue;
72
+ const size = this.header.readUInt32LE(0);
73
+ if (!size || size > 268435456) {
74
+ this.close();
75
+ return;
76
+ }
77
+ this.payload = Buffer.allocUnsafe(size);
78
+ this.payloadBytes = 0;
79
+ this.headerBytes = 0;
80
+ }
81
+ const copied = chunk.copy(this.payload, this.payloadBytes, offset, offset + this.payload.length - this.payloadBytes);
82
+ this.payloadBytes += copied;
83
+ offset += copied;
84
+ if (this.payloadBytes < this.payload.length) continue;
85
+ const payload = this.payload;
86
+ this.payload = void 0;
87
+ try {
88
+ this.receive(JSON.parse(payload.toString("utf8")));
89
+ } catch {
90
+ this.close();
91
+ }
92
+ }
93
+ });
94
+ socket.on("error", () => this.close());
95
+ socket.on("close", () => {
96
+ this.payload = void 0;
97
+ for (const pending of this.pending.values()) pending.reject(new CodexIpcError("Codex IPC disconnected; delivery may be uncertain.", true));
98
+ this.pending.clear();
99
+ for (const listener of this.disconnects) listener();
100
+ this.disconnects.clear();
101
+ this.broadcasts.clear();
102
+ });
103
+ }
104
+ static async open(paths = codexSocketPaths()) {
105
+ for (const path of paths) {
106
+ if (!await trustedSocket(path)) continue;
107
+ let client;
108
+ try {
109
+ const socket = connect(path);
110
+ client = new CodexIpc(socket);
111
+ await new Promise((resolve, reject) => {
112
+ const timer = setTimeout(() => {
113
+ socket.destroy();
114
+ reject(/* @__PURE__ */ new Error("Connect timeout"));
115
+ }, 750);
116
+ socket.once("connect", () => {
117
+ clearTimeout(timer);
118
+ resolve();
119
+ });
120
+ socket.once("error", (error) => {
121
+ clearTimeout(timer);
122
+ reject(error);
123
+ });
124
+ });
125
+ const result = (await client.request("initialize", 0, { clientType: "tempad-dev" }, void 0, void 0, 2e3)).result;
126
+ if (typeof result?.clientId !== "string" || !result.clientId) throw new Error("Invalid IPC identity");
127
+ client.clientId = result.clientId;
128
+ return client;
129
+ } catch {
130
+ client?.close();
131
+ }
132
+ }
133
+ throw new CodexIpcError("Codex App IPC is unavailable. Open the original conversation in Codex.");
134
+ }
135
+ receive(message) {
136
+ if (message.type === "broadcast") {
137
+ for (const listener of this.broadcasts) listener(message);
138
+ return;
139
+ }
140
+ if (message.type === "client-discovery-request") {
141
+ this.write({
142
+ type: "client-discovery-response",
143
+ requestId: message.requestId,
144
+ response: { canHandle: false }
145
+ });
146
+ return;
147
+ }
148
+ if (message.type !== "response" || typeof message.requestId !== "string") return;
149
+ const pending = this.pending.get(message.requestId);
150
+ if (!pending) return;
151
+ if (message.resultType === "success" && message.method === pending.method) pending.resolve(message);
152
+ else pending.reject(new CodexIpcError(typeof message.error === "string" ? message.error : "Codex IPC returned an incompatible response.", message.resultType === "success"));
153
+ }
154
+ write(message) {
155
+ const data = Buffer.from(JSON.stringify(message));
156
+ const header = Buffer.alloc(4);
157
+ header.writeUInt32LE(data.length);
158
+ this.socket.write(Buffer.concat([header, data]));
159
+ }
160
+ onBroadcast(listener) {
161
+ this.broadcasts.add(listener);
162
+ return () => this.broadcasts.delete(listener);
163
+ }
164
+ onDisconnect(listener) {
165
+ this.disconnects.add(listener);
166
+ return () => this.disconnects.delete(listener);
167
+ }
168
+ broadcast(method, version, params, targetClientIds) {
169
+ if (this.socket.destroyed) throw new CodexIpcError("Codex IPC is disconnected.");
170
+ this.write({
171
+ type: "broadcast",
172
+ sourceClientId: this.clientId,
173
+ method,
174
+ version,
175
+ params,
176
+ targetClientIds
177
+ });
178
+ }
179
+ request(method, version, params, targetClientId, signal, timeoutMs = 25e3) {
180
+ if (signal?.aborted || this.socket.destroyed) return Promise.reject(new CodexIpcError("Codex IPC request cancelled before dispatch."));
181
+ const requestId = randomUUID();
182
+ return new Promise((resolve, reject) => {
183
+ const finish = (error, response) => {
184
+ this.pending.delete(requestId);
185
+ clearTimeout(timer);
186
+ signal?.removeEventListener("abort", abort);
187
+ if (error) reject(error);
188
+ else resolve(response);
189
+ };
190
+ const abort = () => finish(new CodexIpcError("Codex IPC delivery was cancelled after dispatch; check the conversation.", true));
191
+ const timer = setTimeout(() => finish(new CodexIpcError("Codex IPC delivery timed out; check the conversation before retrying.", true)), timeoutMs);
192
+ this.pending.set(requestId, {
193
+ method,
194
+ resolve: (message) => finish(void 0, message),
195
+ reject: (error) => finish(error)
196
+ });
197
+ signal?.addEventListener("abort", abort, { once: true });
198
+ this.write({
199
+ type: "request",
200
+ requestId,
201
+ sourceClientId: this.clientId,
202
+ version,
203
+ method,
204
+ params,
205
+ timeoutMs,
206
+ ...targetClientId ? { targetClientId } : {}
207
+ });
208
+ });
209
+ }
210
+ async owner(conversationId, signal, timeoutMs = 12e3) {
211
+ let response;
212
+ try {
213
+ response = await this.request("thread-owner-discovery", 1, {
214
+ hostId: "local",
215
+ conversationId
216
+ }, void 0, signal, timeoutMs);
217
+ } catch (error) {
218
+ if (error instanceof CodexIpcError && error.uncertain) throw new CodexDiscoveryError();
219
+ throw error;
220
+ }
221
+ if (typeof response.handledByClientId !== "string" || response.result?.supportsUntrustedAppInput !== true) throw new CodexIpcError("The conversation owner does not support external comment input.");
222
+ return response.handledByClientId;
223
+ }
224
+ close() {
225
+ this.socket.destroy();
265
226
  }
266
227
  };
267
- MCP_CLIENTS_BY_ID.vscode, MCP_CLIENTS_BY_ID.cursor, MCP_CLIENTS_BY_ID.claude, MCP_CLIENTS_BY_ID.codex, MCP_CLIENTS_BY_ID.gemini, MCP_CLIENTS_BY_ID.opencode, MCP_CLIENTS_BY_ID.trae;
268
- const AGENT_INTEGRATIONS_BY_ID = {
269
- codex: {
270
- id: "codex",
271
- name: "Codex",
272
- actions: [{
273
- id: "plugin-prompt",
274
- label: "Plugin install",
275
- kind: "deep-link",
276
- value: buildPluginSetupDeepLink("codex")
277
- }, {
278
- id: "plugin-cli",
279
- label: "Plugin CLI",
280
- kind: "command",
281
- value: buildPluginSetupCommand("codex")
282
- }]
283
- },
284
- cursor: {
285
- id: "cursor",
286
- name: "Cursor",
287
- actions: [
288
- {
289
- id: "mcp-deep-link",
290
- label: "MCP install",
291
- kind: "deep-link",
292
- value: MCP_CLIENTS_BY_ID.cursor.deepLink ?? ""
293
- },
294
- {
295
- id: "mcp-config",
296
- label: "MCP config",
297
- kind: "config",
298
- value: buildMcpConfigSnippet()
299
- },
300
- {
301
- id: "skill-cli",
302
- label: "Agent skill",
303
- kind: "command",
304
- value: buildSkillInstallCommand("cursor")
228
+ //#endregion
229
+ //#region src/agent-clients/codex-queue-rpc.ts
230
+ /** Use the running desktop's bundled binary, never an unrelated CLI on PATH. */
231
+ async function codexQueueExecutable() {
232
+ const { stdout } = process.platform === "win32" ? await promisify(execFile)("powershell.exe", [
233
+ "-NoProfile",
234
+ "-NonInteractive",
235
+ "-Command",
236
+ "(Get-Process codex -ErrorAction Stop).Path"
237
+ ], { timeout: 3e3 }) : await promisify(execFile)("ps", [
238
+ "-U",
239
+ String(process.getuid()),
240
+ "-o",
241
+ "comm="
242
+ ], { timeout: 3e3 });
243
+ const paths = [...new Set(stdout.split(/\r?\n/).map((path) => path.trim()))].filter((path) => /[/\\]resources[/\\]codex(?:\.exe)?$/i.test(path));
244
+ if (paths.length !== 1) throw new Error("The running Codex desktop executable could not be identified.");
245
+ return paths[0];
246
+ }
247
+ /** A queue-only connection: the desktop remains the sole executor of its tasks. */
248
+ var CodexQueueRpc = class {
249
+ executable;
250
+ child;
251
+ ready;
252
+ closed = false;
253
+ nextId = 0;
254
+ pending = /* @__PURE__ */ new Map();
255
+ constructor(executable = codexQueueExecutable) {
256
+ this.executable = executable;
257
+ }
258
+ async list(threadId, signal) {
259
+ await this.connect();
260
+ const messages = [];
261
+ let cursor = null;
262
+ do {
263
+ const page = await this.request("thread/queue/list", {
264
+ threadId,
265
+ cursor
266
+ }, signal);
267
+ if (!Array.isArray(page?.data) || page.data.some((item) => !item || typeof item.id !== "string" || !item.id || !Array.isArray(item.input) || item.clientUserMessageId !== null && typeof item.clientUserMessageId !== "string")) throw new Error("Codex returned an incompatible server queue.");
268
+ messages.push(...page.data);
269
+ if (page.nextCursor != null && (typeof page.nextCursor !== "string" || page.nextCursor === cursor)) throw new Error("Codex returned an incompatible queue cursor.");
270
+ cursor = page.nextCursor ?? null;
271
+ } while (cursor !== null);
272
+ return messages;
273
+ }
274
+ async add(threadId, clientUserMessageId, text, signal) {
275
+ await this.connect();
276
+ const result = await this.request("thread/queue/add", {
277
+ threadId,
278
+ clientUserMessageId,
279
+ input: [{
280
+ type: "text",
281
+ text,
282
+ text_elements: []
283
+ }]
284
+ }, signal);
285
+ if (typeof result?.queuedSubmission?.id !== "string" || !result.queuedSubmission.id || result.queuedSubmission.clientUserMessageId !== clientUserMessageId) throw new CodexIpcError("Codex did not confirm queue admission.", true);
286
+ }
287
+ async remove(threadId, queuedSubmissionId, signal) {
288
+ await this.connect();
289
+ if (typeof (await this.request("thread/queue/delete", {
290
+ threadId,
291
+ queuedSubmissionId
292
+ }, signal))?.deleted !== "boolean") throw new CodexIpcError("Codex did not confirm queue removal.", true);
293
+ }
294
+ async connect() {
295
+ if (this.closed) throw new Error("Codex queue connection is closed.");
296
+ this.ready ??= this.start();
297
+ const ready = this.ready;
298
+ try {
299
+ await ready;
300
+ } catch (error) {
301
+ if (this.ready === ready) this.disconnect();
302
+ throw error;
303
+ }
304
+ }
305
+ async start() {
306
+ const executable = await this.executable();
307
+ if (this.closed) throw new Error("Codex queue connection is closed.");
308
+ const child = spawn(executable, ["app-server"], {
309
+ stdio: "pipe",
310
+ windowsHide: true
311
+ });
312
+ this.child = child;
313
+ child.stderr.resume();
314
+ const lines = createInterface({ input: child.stdout });
315
+ lines.on("line", (line) => {
316
+ if (this.child !== child) return;
317
+ try {
318
+ const response = JSON.parse(line);
319
+ const pending = this.pending.get(response.id);
320
+ if (!pending) return;
321
+ if (response.error) pending.reject(new CodexIpcError(String(response.error.message ?? "Codex queue request failed.")));
322
+ else if ("result" in response) pending.resolve(response.result);
323
+ else this.disconnect();
324
+ } catch {
325
+ this.disconnect();
305
326
  }
306
- ]
307
- },
308
- claude: {
309
- id: "claude",
310
- name: "Claude Code",
311
- actions: [{
312
- id: "plugin-prompt",
313
- label: "Plugin install",
314
- kind: "deep-link",
315
- value: buildPluginSetupDeepLink("claude")
316
- }, {
317
- id: "plugin-cli",
318
- label: "Plugin CLI",
319
- kind: "command",
320
- value: buildPluginSetupCommand("claude")
321
- }]
322
- },
323
- gemini: {
324
- id: "gemini",
325
- name: "Gemini",
326
- actions: [{
327
- id: "mcp-cli",
328
- label: "MCP CLI",
329
- kind: "command",
330
- value: buildCliCommand("gemini")
331
- }, {
332
- id: "skill-cli",
333
- label: "Agent skill",
334
- kind: "command",
335
- value: `gemini skills install ${SKILL_URL}`
336
- }]
337
- },
338
- vscode: {
339
- id: "vscode",
340
- name: "VS Code",
341
- actions: [
342
- {
343
- id: "mcp-deep-link",
344
- label: "MCP install",
345
- kind: "deep-link",
346
- value: MCP_CLIENTS_BY_ID.vscode.deepLink ?? ""
347
- },
348
- {
349
- id: "mcp-cli",
350
- label: "MCP CLI",
351
- kind: "command",
352
- value: buildCliCommand("vscode")
327
+ });
328
+ const disconnected = () => {
329
+ if (this.child === child) this.disconnect();
330
+ };
331
+ child.on("error", disconnected);
332
+ child.on("exit", disconnected);
333
+ child.stdin.on("error", disconnected);
334
+ child.on("close", () => lines.close());
335
+ await this.request("initialize", {
336
+ clientInfo: {
337
+ name: "tempad-dev-queue",
338
+ version: "1"
353
339
  },
354
- {
355
- id: "skill-cli",
356
- label: "Agent skill",
357
- kind: "command",
358
- value: buildSkillInstallCommand("github-copilot")
340
+ capabilities: { experimentalApi: true }
341
+ });
342
+ child.stdin.write("{\"method\":\"initialized\"}\n");
343
+ }
344
+ request(method, params, signal) {
345
+ signal?.throwIfAborted();
346
+ const child = this.child;
347
+ if (!child || child.stdin.destroyed) throw new CodexIpcError("Codex queue connection is unavailable.");
348
+ const id = ++this.nextId;
349
+ return new Promise((resolve, reject) => {
350
+ const finish = (error, value) => {
351
+ clearTimeout(timer);
352
+ signal?.removeEventListener("abort", abort);
353
+ this.pending.delete(id);
354
+ if (error) reject(error);
355
+ else resolve(value);
356
+ };
357
+ const abort = () => finish(new CodexIpcError("Codex queue request was cancelled after dispatch.", true));
358
+ const timer = setTimeout(() => finish(new CodexIpcError("Codex queue request timed out.", true)), 1e4);
359
+ this.pending.set(id, {
360
+ resolve: (value) => finish(void 0, value),
361
+ reject: (error) => finish(error)
362
+ });
363
+ signal?.addEventListener("abort", abort, { once: true });
364
+ try {
365
+ child.stdin.write(`${JSON.stringify({
366
+ id,
367
+ method,
368
+ params
369
+ })}\n`);
370
+ } catch (cause) {
371
+ finish(new CodexIpcError(`Codex queue write failed: ${String(cause)}`, true));
359
372
  }
360
- ]
361
- },
362
- opencode: {
363
- id: "opencode",
364
- name: "OpenCode",
365
- actions: [{
366
- id: "mcp-config",
367
- label: "MCP config",
368
- kind: "config",
369
- value: OPENCODE_CONFIG_SNIPPET
370
- }, {
371
- id: "skill-cli",
372
- label: "Agent skill",
373
- kind: "command",
374
- value: buildSkillInstallCommand("opencode")
375
- }]
376
- },
377
- trae: {
378
- id: "trae",
379
- name: "TRAE",
380
- actions: [{
381
- id: "mcp-deep-link",
382
- label: "MCP install",
383
- kind: "deep-link",
384
- value: MCP_CLIENTS_BY_ID.trae.deepLink ?? "",
385
- fallbackValue: MCP_CLIENTS_BY_ID.trae.fallbackDeepLink
386
- }, {
387
- id: "skill-cli",
388
- label: "Agent skill",
389
- kind: "command",
390
- value: buildSkillInstallCommand("trae", "trae-cn")
391
- }]
373
+ });
374
+ }
375
+ disconnect() {
376
+ const child = this.child;
377
+ this.child = void 0;
378
+ this.ready = void 0;
379
+ for (const pending of this.pending.values()) pending.reject(new CodexIpcError("Codex queue connection closed after dispatch.", true));
380
+ child?.kill();
381
+ }
382
+ close() {
383
+ this.closed = true;
384
+ this.disconnect();
392
385
  }
393
386
  };
394
- AGENT_INTEGRATIONS_BY_ID.codex, AGENT_INTEGRATIONS_BY_ID.cursor, AGENT_INTEGRATIONS_BY_ID.claude, AGENT_INTEGRATIONS_BY_ID.gemini, AGENT_INTEGRATIONS_BY_ID.vscode, AGENT_INTEGRATIONS_BY_ID.opencode, AGENT_INTEGRATIONS_BY_ID.trae;
395
- const RegisteredMessageSchema = z.object({
396
- type: z.literal("registered"),
397
- id: z.string().min(1)
398
- }).strict();
399
- const StateMessageSchema = z.object({
400
- type: z.literal("state"),
401
- activeId: z.string().nullable(),
402
- assetServerUrl: z.string().url()
403
- }).strict();
404
- const ToolCallPayloadSchema = z.object({
405
- name: z.string(),
406
- args: z.unknown()
407
- }).strict();
408
- const ToolCallMessageSchema = z.object({
409
- type: z.literal("toolCall"),
410
- id: z.string().min(1),
411
- payload: ToolCallPayloadSchema
412
- }).strict();
413
- z.discriminatedUnion("type", [
414
- RegisteredMessageSchema,
415
- StateMessageSchema,
416
- ToolCallMessageSchema
417
- ]);
418
- const ActivateMessageSchema = z.object({ type: z.literal("activate") }).strict();
419
- const ToolResultMessageSchema = z.object({
420
- type: z.literal("toolResult"),
421
- id: z.string().min(1),
422
- payload: z.unknown().optional(),
423
- error: TempadMcpErrorPayloadSchema.optional()
424
- }).strict().refine(hasToolResultOutcome, { message: TOOL_RESULT_OUTCOME_ERROR });
425
- const PingMessageSchema = z.object({ type: z.literal("ping") }).strict();
426
- const MessageFromExtensionSchema = z.union([
427
- ActivateMessageSchema,
428
- ToolResultMessageSchema,
429
- PingMessageSchema
430
- ]);
431
- const ENCODER = new TextEncoder();
432
- function utf8Bytes(value) {
433
- return ENCODER.encode(serializeUtf8Value(value)).length;
434
- }
435
- function measureCallToolResultBytes(result) {
436
- return utf8Bytes(result);
437
- }
438
- function buildGetCodeToolResult(payload) {
439
- const summary = [];
440
- const codeSize = utf8Bytes(payload.code);
441
- summary.push(`Generated \`${payload.lang}\` snippet (${formatBytes(codeSize)}).`);
442
- if (payload.warnings?.length) summary.push(...payload.warnings.map((warning) => warning.message));
443
- summary.push(payload.assets?.length ? `Assets attached: ${payload.assets.length}. Download bytes from each asset.url.` : "No binary assets were attached to this response.");
444
- const tokenCount = payload.tokens ? Object.keys(payload.tokens).length : 0;
445
- if (tokenCount) summary.push(`Token references included: ${tokenCount}.`);
446
- summary.push("Read structuredContent for the full code string and metadata.");
447
- return buildTextToolResult(summary.join("\n"), payload);
448
- }
449
- function buildGetDesignSystemToolResult(payload) {
450
- return buildTextToolResult(`${`Found ${formatCount(payload.components.length, "component")} and ${formatCount(payload.variables.length, "variable")} on page "${payload.page.name}".`}${payload.warnings?.length ? `\n${payload.warnings.join("\n")}` : ""}\nRead structuredContent for stable component and variable references.`, payload);
451
- }
452
- function buildApplyCanvasToolResult(payload) {
453
- return buildTextToolResult(`${`Applied ${formatCount(payload.mutationCount, "canvas mutation")}: ${formatCount(payload.createdNodeIds.length, "node")} created and ${formatCount(payload.updatedNodeIds.length, "node")} updated.`}${payload.warnings?.length ? `\n${payload.warnings.join("\n")}` : ""}\nRoot node: ${payload.rootNodeId}. Reuse nodeIdsByKey for later updates.`, payload);
454
- }
455
- function buildGetStructureToolResult(payload) {
456
- const roots = payload.roots.length;
457
- const nodeCount = countOutlineNodes(payload.roots);
458
- return buildTextToolResult(`${roots === 0 ? "No structure nodes were returned." : `Returned structure outline with ${formatCount(roots, "root")} and ${formatCount(nodeCount, "node")}.`}\nRead structuredContent for the full outline payload.`, payload);
459
- }
460
- function buildGetTokenDefsToolResult(payload) {
461
- const count = Object.keys(payload).length;
462
- return buildTextToolResult(`${count === 0 ? "No token definitions were resolved." : `Resolved ${formatCount(count, "token definition")}.`}\nRead structuredContent for token values and aliases.`, payload);
463
- }
464
- function buildGetScreenshotToolResult(payload) {
465
- return buildTextToolResult(`${describeScreenshot(payload)} - Download: ${payload.asset.url}`, payload);
466
- }
467
- function buildGetAssetsToolResult(payload) {
468
- const summary = [];
469
- summary.push(payload.assets.length ? `Resolved ${formatCount(payload.assets.length, "asset")}.` : "No assets were resolved for the requested hashes.");
470
- if (payload.missing.length) summary.push(`Missing: ${payload.missing.join(", ")}`);
471
- summary.push("Download bytes from each asset.url.");
472
- return buildTextToolResult(summary.join("\n"), payload);
473
- }
474
- function buildTextToolResult(text, structuredContent) {
387
+ //#endregion
388
+ //#region src/agent-clients/codex-server-queue.ts
389
+ /** A missing database identifies an older store; an unreadable store is never empty. */
390
+ async function readCodexServerQueue(conversationId) {
391
+ const path = join(process.env.CODEX_SQLITE_HOME || process.env.CODEX_HOME || join(homedir(), ".codex"), "queue_1.sqlite");
392
+ try {
393
+ try {
394
+ await stat(path);
395
+ } catch (error) {
396
+ if (error.code === "ENOENT") return null;
397
+ throw error;
398
+ }
399
+ const { DatabaseSync } = await import("node:sqlite");
400
+ const database = new DatabaseSync(path, { readOnly: true });
401
+ try {
402
+ database.exec("PRAGMA query_only = ON; PRAGMA busy_timeout = 250");
403
+ return { hasMessages: database.prepare("SELECT 1 AS queued FROM queued_items WHERE thread_id = ? LIMIT 1").get(conversationId) !== void 0 };
404
+ } finally {
405
+ database.close();
406
+ }
407
+ } catch (error) {
408
+ throw new Error("The Codex server queue could not be checked. Comments remain saved.", { cause: error });
409
+ }
410
+ }
411
+ //#endregion
412
+ //#region src/agent-clients/codex-queue.ts
413
+ function object$2(value) {
414
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Codex queue state has an unsupported format.");
415
+ return value;
416
+ }
417
+ var CodexQueueUnavailable = class extends Error {};
418
+ /** Read only. The native owner commits this file before acknowledging queue writes. */
419
+ async function readCodexQueue(conversationId) {
420
+ const path = join(process.env.CODEX_HOME || join(homedir(), ".codex"), ".codex-global-state.json");
421
+ let state;
422
+ try {
423
+ state = object$2(JSON.parse(await readFile(path, "utf8")));
424
+ } catch (cause) {
425
+ throw new CodexQueueUnavailable("The Codex queue snapshot is unavailable.", { cause });
426
+ }
427
+ const messages = (state["queued-follow-ups"] == null ? {} : object$2(state["queued-follow-ups"]))[conversationId] ?? [];
428
+ if (!Array.isArray(messages)) throw new Error("Codex queue state has an unsupported format.");
429
+ const ids = /* @__PURE__ */ new Set();
430
+ for (const message of messages) {
431
+ const id = object$2(message).id;
432
+ if (typeof id !== "string" || !id || ids.has(id)) throw new Error("Codex queue contains invalid or duplicate message identities.");
433
+ ids.add(id);
434
+ }
435
+ return messages;
436
+ }
437
+ function codexFeedbackQueuedMessage(taskId, feedback, cwd) {
438
+ const text = formatDesignFeedback(feedback);
475
439
  return {
476
- content: [{
440
+ id: feedback.id,
441
+ text,
442
+ cwd,
443
+ createdAt: feedback.createdAt,
444
+ context: {
445
+ prompt: text,
446
+ addedFiles: [],
447
+ fileAttachments: [],
448
+ imageAttachments: [],
449
+ commentAttachments: [],
450
+ ideContext: null
451
+ },
452
+ writingBlockAdditionalContext: { "tempad-design-task": {
453
+ kind: "untrusted",
454
+ value: `Design task: ${JSON.stringify(taskId)}`
455
+ } }
456
+ };
457
+ }
458
+ /** Obtain the original conversation's cwd without guessing from the Hub process. */
459
+ async function conversationCwd(ipc, owner, conversationId, signal) {
460
+ signal.throwIfAborted();
461
+ const cleanups = [];
462
+ let timer;
463
+ try {
464
+ return await new Promise((resolve, reject) => {
465
+ timer = setTimeout(() => reject(new CodexQueueUnavailable("Codex queue context timed out.")), 5e3);
466
+ const abort = () => reject(signal.reason);
467
+ signal.addEventListener("abort", abort, { once: true });
468
+ cleanups.push(() => signal.removeEventListener("abort", abort));
469
+ cleanups.push(ipc.onDisconnect(() => reject(new CodexQueueUnavailable("Codex disconnected."))));
470
+ cleanups.push(ipc.onBroadcast((message) => {
471
+ if (message.method !== "thread-stream-state-changed" || message.sourceClientId !== owner) return;
472
+ try {
473
+ const params = object$2(message.params);
474
+ if (params.conversationId !== conversationId || params.hostId !== "local") return;
475
+ if (message.version !== 11) throw new CodexQueueUnavailable("Unsupported Codex snapshot version.");
476
+ const change = object$2(params.change);
477
+ if (change.type !== "snapshot") return;
478
+ const state = object$2(change.conversationState);
479
+ if (state.id !== conversationId || typeof state.cwd !== "string" || !state.cwd) throw new CodexQueueUnavailable("The original Codex workspace is unavailable.");
480
+ resolve(state.cwd);
481
+ } catch (error) {
482
+ reject(error);
483
+ }
484
+ }));
485
+ ipc.broadcast("thread-stream-following-changed", 1, {
486
+ hostId: "local",
487
+ conversationId,
488
+ following: true
489
+ }, [owner]);
490
+ });
491
+ } finally {
492
+ clearTimeout(timer);
493
+ for (const cleanup of cleanups) cleanup();
494
+ try {
495
+ ipc.broadcast("thread-stream-following-changed", 1, {
496
+ hostId: "local",
497
+ conversationId,
498
+ following: false
499
+ }, [owner]);
500
+ } catch {}
501
+ }
502
+ }
503
+ var CodexNativeQueue = class {
504
+ readLegacy;
505
+ readServer;
506
+ server;
507
+ constructor(readLegacy = readCodexQueue, readServer = readCodexServerQueue, server = new CodexQueueRpc()) {
508
+ this.readLegacy = readLegacy;
509
+ this.readServer = readServer;
510
+ this.server = server;
511
+ }
512
+ async read(conversationId, backend = "legacy") {
513
+ if (backend === "legacy") return this.readLegacy(conversationId);
514
+ return (await this.server.list(conversationId)).map((message) => ({
515
+ id: message.clientUserMessageId ?? message.id,
516
+ text: message.input.filter((input) => input.type === "text").map((input) => input.text).join("\n")
517
+ }));
518
+ }
519
+ /** Direct Start must not overtake either native queue while native admission is unavailable. */
520
+ async areQueuesEmpty(conversationId) {
521
+ const server = await this.readServer(conversationId);
522
+ const messages = await this.read(conversationId);
523
+ return !server?.hasMessages && messages.length === 0;
524
+ }
525
+ async admit(ipc, owner, conversationId, taskId, feedback, signal, beforeWrite, onDispatch) {
526
+ const cwd = await conversationCwd(ipc, owner, conversationId, signal);
527
+ const backend = await this.readServer(conversationId) && (await this.readLegacy(conversationId)).length === 0 ? "server" : "legacy";
528
+ await beforeWrite(backend);
529
+ const messages = await this.read(conversationId, backend);
530
+ signal.throwIfAborted();
531
+ if (backend === "server") {
532
+ const text = formatDesignFeedback(feedback);
533
+ const existing = messages.find((message) => message.id === feedback.id);
534
+ if (existing) {
535
+ if (existing.text !== text) throw new Error("This Codex queue identity belongs to different content.");
536
+ return;
537
+ }
538
+ onDispatch();
539
+ await this.server.add(conversationId, feedback.id, text, signal);
540
+ return;
541
+ }
542
+ const existing = messages.find((message) => message.id === feedback.id);
543
+ if (existing) {
544
+ if (existing.text !== formatDesignFeedback(feedback) || JSON.stringify(existing.writingBlockAdditionalContext) !== JSON.stringify(codexFeedbackQueuedMessage(taskId, feedback, cwd).writingBlockAdditionalContext)) throw new Error("This Codex queue identity belongs to different content.");
545
+ return;
546
+ }
547
+ onDispatch();
548
+ await this.replace(ipc, owner, conversationId, [...messages, codexFeedbackQueuedMessage(taskId, feedback, cwd)], signal);
549
+ }
550
+ async remove(ipc, owner, conversationId, ids, signal, backend = "legacy") {
551
+ if (backend === "server") {
552
+ for (const message of await this.server.list(conversationId, signal)) if (message.clientUserMessageId && ids.has(message.clientUserMessageId)) await this.server.remove(conversationId, message.id, signal);
553
+ return;
554
+ }
555
+ const messages = await this.read(conversationId);
556
+ const remaining = messages.filter((message) => !ids.has(message.id));
557
+ if (remaining.length !== messages.length) {
558
+ if (!ipc || !owner) throw new Error("The Codex queue owner is unavailable.");
559
+ await this.replace(ipc, owner, conversationId, remaining, signal);
560
+ }
561
+ }
562
+ close() {
563
+ this.server.close();
564
+ }
565
+ async replace(ipc, owner, conversationId, messages, signal) {
566
+ signal.throwIfAborted();
567
+ const response = await ipc.request("thread-follower-set-queued-follow-ups-state", 1, {
568
+ conversationId,
569
+ state: { [conversationId]: messages }
570
+ }, owner, signal);
571
+ if (response.handledByClientId !== owner || object$2(response.result).ok !== true) throw new CodexIpcError("Codex did not confirm queue admission.", true);
572
+ }
573
+ };
574
+ //#endregion
575
+ //#region src/agent-clients/types.ts
576
+ /** Only clients with a verified native conversation channel can carry comments or interruption. */
577
+ function nativeFeedback(client) {
578
+ return AGENT_CLIENTS[client.kind].feedback;
579
+ }
580
+ /** The conversation reachable over that native channel, which every native delivery path needs. */
581
+ function nativeConversation(client) {
582
+ return client && nativeFeedback(client) ? client.sessionId : void 0;
583
+ }
584
+ const CANVAS_ONLY = {
585
+ interrupt: false,
586
+ queue: false,
587
+ steer: false,
588
+ continue: false,
589
+ reason: "Comments are unavailable for this client. Native conversation delivery is currently supported only in Codex App."
590
+ };
591
+ const CODEX_FEEDBACK_UNAVAILABLE = {
592
+ ...CANVAS_ONLY,
593
+ reason: "Codex App comment delivery is unavailable. Open the original conversation in Codex App and retry. Comments stay saved; they are never delivered through hooks."
594
+ };
595
+ //#endregion
596
+ //#region src/agent-clients/codex-feedback.ts
597
+ const CODEX_APP_FEEDBACK = {
598
+ interrupt: false,
599
+ continue: false,
600
+ queue: true,
601
+ steer: true,
602
+ queueDelivery: "native",
603
+ steerDelivery: "native",
604
+ reason: "Queue waits for the current response to finish. Steer sends comments to the active response."
605
+ };
606
+ function codexFeedbackTurn(conversationId, taskId, feedback) {
607
+ const callId = `tempad-comments-${feedback.id}`;
608
+ return {
609
+ request: {
610
+ threadId: conversationId,
611
+ clientUserMessageId: feedback.id,
612
+ input: [{
613
+ type: "text",
614
+ text: formatDesignFeedback(feedback),
615
+ text_elements: []
616
+ }]
617
+ },
618
+ context: { responseItems: [{
619
+ type: "function_call",
620
+ call_id: callId,
621
+ name: "untrusted_input",
622
+ arguments: "{}"
623
+ }, {
624
+ type: "function_call_output",
625
+ call_id: callId,
626
+ output: [{
627
+ type: "input_text",
628
+ text: `Design task: ${JSON.stringify(taskId)}`
629
+ }]
630
+ }] }
631
+ };
632
+ }
633
+ function codexFeedbackSteer(conversationId, taskId, feedback) {
634
+ const text = formatDesignFeedback(feedback);
635
+ return {
636
+ conversationId,
637
+ clientUserMessageId: feedback.id,
638
+ input: [{
477
639
  type: "text",
478
- text
640
+ text,
641
+ text_elements: []
479
642
  }],
480
- structuredContent
643
+ restoreMessage: {
644
+ text,
645
+ context: {}
646
+ },
647
+ additionalContext: { "tempad-design-task": {
648
+ kind: "untrusted",
649
+ value: `Design task: ${JSON.stringify(taskId)}`
650
+ } }
481
651
  };
482
652
  }
483
- function serializeUtf8Value(value) {
484
- if (typeof value === "string") return value;
485
- return JSON.stringify(value, null, 0) ?? "undefined";
486
- }
487
- function countOutlineNodes(nodes) {
488
- let count = 0;
489
- const stack = [...nodes];
490
- while (stack.length) {
491
- const current = stack.pop();
492
- if (!current) continue;
493
- count += 1;
494
- if (current.children?.length) stack.push(...current.children);
495
- }
496
- return count;
497
- }
498
- function formatBytes(bytes) {
499
- if (bytes < 1024) return `${bytes} B`;
500
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
501
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
502
- }
503
- function formatCount(count, singular) {
504
- return `${count} ${count === 1 ? singular : `${singular}s`}`;
505
- }
506
- function describeScreenshot(result) {
507
- return `Screenshot ${result.width}x${result.height} @${result.scale}x (${formatBytes(result.bytes)})`;
508
- }
509
- const AssetDescriptorSchema = z.object({
510
- hash: z.string().regex(MCP_HASH_PATTERN),
511
- url: z.string().url(),
512
- mimeType: z.string().min(1),
513
- size: z.number().int().nonnegative(),
514
- width: z.number().int().positive().optional(),
515
- height: z.number().int().positive().optional(),
516
- themeable: z.boolean().optional()
517
- });
518
- const GetCodeParametersSchema = z.object({
519
- nodeId: z.string().describe("Optional target node id; omit to use the current single selection when pulling the baseline snapshot.").optional(),
520
- preferredLang: z.enum(["jsx", "vue"]).describe("Preferred output language to bias the snapshot; otherwise uses the design’s hint/detected language, then falls back to JSX.").optional(),
521
- resolveTokens: z.boolean().describe("Inline token values instead of references for quick renders; default false returns token metadata so you can map into your theming system. When true, values are resolved per-node (mode-aware).").optional(),
522
- vectorMode: z.enum(["smart", "snapshot"]).describe("Vector output mode. `smart` (default) emits `<svg data-src=\"...\">` placeholders in code and preserves themeable instance color on the emitted SVG root markup for downstream adaptation; if asset upload fails after export, the tool may inline the SVG as a fallback to preserve source of truth. `snapshot` preserves vector assets for fidelity. Final vector delivery may still be adapted to the Host app’s SVG policy.").optional()
523
- });
524
- const GetTokenDefsParametersSchema = z.object({
525
- names: z.array(z.string().regex(/^--[a-zA-Z0-9-_]+$/)).min(1).describe("Canonical token names (CSS variable form) from Object.keys(get_code.tokens) or your own list to resolve, e.g., --color-primary."),
526
- includeAllModes: z.boolean().describe("Include all token modes (light/dark/etc.) instead of just the active one to mirror responsive tokens; default false.").optional()
527
- });
528
- const GetScreenshotParametersSchema = z.object({ nodeId: z.string().describe("Optional node id to screenshot; defaults to the current single selection. Useful when layout/overlap is uncertain (auto-layout none/inferred).").optional() });
529
- const GetStructureParametersSchema = z.object({
530
- nodeId: z.string().describe("Optional node id to outline; defaults to the current single selection. Useful when auto-layout hints are none/inferred or you need explicit geometry for refactors.").optional(),
531
- options: z.object({ depth: z.number().int().positive().describe("Limit traversal depth; defaults to full tree (subject to safety caps).").optional() }).optional()
532
- });
533
- const GetDesignSystemParametersSchema = z.object({ query: z.string().trim().min(1).max(500).describe("Optional task or design-system query used to rank matching components and variables.").optional() }).strict();
534
- const CanvasDesignReferenceSchema = z.object({
535
- id: z.string().min(1).describe("Live Figma node or variable id.").optional(),
536
- key: z.string().min(1).describe("Importable Figma library key.").optional()
537
- }).strict().refine((reference) => reference.id !== void 0 || reference.key !== void 0, { message: "A design-system reference requires id or key." });
538
- const CanvasNodeTypeSchema = z.enum([
539
- "ELLIPSE",
540
- "FRAME",
541
- "INSTANCE",
542
- "LINE",
543
- "RECTANGLE",
544
- "TEXT"
545
- ]);
546
- const CanvasColorSchema = z.string().regex(/^#[\dA-Fa-f]{6}(?:[\dA-Fa-f]{2})?$/, "Use #RRGGBB or #RRGGBBAA.");
547
- const CanvasFiniteNumberSchema = z.number().finite();
548
- const CanvasNonnegativeNumberSchema = z.number().nonnegative().finite();
549
- const CanvasPositiveNumberSchema = z.number().positive().finite();
550
- const CanvasPositionSchema = z.object({
551
- x: CanvasFiniteNumberSchema.optional(),
552
- y: CanvasFiniteNumberSchema.optional()
553
- }).strict();
554
- const CanvasSizeSchema = z.object({
555
- width: CanvasPositiveNumberSchema.optional(),
556
- height: CanvasPositiveNumberSchema.optional(),
557
- horizontal: z.enum([
558
- "FILL",
559
- "FIXED",
560
- "HUG"
561
- ]).optional(),
562
- vertical: z.enum([
563
- "FILL",
564
- "FIXED",
565
- "HUG"
566
- ]).optional()
567
- }).strict();
568
- const CanvasPaddingSchema = z.object({
569
- top: CanvasNonnegativeNumberSchema.optional(),
570
- right: CanvasNonnegativeNumberSchema.optional(),
571
- bottom: CanvasNonnegativeNumberSchema.optional(),
572
- left: CanvasNonnegativeNumberSchema.optional()
573
- }).strict();
574
- const CanvasLayoutSchema = z.object({
575
- mode: z.enum([
576
- "HORIZONTAL",
577
- "NONE",
578
- "VERTICAL"
579
- ]).optional(),
580
- gap: CanvasFiniteNumberSchema.optional(),
581
- padding: z.union([CanvasNonnegativeNumberSchema, CanvasPaddingSchema]).optional(),
582
- primaryAlign: z.enum([
583
- "CENTER",
584
- "MAX",
585
- "MIN",
586
- "SPACE_BETWEEN"
587
- ]).optional(),
588
- counterAlign: z.enum([
589
- "BASELINE",
590
- "CENTER",
591
- "MAX",
592
- "MIN"
593
- ]).optional()
594
- }).strict();
595
- const CanvasAppearanceSchema = z.object({
596
- fill: CanvasColorSchema.nullable().optional(),
597
- stroke: CanvasColorSchema.nullable().optional(),
598
- strokeWeight: CanvasNonnegativeNumberSchema.optional(),
599
- cornerRadius: CanvasNonnegativeNumberSchema.optional(),
600
- opacity: z.number().min(0).max(1).finite().optional()
601
- }).strict();
602
- const CanvasTextSchema = z.object({
603
- characters: z.string().max(1e5).optional(),
604
- fontFamily: z.string().min(1).max(200).optional(),
605
- fontStyle: z.string().min(1).max(200).optional(),
606
- fontSize: CanvasPositiveNumberSchema.optional(),
607
- lineHeight: CanvasPositiveNumberSchema.optional(),
608
- letterSpacing: CanvasFiniteNumberSchema.optional(),
609
- alignHorizontal: z.enum([
610
- "CENTER",
611
- "JUSTIFIED",
612
- "LEFT",
613
- "RIGHT"
614
- ]).optional(),
615
- alignVertical: z.enum([
616
- "BOTTOM",
617
- "CENTER",
618
- "TOP"
619
- ]).optional()
620
- }).strict();
621
- const CanvasVariableBindingsSchema = z.object({
622
- fill: CanvasDesignReferenceSchema.optional(),
623
- stroke: CanvasDesignReferenceSchema.optional(),
624
- width: CanvasDesignReferenceSchema.optional(),
625
- height: CanvasDesignReferenceSchema.optional(),
626
- gap: CanvasDesignReferenceSchema.optional(),
627
- paddingTop: CanvasDesignReferenceSchema.optional(),
628
- paddingRight: CanvasDesignReferenceSchema.optional(),
629
- paddingBottom: CanvasDesignReferenceSchema.optional(),
630
- paddingLeft: CanvasDesignReferenceSchema.optional(),
631
- cornerRadius: CanvasDesignReferenceSchema.optional(),
632
- opacity: CanvasDesignReferenceSchema.optional(),
633
- fontFamily: CanvasDesignReferenceSchema.optional(),
634
- fontStyle: CanvasDesignReferenceSchema.optional(),
635
- fontSize: CanvasDesignReferenceSchema.optional(),
636
- lineHeight: CanvasDesignReferenceSchema.optional(),
637
- letterSpacing: CanvasDesignReferenceSchema.optional()
638
- }).strict();
639
- const MAX_CANVAS_NODES = 100;
640
- const MAX_CANVAS_DEPTH = 12;
641
- const CanvasNodeSpecSchema = z.lazy(() => z.object({
642
- key: z.string().min(1).max(128).regex(/^[\w./:-]+$/, "Use a stable key containing letters, numbers, ., /, :, _, or -.").describe("Agent-stable identity reused across later apply_canvas results."),
643
- nodeId: z.string().min(1).describe("Optional exact live node identity; update mode only.").optional(),
644
- type: CanvasNodeTypeSchema.describe("Native Figma node type."),
645
- name: z.string().max(500).optional(),
646
- visible: z.boolean().optional(),
647
- position: CanvasPositionSchema.optional(),
648
- size: CanvasSizeSchema.optional(),
649
- layout: CanvasLayoutSchema.optional(),
650
- appearance: CanvasAppearanceSchema.optional(),
651
- text: CanvasTextSchema.optional(),
652
- component: CanvasDesignReferenceSchema.describe("Required design-system component reference for INSTANCE nodes.").optional(),
653
- componentProperties: z.record(z.string().min(1), z.union([z.string(), z.boolean()])).describe("Exposed component property values for an INSTANCE.").optional(),
654
- variables: CanvasVariableBindingsSchema.describe("Figma variable bindings. A binding wins over a literal for the same field.").optional(),
655
- children: z.array(CanvasNodeSpecSchema).max(MAX_CANVAS_NODES).describe("Desired FRAME children in order; omitted live children are preserved.").optional()
656
- }).strict());
657
- const ApplyCanvasParametersSchema = z.object({
658
- mode: z.enum(["create", "update"]).describe("Create one new FRAME tree, or update one explicitly scoped live subtree."),
659
- targetNodeId: z.string().min(1).describe("Required update-scope root node id; invalid in create mode.").optional(),
660
- root: CanvasNodeSpecSchema.describe("Declarative desired result. Omitted fields and live children are preserved.")
661
- }).strict().superRefine((value, context) => {
662
- function addIssue(message, path) {
663
- context.addIssue({
664
- code: "custom",
665
- message,
666
- path
653
+ async function loadConversation(conversationId, signal) {
654
+ if (!/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(conversationId)) throw new Error("Open the original conversation in Codex before sending these comments.");
655
+ const url = `codex://threads/${conversationId}`;
656
+ const command = process.platform === "darwin" ? {
657
+ file: "open",
658
+ args: ["-g", url]
659
+ } : process.platform === "win32" ? {
660
+ file: "rundll32.exe",
661
+ args: ["url.dll,FileProtocolHandler", url]
662
+ } : void 0;
663
+ if (!command) throw new Error("Open the original conversation in Codex before sending these comments.");
664
+ await promisify(execFile)(command.file, command.args, {
665
+ signal,
666
+ timeout: 5e3
667
+ });
668
+ }
669
+ function isUnloadedConversation(error) {
670
+ return error instanceof CodexIpcError && !error.uncertain && error.message === "no-client-found";
671
+ }
672
+ var CodexAppFeedback = class {
673
+ directory;
674
+ open;
675
+ retryMs;
676
+ load;
677
+ nativeQueue;
678
+ shutdown = new AbortController();
679
+ cancelledTasks = /* @__PURE__ */ new Set();
680
+ taskConversations = /* @__PURE__ */ new Map();
681
+ queues = /* @__PURE__ */ new Map();
682
+ availability = /* @__PURE__ */ new Map();
683
+ constructor(directory, open = () => CodexIpc.open(), retryMs = 1e3, load = loadConversation, nativeQueue = new CodexNativeQueue()) {
684
+ this.directory = directory;
685
+ this.open = open;
686
+ this.retryMs = retryMs;
687
+ this.load = load;
688
+ this.nativeQueue = nativeQueue;
689
+ }
690
+ async available(binding) {
691
+ const { sessionId } = binding.client;
692
+ if (!sessionId || !nativeFeedback(binding.client) || this.shutdown.signal.aborted) return false;
693
+ const cached = this.availability.get(sessionId);
694
+ if (cached && cached.expiresAt > Date.now()) return cached.available;
695
+ let connection;
696
+ let available = false;
697
+ try {
698
+ connection = await this.open();
699
+ await connection.owner(sessionId, void 0, 2e3);
700
+ available = true;
701
+ } catch {} finally {
702
+ connection?.close();
703
+ }
704
+ if (this.availability.size >= 256) this.availability.clear();
705
+ this.availability.set(sessionId, {
706
+ available,
707
+ expiresAt: Date.now() + 1e4
667
708
  });
709
+ return available;
710
+ }
711
+ enqueue(binding, taskId, feedback, signal, beforeSend, onDispatch) {
712
+ const conversationId = binding.client.sessionId;
713
+ if (this.cancelledTasks.has(taskId)) return Promise.reject(/* @__PURE__ */ new Error("These design comments were cancelled."));
714
+ if (!conversationId || !["queue", "steer"].includes(feedback.mode)) return Promise.reject(/* @__PURE__ */ new Error("Native Codex delivery requires Queue or Steer comments."));
715
+ if (feedback.mode === "steer" && this.queues.has(conversationId)) return Promise.reject(/* @__PURE__ */ new Error("Codex already has a pending delivery. Comments are saved; retry when it finishes."));
716
+ if (this.queues.size >= 128) return Promise.reject(/* @__PURE__ */ new Error("Too many pending Codex conversations."));
717
+ this.taskConversations.set(taskId, conversationId);
718
+ const combined = AbortSignal.any([signal, this.shutdown.signal]);
719
+ return this.schedule(conversationId, () => this.deliver(conversationId, taskId, feedback, combined, beforeSend, onDispatch));
720
+ }
721
+ schedule(conversationId, action) {
722
+ const pending = (this.queues.get(conversationId) ?? Promise.resolve()).catch(() => {}).then(action);
723
+ this.queues.set(conversationId, pending);
724
+ pending.finally(() => {
725
+ if (this.queues.get(conversationId) === pending) this.queues.delete(conversationId);
726
+ }).catch(() => {});
727
+ return pending;
728
+ }
729
+ async deliver(conversationId, taskId, feedback, signal, beforeSend, onDispatch) {
730
+ const hash = (text) => createHash("sha256").update(text).digest("hex");
731
+ const key = hash(JSON.stringify([
732
+ conversationId,
733
+ feedback.fileKey,
734
+ feedback.id
735
+ ]));
736
+ const signature = hash(JSON.stringify(feedback));
737
+ const path = join(this.directory, `${key}.json`);
738
+ const deadline = Date.now() + 3e5;
739
+ let loaded = false;
740
+ let nativeQueueUnavailable = false;
741
+ await mkdir(this.directory, {
742
+ recursive: true,
743
+ mode: 448
744
+ });
745
+ while (true) {
746
+ signal.throwIfAborted();
747
+ beforeSend();
748
+ let existing;
749
+ try {
750
+ existing = JSON.parse(await readFile(path, "utf8"));
751
+ } catch (error) {
752
+ if (error.code !== "ENOENT") throw error;
753
+ }
754
+ if (existing) {
755
+ if (existing.signature !== signature || existing.taskId && existing.taskId !== taskId) throw new Error("This comment delivery ID already belongs to different content or task.");
756
+ onDispatch();
757
+ if (existing.status === "delivered") return;
758
+ if (["cancelled", "removed"].includes(existing.status)) throw new Error("These queued comments were cancelled.");
759
+ if (existing.delivery === "queue" && (await this.nativeQueue.read(conversationId, existing.backend)).some((message) => message.id === feedback.id)) {
760
+ await this.saveReceipt(path, {
761
+ ...existing,
762
+ status: "delivered"
763
+ });
764
+ return;
765
+ }
766
+ throw new Error("Earlier Codex delivery is uncertain. Check the original conversation; these comments will not be resent automatically.");
767
+ }
768
+ if (feedback.mode === "queue" && nativeQueueUnavailable && !await this.nativeQueue.areQueuesEmpty(conversationId)) {
769
+ if (Date.now() >= deadline) throw new Error("Codex still has queued messages. Comments are saved; retry later.");
770
+ await setTimeout$1(this.retryMs, void 0, { signal });
771
+ continue;
772
+ }
773
+ const connection = await this.open();
774
+ try {
775
+ let owner;
776
+ try {
777
+ owner = await connection.owner(conversationId, signal);
778
+ } catch (error) {
779
+ if (!isUnloadedConversation(error) || loaded) throw error;
780
+ signal.throwIfAborted();
781
+ beforeSend();
782
+ loaded = true;
783
+ owner = await this.loadOwner(connection, conversationId, signal, beforeSend);
784
+ }
785
+ this.availability.delete(conversationId);
786
+ signal.throwIfAborted();
787
+ beforeSend();
788
+ await writeFile(path, JSON.stringify({
789
+ signature,
790
+ status: "pending"
791
+ }), {
792
+ flag: "wx",
793
+ mode: 384
794
+ });
795
+ try {
796
+ signal.throwIfAborted();
797
+ beforeSend();
798
+ } catch (error) {
799
+ await unlink(path);
800
+ throw error;
801
+ }
802
+ if (feedback.mode === "queue" && !nativeQueueUnavailable) {
803
+ const receipt = {
804
+ signature,
805
+ status: "pending",
806
+ delivery: "queue",
807
+ conversationId,
808
+ taskId,
809
+ messageId: feedback.id
810
+ };
811
+ let attempted = false;
812
+ try {
813
+ await this.nativeQueue.admit(connection, owner, conversationId, taskId, feedback, signal, async (backend) => {
814
+ receipt.backend = backend;
815
+ await this.saveReceipt(path, receipt);
816
+ signal.throwIfAborted();
817
+ beforeSend();
818
+ }, () => {
819
+ beforeSend();
820
+ attempted = true;
821
+ });
822
+ onDispatch();
823
+ await this.saveReceipt(path, {
824
+ ...receipt,
825
+ status: "delivered"
826
+ });
827
+ return;
828
+ } catch (error) {
829
+ if (!attempted || error instanceof CodexIpcError && !error.uncertain) {
830
+ await unlink(path);
831
+ if (!(error instanceof CodexQueueUnavailable)) throw error;
832
+ nativeQueueUnavailable = true;
833
+ if (!await this.nativeQueue.areQueuesEmpty(conversationId)) continue;
834
+ await writeFile(path, JSON.stringify({
835
+ signature,
836
+ status: "pending"
837
+ }), {
838
+ flag: "wx",
839
+ mode: 384
840
+ });
841
+ } else {
842
+ onDispatch();
843
+ if (await this.nativeQueue.read(conversationId, receipt.backend).then((messages) => messages.some((message) => message.id === feedback.id)).catch(() => false)) {
844
+ await this.saveReceipt(path, {
845
+ ...receipt,
846
+ status: "delivered"
847
+ });
848
+ return;
849
+ }
850
+ throw new Error("Codex queue admission is uncertain. Check the original conversation; comments will not be queued again automatically.", { cause: error });
851
+ }
852
+ }
853
+ }
854
+ let response;
855
+ let steered = false;
856
+ try {
857
+ response = await connection.request("thread-follower-start-turn", 2, {
858
+ conversationId,
859
+ turnStart: codexFeedbackTurn(conversationId, taskId, feedback)
860
+ }, owner, signal);
861
+ } catch (error) {
862
+ if (!(error instanceof CodexIpcError) || error.uncertain || error.message !== "App context must wait until the current turn finishes") {
863
+ onDispatch();
864
+ throw new Error("Codex delivery could not be confirmed. Check the original conversation; drafts are retained and will not be resent automatically.", { cause: error });
865
+ }
866
+ if (feedback.mode === "steer") {
867
+ try {
868
+ signal.throwIfAborted();
869
+ beforeSend();
870
+ } catch (error) {
871
+ await unlink(path);
872
+ throw error;
873
+ }
874
+ try {
875
+ steered = true;
876
+ response = await connection.request("thread-follower-steer-turn", 1, codexFeedbackSteer(conversationId, taskId, feedback), owner, signal);
877
+ } catch (error) {
878
+ if (error instanceof CodexIpcError && !error.uncertain && error.message === `Cannot steer conversation ${conversationId} because its active turn already ended`) {
879
+ await unlink(path);
880
+ throw new Error("Codex finished before Steer arrived. Comments are saved; retry to start a new response.", { cause: error });
881
+ }
882
+ onDispatch();
883
+ throw new Error("Codex Steer could not be confirmed. Check the original conversation; drafts are retained and will not be resent automatically.", { cause: error });
884
+ }
885
+ } else {
886
+ await unlink(path);
887
+ if (Date.now() >= deadline) throw new Error("Codex is still busy. Comments are saved; retry when the current response ends.", { cause: error });
888
+ response = {};
889
+ }
890
+ }
891
+ if (response.resultType === "success") {
892
+ onDispatch();
893
+ const result = response.result;
894
+ const turnId = steered ? result?.result?.turnId : result?.result?.turn?.id;
895
+ if (response.handledByClientId !== owner || typeof turnId !== "string" || !turnId) throw new Error("Codex did not confirm the feedback turn. Check the conversation before retrying.");
896
+ const temp = `${path}.${randomUUID()}.tmp`;
897
+ await writeFile(temp, JSON.stringify({
898
+ signature,
899
+ status: "delivered",
900
+ turnId
901
+ }), { mode: 384 });
902
+ await rename(temp, path);
903
+ return;
904
+ }
905
+ } finally {
906
+ connection.close();
907
+ }
908
+ await setTimeout$1(this.retryMs, void 0, { signal });
909
+ }
668
910
  }
669
- if (value.mode === "create") {
670
- if (value.targetNodeId !== void 0) addIssue("targetNodeId is only valid in update mode.", ["targetNodeId"]);
671
- if (value.root.type !== "FRAME") addIssue("Create mode requires a FRAME root.", ["root", "type"]);
672
- } else {
673
- if (value.targetNodeId === void 0) addIssue("Update mode requires targetNodeId.", ["targetNodeId"]);
674
- if (value.root.nodeId !== void 0 && value.root.nodeId !== value.targetNodeId) addIssue("The root nodeId must match targetNodeId in update mode.", ["root", "nodeId"]);
675
- }
676
- const keys = /* @__PURE__ */ new Set();
677
- const nodeIds = /* @__PURE__ */ new Set();
678
- const stack = [{
679
- depth: 1,
680
- node: value.root,
681
- path: ["root"]
682
- }];
683
- let count = 0;
684
- while (stack.length) {
685
- const { depth, node, path } = stack.pop();
686
- count += 1;
687
- if (count > MAX_CANVAS_NODES) {
688
- addIssue(`Canvas specs may contain at most ${MAX_CANVAS_NODES} nodes.`, ["root"]);
689
- break;
690
- }
691
- if (depth > MAX_CANVAS_DEPTH) addIssue(`Canvas specs may be at most ${MAX_CANVAS_DEPTH} levels deep.`, path);
692
- if (keys.has(node.key)) addIssue(`Duplicate canvas key "${node.key}".`, [...path, "key"]);
693
- keys.add(node.key);
694
- if (node.nodeId) {
695
- if (value.mode === "create") addIssue("Create mode cannot reference existing nodeIds.", [...path, "nodeId"]);
696
- if (nodeIds.has(node.nodeId)) addIssue(`Duplicate nodeId "${node.nodeId}".`, [...path, "nodeId"]);
697
- nodeIds.add(node.nodeId);
698
- }
699
- if (node.type === "INSTANCE" && !node.component) addIssue("INSTANCE nodes require a component reference.", [...path, "component"]);
700
- if (node.type !== "INSTANCE" && node.component) addIssue("Only INSTANCE nodes accept a component reference.", [...path, "component"]);
701
- if (node.type !== "INSTANCE" && node.componentProperties) addIssue("Only INSTANCE nodes accept componentProperties.", [...path, "componentProperties"]);
702
- if (node.type !== "TEXT" && node.text) addIssue("Only TEXT nodes accept text properties.", [...path, "text"]);
703
- if (node.type !== "FRAME" && node.layout) addIssue("Only FRAME nodes accept layout properties.", [...path, "layout"]);
704
- if (node.type !== "FRAME" && node.children !== void 0) addIssue("Only FRAME nodes may declare children.", [...path, "children"]);
705
- node.children?.forEach((child, index) => {
706
- stack.push({
707
- depth: depth + 1,
708
- node: child,
709
- path: [
710
- ...path,
711
- "children",
712
- index
713
- ]
911
+ async saveReceipt(path, receipt) {
912
+ const temp = `${path}.${randomUUID()}.tmp`;
913
+ try {
914
+ await writeFile(temp, JSON.stringify(receipt), { mode: 384 });
915
+ await rename(temp, path);
916
+ } finally {
917
+ await unlink(temp).catch(() => {});
918
+ }
919
+ }
920
+ /** Fence receipts first, then remove only this task's native queue entries. */
921
+ async cancelQueued(taskId) {
922
+ this.cancelledTasks.add(taskId);
923
+ const pendingConversation = this.taskConversations.get(taskId);
924
+ if (pendingConversation) await this.queues.get(pendingConversation)?.catch(() => {});
925
+ const queues = /* @__PURE__ */ new Map();
926
+ for (const { receipt } of await this.queueReceipts()) if (receipt.taskId === taskId) queues.set(JSON.stringify([receipt.conversationId, receipt.backend ?? "legacy"]), receipt);
927
+ for (const { conversationId, backend = "legacy" } of queues.values()) await this.schedule(conversationId, async () => {
928
+ const receipts = (await this.queueReceipts()).filter(({ receipt }) => receipt.taskId === taskId && receipt.conversationId === conversationId && (receipt.backend ?? "legacy") === backend && receipt.messageId);
929
+ if (!receipts.length) return;
930
+ const ids = new Set(receipts.map(({ receipt }) => receipt.messageId));
931
+ for (const { path, receipt } of receipts) if (receipt.status !== "removed") await this.saveReceipt(path, {
932
+ ...receipt,
933
+ status: "cancelled"
714
934
  });
935
+ const hasMessages = (await this.nativeQueue.read(conversationId, backend)).some((message) => ids.has(message.id));
936
+ let connection;
937
+ try {
938
+ if (hasMessages) {
939
+ let owner;
940
+ if (backend === "legacy") {
941
+ connection = await this.open();
942
+ owner = await connection.owner(conversationId, this.shutdown.signal);
943
+ }
944
+ await this.nativeQueue.remove(connection, owner, conversationId, ids, this.shutdown.signal, backend);
945
+ }
946
+ for (const { path, receipt } of receipts) if (hasMessages || receipt.status !== "removed") await this.saveReceipt(path, {
947
+ ...receipt,
948
+ status: "removed"
949
+ });
950
+ } finally {
951
+ connection?.close();
952
+ }
715
953
  });
716
954
  }
955
+ async reconcileQueued(isCancelled) {
956
+ const tasks = /* @__PURE__ */ new Set();
957
+ const snapshots = /* @__PURE__ */ new Map();
958
+ for (const { receipt } of await this.queueReceipts()) {
959
+ if (!["cancelled", "removed"].includes(receipt.status) && !isCancelled(receipt.taskId)) continue;
960
+ if (receipt.status !== "removed") {
961
+ tasks.add(receipt.taskId);
962
+ continue;
963
+ }
964
+ const key = JSON.stringify([receipt.conversationId, receipt.backend ?? "legacy"]);
965
+ let ids = snapshots.get(key);
966
+ if (!ids) {
967
+ const messages = await this.nativeQueue.read(receipt.conversationId, receipt.backend).catch(() => void 0);
968
+ if (!messages) continue;
969
+ ids = new Set(messages.map((message) => message.id));
970
+ snapshots.set(key, ids);
971
+ }
972
+ if (ids.has(receipt.messageId)) tasks.add(receipt.taskId);
973
+ }
974
+ for (const task of tasks) await this.cancelQueued(task).catch(() => {});
975
+ }
976
+ async queueReceipts() {
977
+ const entries = [];
978
+ const files = await readdir(this.directory).catch((error) => {
979
+ if (error.code === "ENOENT") return [];
980
+ throw error;
981
+ });
982
+ for (const file of files) {
983
+ if (!/^[a-f0-9]{64}\.json$/.test(file)) continue;
984
+ const path = join(this.directory, file);
985
+ try {
986
+ const receipt = JSON.parse(await readFile(path, "utf8"));
987
+ if (receipt?.delivery === "queue" && typeof receipt.signature === "string" && typeof receipt.status === "string" && typeof receipt.conversationId === "string" && typeof receipt.taskId === "string" && (receipt.backend === void 0 || receipt.backend === "legacy" || receipt.backend === "server") && typeof receipt.messageId === "string") entries.push({
988
+ path,
989
+ receipt
990
+ });
991
+ } catch {}
992
+ }
993
+ return entries;
994
+ }
995
+ async loadOwner(connection, conversationId, signal, beforeSend) {
996
+ try {
997
+ await this.load(conversationId, signal);
998
+ const deadline = Date.now() + 5e3;
999
+ while (true) {
1000
+ signal.throwIfAborted();
1001
+ beforeSend();
1002
+ try {
1003
+ return await connection.owner(conversationId, signal, Math.max(1, Math.min(1e3, deadline - Date.now())));
1004
+ } catch (error) {
1005
+ if (!isUnloadedConversation(error) && !(error instanceof CodexDiscoveryError) || Date.now() >= deadline) throw error;
1006
+ }
1007
+ await setTimeout$1(Math.min(this.retryMs, 250), void 0, { signal });
1008
+ }
1009
+ } catch (error) {
1010
+ signal.throwIfAborted();
1011
+ beforeSend();
1012
+ throw new Error(`Codex could not load the original conversation. Comments are saved. ${error instanceof Error ? error.message : "Try opening the original conversation in Codex."}`, { cause: error });
1013
+ }
1014
+ }
1015
+ close() {
1016
+ this.shutdown.abort();
1017
+ this.nativeQueue.close();
1018
+ }
1019
+ };
1020
+ //#endregion
1021
+ //#region src/agent-clients/codex-turn-state.ts
1022
+ function object$1(value) {
1023
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Unsupported Codex lifecycle value.");
1024
+ return value;
1025
+ }
1026
+ function turn(value) {
1027
+ const source = object$1(value);
1028
+ const result = {};
1029
+ for (const field of ["turnId", "status"]) {
1030
+ const value = source[field];
1031
+ if (value == null) continue;
1032
+ if (typeof value !== "string") throw new Error("Unsupported Codex turn field.");
1033
+ result[field] = value;
1034
+ }
1035
+ return result;
1036
+ }
1037
+ /** A projection of the native stream, containing no messages or tool results. */
1038
+ var CodexTurnState = class {
1039
+ conversationId;
1040
+ legacy;
1041
+ canonical;
1042
+ kind;
1043
+ constructor(value, conversationId) {
1044
+ this.conversationId = conversationId;
1045
+ this.snapshot(value);
1046
+ }
1047
+ snapshot(value) {
1048
+ const state = object$1(value);
1049
+ if (state.id !== this.conversationId) throw new Error("Unexpected Codex conversation snapshot.");
1050
+ this.legacy = Array.isArray(state.turns) ? state.turns.map(turn) : void 0;
1051
+ this.history(state.turnHistory);
1052
+ }
1053
+ entities(value) {
1054
+ this.canonical = new Map(Object.entries(object$1(value)).map(([key, value]) => [key, turn(value)]));
1055
+ }
1056
+ history(value) {
1057
+ this.setKind(value == null ? void 0 : object$1(value).kind);
1058
+ this.canonical = void 0;
1059
+ if (this.kind === "canonical") this.entities(object$1(object$1(value).history).entitiesByKey);
1060
+ }
1061
+ setKind(value) {
1062
+ if (value !== void 0 && value !== "canonical" && value !== "legacy") throw new Error("Unsupported Codex history kind.");
1063
+ this.kind = value;
1064
+ }
1065
+ state() {
1066
+ const entries = this.kind === "canonical" ? this.canonical?.values() : this.legacy;
1067
+ if (!entries) throw new Error("Unsupported Codex turn history.");
1068
+ const turns = [];
1069
+ for (const entry of entries) if (typeof entry.turnId === "string" && typeof entry.status === "string") turns.push({
1070
+ turnId: entry.turnId,
1071
+ status: entry.status
1072
+ });
1073
+ return { turns };
1074
+ }
1075
+ /** Publish only after the entire batch succeeds; discard this projection on failure. */
1076
+ apply(patches) {
1077
+ let changed = false;
1078
+ for (const value of patches) {
1079
+ const patch = object$1(value);
1080
+ const path = patch.path;
1081
+ if (!Array.isArray(path)) throw new Error("Unsupported Codex state patch.");
1082
+ if (path.length && ![
1083
+ "id",
1084
+ "turns",
1085
+ "turnHistory"
1086
+ ].includes(path[0])) continue;
1087
+ if (path[0] === "turns" && path.length > 2 && !["turnId", "status"].includes(path[2])) continue;
1088
+ if (path[0] === "turnHistory" && path.length > 1) {
1089
+ if (!["kind", "history"].includes(path[1])) continue;
1090
+ if (path[1] === "history" && path.length > 2 && path[2] !== "entitiesByKey") continue;
1091
+ if (path.length > 4 && !["turnId", "status"].includes(path[4])) continue;
1092
+ }
1093
+ const op = patch.op;
1094
+ if (typeof op !== "string" || ![
1095
+ "add",
1096
+ "replace",
1097
+ "remove"
1098
+ ].includes(op)) throw new Error("Unsupported Codex lifecycle operation.");
1099
+ changed = true;
1100
+ const next = op === "remove" ? void 0 : patch.value;
1101
+ if (!path.length) this.snapshot(next);
1102
+ else if (path[0] === "id") {
1103
+ if (path.length !== 1 || next !== this.conversationId) throw new Error("Unexpected Codex conversation patch.");
1104
+ } else if (path[0] === "turns") this.patchLegacy(path, op, next);
1105
+ else this.patchHistory(path, op, next);
1106
+ }
1107
+ return changed;
1108
+ }
1109
+ patchLegacy(path, op, next) {
1110
+ if (path.length === 1) {
1111
+ if (next !== void 0 && !Array.isArray(next)) throw new Error("Unsupported Codex turns.");
1112
+ this.legacy = next?.map(turn);
1113
+ return;
1114
+ }
1115
+ const entries = this.legacy;
1116
+ if (!entries) throw new Error("Missing Codex turns.");
1117
+ const index = path[1];
1118
+ if (index === "length" && path.length === 2 && op === "replace") {
1119
+ if (typeof next !== "number" || !Number.isSafeInteger(next) || next < 0 || next > entries.length) throw new Error("Unsupported Codex turn array length.");
1120
+ entries.length = next;
1121
+ return;
1122
+ }
1123
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0 || index > entries.length) throw new Error("Unsupported Codex turn index.");
1124
+ if (path.length === 2 && op === "add") {
1125
+ entries.splice(index, 0, turn(next));
1126
+ return;
1127
+ }
1128
+ if (index === entries.length) throw new Error("Missing Codex turn.");
1129
+ if (path.length > 2) this.field(entries[index], path.slice(2), next);
1130
+ else if (op === "remove") entries.splice(index, 1);
1131
+ else entries[index] = turn(next);
1132
+ }
1133
+ patchHistory(path, op, next) {
1134
+ if (path.length === 1) {
1135
+ this.history(next);
1136
+ return;
1137
+ }
1138
+ if (path[1] === "kind" && path.length === 2) {
1139
+ this.setKind(next);
1140
+ return;
1141
+ }
1142
+ if (path[1] !== "history") throw new Error("Unsupported Codex lifecycle path.");
1143
+ if (path.length <= 3) {
1144
+ this.canonical = void 0;
1145
+ if (next !== void 0) this.entities(path.length === 2 ? object$1(next).entitiesByKey : next);
1146
+ return;
1147
+ }
1148
+ const entries = this.canonical;
1149
+ const key = path[3];
1150
+ if (!entries || typeof key !== "string") throw new Error("Unsupported Codex turn key.");
1151
+ if (path.length === 4) {
1152
+ if (op === "remove") entries.delete(key);
1153
+ else entries.set(key, turn(next));
1154
+ return;
1155
+ }
1156
+ const entry = entries.get(key);
1157
+ if (!entry) throw new Error("Missing Codex turn.");
1158
+ this.field(entry, path.slice(4), next);
1159
+ }
1160
+ field(entry, path, value) {
1161
+ const field = path[0];
1162
+ if (path.length !== 1 || field !== "turnId" && field !== "status") throw new Error("Unsupported Codex turn field path.");
1163
+ if (value == null) delete entry[field];
1164
+ else if (typeof value === "string") entry[field] = value;
1165
+ else throw new Error("Unsupported Codex turn field.");
1166
+ }
1167
+ };
1168
+ //#endregion
1169
+ //#region src/agent-clients/codex-lifecycle.ts
1170
+ function object(value) {
1171
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1172
+ }
1173
+ /** Follow the existing App owner. Never start another app-server or acquire ownership. */
1174
+ var CodexAppLifecycle = class {
1175
+ changed;
1176
+ open;
1177
+ retryMs;
1178
+ snapshotTimeoutMs;
1179
+ watches = /* @__PURE__ */ new Map();
1180
+ closed = false;
1181
+ constructor(changed, open = () => CodexIpc.open(), retryMs = 2e3, snapshotTimeoutMs = 5e3) {
1182
+ this.changed = changed;
1183
+ this.open = open;
1184
+ this.retryMs = retryMs;
1185
+ this.snapshotTimeoutMs = snapshotTimeoutMs;
1186
+ }
1187
+ watch(conversationId) {
1188
+ if (this.closed || this.watches.has(conversationId) || this.watches.size >= 128) return;
1189
+ const watch = {
1190
+ controller: new AbortController(),
1191
+ state: void 0
1192
+ };
1193
+ this.watches.set(conversationId, watch);
1194
+ this.follow(conversationId, watch);
1195
+ }
1196
+ state(conversationId) {
1197
+ return this.watches.get(conversationId)?.state;
1198
+ }
1199
+ retain(conversationIds) {
1200
+ for (const [id, watch] of this.watches) {
1201
+ if (conversationIds.has(id)) continue;
1202
+ watch.controller.abort();
1203
+ this.watches.delete(id);
1204
+ }
1205
+ }
1206
+ async interrupt(conversationId, expectedTurnId) {
1207
+ const connection = await this.open();
1208
+ try {
1209
+ const owner = await connection.owner(conversationId, void 0, 2e3);
1210
+ const response = await connection.request("thread-follower-interrupt-turn", 4, {
1211
+ conversationId,
1212
+ mode: "user-stop",
1213
+ expectedTurnId
1214
+ }, owner);
1215
+ const result = object(response.result);
1216
+ if (response.handledByClientId !== owner || result.ok !== true || result.interruptedTurnId !== null && result.interruptedTurnId !== expectedTurnId) throw new Error("Codex did not confirm the requested turn interruption.");
1217
+ return result.interruptedTurnId === expectedTurnId;
1218
+ } finally {
1219
+ connection.close();
1220
+ }
1221
+ }
1222
+ async follow(conversationId, watch) {
1223
+ const signal = watch.controller.signal;
1224
+ const publish = (state) => {
1225
+ if (signal.aborted) return;
1226
+ const changed = JSON.stringify(watch.state) !== JSON.stringify(state);
1227
+ watch.state = state;
1228
+ if (changed) this.changed(conversationId, state);
1229
+ };
1230
+ while (!signal.aborted) {
1231
+ let connection;
1232
+ let owner;
1233
+ let timer;
1234
+ const cleanups = [];
1235
+ try {
1236
+ connection = await this.open();
1237
+ signal.throwIfAborted();
1238
+ owner = await connection.owner(conversationId, signal, 2e3);
1239
+ signal.throwIfAborted();
1240
+ const ipc = connection;
1241
+ const ownerId = owner;
1242
+ await new Promise((resolve, reject) => {
1243
+ let revision;
1244
+ let turns;
1245
+ let awaitingSnapshot = false;
1246
+ const requestSnapshot = () => {
1247
+ if (awaitingSnapshot) return;
1248
+ awaitingSnapshot = true;
1249
+ turns = void 0;
1250
+ publish();
1251
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error("Codex snapshot timed out.")), this.snapshotTimeoutMs);
1252
+ ipc.broadcast("thread-stream-following-changed", 1, {
1253
+ hostId: "local",
1254
+ conversationId,
1255
+ following: true
1256
+ }, [ownerId]);
1257
+ };
1258
+ cleanups.push(ipc.onDisconnect(resolve));
1259
+ const abort = () => resolve();
1260
+ signal.addEventListener("abort", abort, { once: true });
1261
+ cleanups.push(() => signal.removeEventListener("abort", abort));
1262
+ cleanups.push(ipc.onBroadcast((message) => {
1263
+ try {
1264
+ const params = object(message.params);
1265
+ if (message.method === "ipc-connection-reset" || message.method === "client-status-changed" && params.clientId === ownerId && params.status === "disconnected") {
1266
+ resolve();
1267
+ return;
1268
+ }
1269
+ if (params.hostId !== "local" || params.conversationId !== conversationId || message.sourceClientId !== ownerId) return;
1270
+ if (message.method === "thread-stream-following-status-requested") {
1271
+ ipc.broadcast("thread-stream-following-changed", 1, {
1272
+ hostId: "local",
1273
+ conversationId,
1274
+ following: true
1275
+ }, [ownerId]);
1276
+ return;
1277
+ }
1278
+ if (message.method !== "thread-stream-state-changed") return;
1279
+ if (message.version !== 11) throw new Error("Unsupported Codex stream version.");
1280
+ const change = object(params.change);
1281
+ if (!Number.isSafeInteger(change.revision)) throw new Error("Invalid Codex stream revision.");
1282
+ if (change.type === "snapshot") {
1283
+ if (revision !== void 0 && change.revision < revision) return;
1284
+ turns = new CodexTurnState(change.conversationState, conversationId);
1285
+ const state = turns.state();
1286
+ clearTimeout(timer);
1287
+ awaitingSnapshot = false;
1288
+ revision = change.revision;
1289
+ publish(state);
1290
+ } else if (change.type === "patches") {
1291
+ if (awaitingSnapshot) return;
1292
+ if (change.revision <= (revision ?? -1)) return;
1293
+ if (change.baseRevision !== revision || !Array.isArray(change.patches)) {
1294
+ requestSnapshot();
1295
+ return;
1296
+ }
1297
+ revision = change.revision;
1298
+ try {
1299
+ if (!turns) throw new Error("Missing Codex lifecycle snapshot.");
1300
+ if (turns.apply(change.patches)) publish(turns.state());
1301
+ } catch {
1302
+ requestSnapshot();
1303
+ }
1304
+ } else throw new Error("Unsupported Codex stream change.");
1305
+ } catch (error) {
1306
+ reject(error);
1307
+ }
1308
+ }));
1309
+ requestSnapshot();
1310
+ });
1311
+ } catch {} finally {
1312
+ clearTimeout(timer);
1313
+ for (const cleanup of cleanups) cleanup();
1314
+ if (connection && owner) try {
1315
+ connection.broadcast("thread-stream-following-changed", 1, {
1316
+ hostId: "local",
1317
+ conversationId,
1318
+ following: false
1319
+ }, [owner]);
1320
+ } catch {}
1321
+ connection?.close();
1322
+ publish();
1323
+ }
1324
+ if (!signal.aborted) await setTimeout$1(this.retryMs, void 0, { signal }).catch(() => {});
1325
+ }
1326
+ }
1327
+ close() {
1328
+ this.closed = true;
1329
+ this.retain(/* @__PURE__ */ new Set());
1330
+ }
1331
+ };
1332
+ //#endregion
1333
+ //#region src/agent-clients/hooks.ts
1334
+ const ClientHookRequestSchema = z.object({
1335
+ method: z.literal("tempad/client-hook"),
1336
+ params: z.object({
1337
+ version: z.literal(1),
1338
+ kind: z.enum(["codex", "claude"]),
1339
+ sessionId: z.string().min(1).max(256),
1340
+ event: z.enum([
1341
+ "PreToolUse",
1342
+ "PostToolUse",
1343
+ "UserPromptSubmit",
1344
+ "Stop",
1345
+ "Interrupt",
1346
+ "SessionEnd"
1347
+ ]),
1348
+ invocationId: z.string().uuid(),
1349
+ turnId: z.string().min(1).max(256).optional(),
1350
+ taskId: z.string().min(1).max(128).optional()
1351
+ }).strict()
717
1352
  });
718
- const GetAssetsParametersSchema = z.object({ hashes: z.array(z.string().regex(MCP_HASH_PATTERN)).min(1).describe("Asset hashes returned from get_code (or other tools) to download/resolve exact bytes for rasterized images or SVGs before routing through your asset pipeline.") });
719
- const GetAssetsResultSchema = z.object({
720
- assets: z.array(AssetDescriptorSchema),
721
- missing: z.array(z.string().regex(MCP_HASH_PATTERN))
722
- });
1353
+ function scope(kind, sessionId) {
1354
+ return JSON.stringify([kind.startsWith("codex") ? "codex" : kind, sessionId]);
1355
+ }
1356
+ /** Hooks carry lifecycle identity and Stop notices, never design comments. */
1357
+ var ClientHooks = class {
1358
+ sessions = /* @__PURE__ */ new Map();
1359
+ stop(binding, taskId) {
1360
+ const session = this.session(binding);
1361
+ if (session) session.stopNotice = {
1362
+ taskId,
1363
+ turnId: binding.turnId
1364
+ };
1365
+ }
1366
+ disconnect(binding) {
1367
+ const session = this.session(binding);
1368
+ if (session) session.active = false;
1369
+ }
1370
+ session(binding) {
1371
+ const { kind, sessionId } = binding.client;
1372
+ return sessionId ? this.sessions.get(scope(kind, sessionId)) : void 0;
1373
+ }
1374
+ handle(input) {
1375
+ const key = scope(input.kind, input.sessionId);
1376
+ let session = this.sessions.get(key);
1377
+ if (!session) {
1378
+ if (this.sessions.size >= 256) {
1379
+ const inactive = [...this.sessions].find(([, value]) => !value.active);
1380
+ if (!inactive) return {};
1381
+ this.sessions.delete(inactive[0]);
1382
+ }
1383
+ session = {
1384
+ active: false,
1385
+ turnId: input.turnId
1386
+ };
1387
+ this.sessions.set(key, session);
1388
+ }
1389
+ if (input.event === "UserPromptSubmit") {
1390
+ session.turnId = input.turnId;
1391
+ session.stopNotice = void 0;
1392
+ } else if (input.turnId && session.turnId && input.turnId !== session.turnId) return {};
1393
+ else if (input.turnId) session.turnId = input.turnId;
1394
+ const ended = ["Interrupt", "SessionEnd"].includes(input.event);
1395
+ session.active = !ended && input.event !== "Stop";
1396
+ if (ended) return {};
1397
+ const notice = session.stopNotice;
1398
+ if (notice && (!notice.turnId || !input.turnId || notice.turnId === input.turnId)) {
1399
+ session.stopNotice = void 0;
1400
+ if (input.event === "PreToolUse" || input.event === "PostToolUse") return { output: { hookSpecificOutput: {
1401
+ hookEventName: input.event,
1402
+ additionalContext: `The user stopped Figma design task ${notice.taskId}. That task is cancelled and cannot resume. Respect the stop and do not automatically replace it. If further design work is necessary or the user requests it, explicitly begin a new task.`
1403
+ } } };
1404
+ }
1405
+ return {};
1406
+ }
1407
+ };
1408
+ //#endregion
1409
+ //#region src/agent-clients/registry.ts
1410
+ /** A turn is a safe target only when the conversation has exactly one in progress. */
1411
+ function soleActiveTurn(state) {
1412
+ const active = state?.turns.filter((turn) => turn.status === "inProgress");
1413
+ return active?.length === 1 ? active[0].turnId : void 0;
1414
+ }
1415
+ /** Conversation bindings and native delivery stay outside shared task lifecycle logic. */
1416
+ var AgentClients = class {
1417
+ tasks;
1418
+ codex;
1419
+ hooks = new ClientHooks();
1420
+ connections = /* @__PURE__ */ new Map();
1421
+ bindings = /* @__PURE__ */ new Map();
1422
+ actions = /* @__PURE__ */ new Map();
1423
+ feedbackSignals = /* @__PURE__ */ new Map();
1424
+ lifecycle;
1425
+ constructor(tasks, codex, lifecycle) {
1426
+ this.tasks = tasks;
1427
+ this.codex = codex;
1428
+ this.lifecycle = lifecycle?.((id, state) => this.onNativeState(id, state));
1429
+ }
1430
+ onNativeState(conversationId, state) {
1431
+ for (const [ownerId, binding] of this.bindings) {
1432
+ if (nativeConversation(binding.client) !== conversationId) continue;
1433
+ const previous = state?.turns.find((turn) => turn.turnId === binding.turnId);
1434
+ if (previous && [
1435
+ "completed",
1436
+ "interrupted",
1437
+ "failed"
1438
+ ].includes(previous.status)) for (const record of this.tasks.list()) {
1439
+ if (record.ownerId !== ownerId) continue;
1440
+ if (previous.status === "interrupted") this.cancelFeedback(record.task.taskId);
1441
+ this.tasks.stop(record.task.taskId, "paused");
1442
+ }
1443
+ const active = soleActiveTurn(state);
1444
+ if (active && (!binding.turnId || previous && previous.status !== "inProgress")) binding.turnId = active;
1445
+ this.refresh(ownerId);
1446
+ }
1447
+ }
1448
+ clientHook(input) {
1449
+ if (input.kind === "codex") return {};
1450
+ if (input.event === "PostToolUse" && input.taskId) this.event("hook", {
1451
+ method: "notifications/tempad/client-event",
1452
+ params: {
1453
+ event: "taskBound",
1454
+ kind: input.kind,
1455
+ sessionId: input.sessionId,
1456
+ taskId: input.taskId,
1457
+ ...input.turnId ? { turnId: input.turnId } : {}
1458
+ }
1459
+ });
1460
+ const result = this.hooks.handle(input);
1461
+ if ([
1462
+ "UserPromptSubmit",
1463
+ "Stop",
1464
+ "Interrupt",
1465
+ "SessionEnd"
1466
+ ].includes(input.event)) this.event("hook", {
1467
+ method: "notifications/tempad/client-event",
1468
+ params: {
1469
+ event: input.event,
1470
+ kind: input.kind,
1471
+ sessionId: input.sessionId,
1472
+ ...input.turnId ? { turnId: input.turnId } : {}
1473
+ }
1474
+ });
1475
+ for (const [ownerId, binding] of this.bindings) if (binding.client.sessionId === input.sessionId && binding.client.kind === input.kind) this.refresh(ownerId);
1476
+ return result;
1477
+ }
1478
+ event(connectionId, input) {
1479
+ const { params } = ClientEventSchema.parse(input);
1480
+ if (params.event === "connect") {
1481
+ this.connections.set(connectionId, {
1482
+ client: clientDescriptor(params.kind, params.sessionId),
1483
+ ...params.turnId ? { turnId: params.turnId } : {}
1484
+ });
1485
+ return;
1486
+ }
1487
+ if (!params.sessionId) return;
1488
+ if (params.event === "taskBound" && params.taskId) {
1489
+ const record = this.tasks.find(params.taskId);
1490
+ if (!record || record.task.client?.sessionId && record.task.client.sessionId !== params.sessionId) return;
1491
+ const connectionId = record.ownerId.split("/")[0];
1492
+ const previous = this.bindings.get(record.ownerId);
1493
+ if (!previous) return;
1494
+ const kind = ["other", "unknown"].includes(previous.client.kind) ? params.kind : previous.client.kind;
1495
+ const next = {
1496
+ ...previous,
1497
+ client: {
1498
+ ...previous.client,
1499
+ kind,
1500
+ sessionId: params.sessionId
1501
+ },
1502
+ ...params.turnId ? { turnId: params.turnId } : {}
1503
+ };
1504
+ const ownerId = `${connectionId}/${kind}/${params.sessionId}`;
1505
+ this.connections.set(connectionId, next);
1506
+ this.bindings.set(ownerId, next);
1507
+ record.ownerId = ownerId;
1508
+ record.task.client = next.client;
1509
+ this.tasks.attachClient(ownerId, next.client, { ...record.task.capabilities ?? CANVAS_ONLY });
1510
+ return;
1511
+ }
1512
+ for (const record of this.tasks.list()) {
1513
+ const client = record.task.client;
1514
+ if (!client || client.sessionId !== params.sessionId || client.kind !== params.kind && !(params.kind === "codex" && client.kind.startsWith("codex"))) continue;
1515
+ const bound = this.bindings.get(record.ownerId);
1516
+ if (params.event === "UserPromptSubmit") {
1517
+ if (bound && params.turnId) bound.turnId = params.turnId;
1518
+ this.refresh(record.ownerId);
1519
+ continue;
1520
+ }
1521
+ if (params.turnId && bound?.turnId && params.turnId !== bound.turnId) continue;
1522
+ if (params.event === "SessionEnd" && bound) this.tasks.attachClient(record.ownerId, bound.client, CANVAS_ONLY);
1523
+ else this.refresh(record.ownerId);
1524
+ if (["Interrupt", "SessionEnd"].includes(params.event)) this.cancelFeedback(record.task.taskId);
1525
+ if ([
1526
+ "Interrupt",
1527
+ "Stop",
1528
+ "SessionEnd"
1529
+ ].includes(params.event)) this.tasks.stop(record.task.taskId, "paused");
1530
+ }
1531
+ }
1532
+ async owner(connectionId, metadata, clientInfo) {
1533
+ const fallback = clientInfo?.name === "claude-code" ? clientDescriptor("claude") : clientDescriptor("other");
1534
+ const binding = bindRequestMetadata(this.connections.get(connectionId) ?? { client: fallback }, metadata);
1535
+ const reportedName = clientInfo?.title?.trim() || clientInfo?.name.trim();
1536
+ if (reportedName) binding.client = {
1537
+ ...binding.client,
1538
+ name: reportedName.slice(0, 80)
1539
+ };
1540
+ const ownerId = binding.client.sessionId ? `${connectionId}/${binding.client.kind}/${binding.client.sessionId}` : connectionId;
1541
+ binding.turnId ??= this.bindings.get(ownerId)?.turnId;
1542
+ this.bindings.set(ownerId, binding);
1543
+ this.tasks.attachClient(ownerId, binding.client);
1544
+ const conversationId = nativeConversation(binding.client);
1545
+ if (conversationId) this.lifecycle?.watch(conversationId);
1546
+ return ownerId;
1547
+ }
1548
+ refresh(ownerId) {
1549
+ const binding = this.bindings.get(ownerId);
1550
+ if (binding) {
1551
+ this.tasks.attachClient(ownerId, binding.client, this.unavailable(binding));
1552
+ if (this.codex) this.describe(ownerId).then(({ capabilities }) => {
1553
+ if (this.bindings.get(ownerId) === binding) this.tasks.attachClient(ownerId, binding.client, capabilities);
1554
+ });
1555
+ }
1556
+ }
1557
+ binding(ownerId) {
1558
+ const binding = this.bindings.get(ownerId);
1559
+ if (binding) return binding;
1560
+ const client = this.tasks.list().find((record) => record.ownerId === ownerId)?.task.client;
1561
+ return client && nativeFeedback(client) ? { client } : void 0;
1562
+ }
1563
+ interruptionTarget(binding) {
1564
+ const conversationId = nativeConversation(binding?.client);
1565
+ if (!this.lifecycle || !conversationId) return void 0;
1566
+ const turnId = binding?.turnId ?? soleActiveTurn(this.lifecycle.state(conversationId));
1567
+ return turnId ? {
1568
+ conversationId,
1569
+ turnId
1570
+ } : void 0;
1571
+ }
1572
+ async describe(ownerId) {
1573
+ const binding = this.binding(ownerId);
1574
+ const conversationId = nativeConversation(binding?.client);
1575
+ if (conversationId) this.lifecycle?.watch(conversationId);
1576
+ return {
1577
+ client: binding?.client ?? clientDescriptor("other"),
1578
+ capabilities: binding && await this.codex?.available(binding) ? {
1579
+ ...CODEX_APP_FEEDBACK,
1580
+ interrupt: !!this.interruptionTarget(binding)
1581
+ } : binding ? this.unavailable(binding) : CANVAS_ONLY
1582
+ };
1583
+ }
1584
+ unavailable(binding) {
1585
+ return nativeFeedback(binding.client) ? CODEX_FEEDBACK_UNAVAILABLE : CANVAS_ONLY;
1586
+ }
1587
+ async action(action, onAccepted) {
1588
+ const record = this.tasks.find(action.taskId);
1589
+ const client = record?.task.client;
1590
+ const key = action.feedback && record && client?.sessionId ? JSON.stringify([
1591
+ "feedback",
1592
+ client.kind,
1593
+ client.sessionId,
1594
+ record.task.target.fileKey,
1595
+ action.requestId
1596
+ ]) : JSON.stringify([
1597
+ "task",
1598
+ action.taskId,
1599
+ action.requestId
1600
+ ]);
1601
+ const signature = JSON.stringify(action.feedback ?? action);
1602
+ const existing = this.actions.get(key);
1603
+ if (existing) {
1604
+ if (existing.signature !== signature) return {
1605
+ requestId: action.requestId,
1606
+ taskId: action.taskId,
1607
+ status: "failed",
1608
+ message: "This delivery identity already belongs to a different feedback batch."
1609
+ };
1610
+ return {
1611
+ ...await existing.pending,
1612
+ taskId: action.taskId
1613
+ };
1614
+ }
1615
+ if (this.actions.size >= 1024) throw new Error("Client action history is full. Check pending deliveries before restarting the Hub.");
1616
+ let dispatched = false;
1617
+ const pending = this.perform(action, onAccepted, () => {
1618
+ dispatched = true;
1619
+ }).then((result) => {
1620
+ if (result.status === "failed" && (!dispatched || action.action === "feedback" && action.feedback?.mode === "queue" && this.codex)) this.actions.delete(key);
1621
+ return result;
1622
+ });
1623
+ this.actions.set(key, {
1624
+ signature,
1625
+ pending
1626
+ });
1627
+ return pending;
1628
+ }
1629
+ async perform(action, onAccepted, onDispatch) {
1630
+ const result = (status, message) => ({
1631
+ requestId: action.requestId,
1632
+ taskId: action.taskId,
1633
+ status,
1634
+ message
1635
+ });
1636
+ try {
1637
+ const record = this.tasks.find(action.taskId);
1638
+ if (!record) throw new Error("This design task is no longer available.");
1639
+ if (action.action === "done") {
1640
+ const cancelled = this.cancelFeedback(action.taskId, true).then(() => true, () => false);
1641
+ this.tasks.closeReview(action.taskId);
1642
+ return result("delivered", await cancelled ? "Design review closed." : "Design review closed. Removing native queued comments will be retried when Codex reconnects.");
1643
+ }
1644
+ this.tasks.assertEpoch(action.taskId, record.ownerId, action.epoch);
1645
+ if (record.task.reviewClosed) throw new Error("This design review is closed.");
1646
+ const binding = this.binding(record.ownerId);
1647
+ if (action.action === "stop") {
1648
+ if (this.tasks.current(record.task.target.fileKey) !== record) throw new Error("This task has been replaced. Stop the current task instead.");
1649
+ if (["completed", "cancelled"].includes(record.task.status)) return result("delivered", "This design task has already ended.");
1650
+ const target = this.interruptionTarget(binding);
1651
+ const diagnostic = {
1652
+ taskId: action.taskId,
1653
+ requestId: action.requestId,
1654
+ conversationId: binding?.client.sessionId,
1655
+ boundTurnId: binding?.turnId,
1656
+ expectedTurnId: target?.turnId
1657
+ };
1658
+ if (binding?.client.kind === "claude") this.hooks.stop(binding, action.taskId);
1659
+ this.cancelFeedback(action.taskId, true).catch(() => {});
1660
+ this.tasks.stop(action.taskId, "cancelled");
1661
+ onAccepted?.();
1662
+ if (this.lifecycle && target) {
1663
+ log.info(diagnostic, "Requesting native Codex Stop interruption.");
1664
+ try {
1665
+ const interrupted = await this.lifecycle.interrupt(target.conversationId, target.turnId);
1666
+ log.info({
1667
+ ...diagnostic,
1668
+ interrupted
1669
+ }, "Native Codex Stop interruption settled.");
1670
+ return result("delivered", interrupted ? "Design task stopped and Codex turn interrupted." : "Design task stopped; Codex did not interrupt the expected turn because it is no longer active.");
1671
+ } catch (error) {
1672
+ log.warn({
1673
+ ...diagnostic,
1674
+ err: error
1675
+ }, "Native Codex Stop interruption failed.");
1676
+ return result("delivered", "Design task stopped. Codex interruption could not be confirmed; further writes from this task remain blocked.");
1677
+ }
1678
+ }
1679
+ if (binding && nativeFeedback(binding.client)) {
1680
+ log.warn(diagnostic, "Native Codex Stop skipped: no verified interruption target.");
1681
+ return result("delivered", "Design task stopped. Codex interruption was not sent because its current turn could not be identified; further writes from this task remain blocked.");
1682
+ }
1683
+ return result("delivered", "Design task stopped.");
1684
+ }
1685
+ if (action.action === "steer") throw new Error("Switching an already queued batch to Steer is not available. Queued comments will wait for the current response to finish.");
1686
+ if (!binding || !action.feedback) throw new Error(CANVAS_ONLY.reason);
1687
+ const feedback = action.feedback;
1688
+ if (feedback.fileKey !== record.task.target.fileKey) throw new Error("The feedback belongs to a different Figma file.");
1689
+ if (!nativeFeedback(binding.client) || !this.codex || !binding.client.sessionId) {
1690
+ const capabilities = this.unavailable(binding);
1691
+ this.tasks.attachClient(record.ownerId, binding.client, capabilities);
1692
+ throw new Error(capabilities.reason);
1693
+ }
1694
+ let controller = this.feedbackSignals.get(action.taskId);
1695
+ if (!controller) {
1696
+ controller = new AbortController();
1697
+ this.feedbackSignals.set(action.taskId, controller);
1698
+ }
1699
+ const signal = controller.signal;
1700
+ onAccepted?.();
1701
+ if (signal.aborted) throw new Error("Feedback cancelled by stop or disconnect.");
1702
+ this.tasks.assertEpoch(action.taskId, record.ownerId, action.epoch);
1703
+ const beforeSend = () => {
1704
+ this.tasks.assertEpoch(action.taskId, record.ownerId, action.epoch);
1705
+ if (record.task.reviewClosed || record.task.status === "cancelled" || this.tasks.current(feedback.fileKey) !== record) throw new Error("This design task was stopped or replaced. Its queued comments will not be sent.");
1706
+ };
1707
+ await this.codex.enqueue(binding, action.taskId, feedback, signal, beforeSend, onDispatch);
1708
+ this.tasks.attachClient(record.ownerId, binding.client, CODEX_APP_FEEDBACK);
1709
+ return result("delivered", "Feedback sent to the bound agent conversation.");
1710
+ } catch (error) {
1711
+ return result("failed", error instanceof Error ? error.message.slice(0, 500) : "The client action failed.");
1712
+ }
1713
+ }
1714
+ async refreshCapabilities() {
1715
+ if (!this.codex) return;
1716
+ await this.codex.reconcileQueued((taskId) => {
1717
+ const record = this.tasks.find(taskId);
1718
+ return !!record && (record.task.reviewClosed === true || record.task.status === "cancelled" || this.tasks.current(record.task.target.fileKey) !== record);
1719
+ });
1720
+ const reviews = this.tasks.list().filter((record) => !record.task.reviewClosed && record.task.status !== "cancelled" && this.tasks.current(record.task.target.fileKey) === record);
1721
+ this.lifecycle?.retain(new Set(reviews.flatMap((record) => {
1722
+ const conversationId = nativeConversation(record.task.client);
1723
+ return conversationId ? [conversationId] : [];
1724
+ })));
1725
+ const owners = new Set(reviews.map((record) => record.ownerId));
1726
+ for (const ownerId of owners) {
1727
+ const binding = this.bindings.get(ownerId);
1728
+ const { client, capabilities } = await this.describe(ownerId);
1729
+ if (this.bindings.get(ownerId) === binding) this.tasks.attachClient(ownerId, client, capabilities);
1730
+ }
1731
+ }
1732
+ close() {
1733
+ this.lifecycle?.close();
1734
+ this.codex?.close();
1735
+ for (const taskId of this.feedbackSignals.keys()) this.cancelFeedback(taskId);
1736
+ }
1737
+ cancelFeedback(taskId, removeQueued = false) {
1738
+ this.feedbackSignals.get(taskId)?.abort();
1739
+ this.feedbackSignals.delete(taskId);
1740
+ return removeQueued && this.codex ? this.codex.cancelQueued(taskId) : Promise.resolve();
1741
+ }
1742
+ disconnect(connectionId) {
1743
+ this.connections.delete(connectionId);
1744
+ for (const ownerId of this.bindings.keys()) {
1745
+ if (ownerId !== connectionId && !ownerId.startsWith(`${connectionId}/`)) continue;
1746
+ this.hooks.disconnect(this.bindings.get(ownerId));
1747
+ for (const record of this.tasks.list()) if (record.ownerId === ownerId) this.cancelFeedback(record.task.taskId);
1748
+ this.tasks.disconnectOwner(ownerId);
1749
+ this.bindings.delete(ownerId);
1750
+ }
1751
+ }
1752
+ };
1753
+ //#endregion
1754
+ //#region src/asset-data-url.ts
1755
+ const IMAGE_DATA_URL_PATTERN = /^data:(image\/(?:png|jpeg|gif));base64,([A-Za-z0-9+/]+={0,2})$/;
1756
+ function decodeImageDataUrl(dataUrl, maxBytes = MCP_MAX_ASSET_BYTES) {
1757
+ const match = IMAGE_DATA_URL_PATTERN.exec(dataUrl);
1758
+ if (!match) throw new Error("Expected a base64 PNG, JPEG, or GIF data URL.");
1759
+ const mimeType = match[1];
1760
+ const encoded = match[2];
1761
+ if (encoded.length % 4 !== 0) throw new Error("Image data URL contains invalid base64 padding.");
1762
+ const bytes = Buffer.from(encoded, "base64");
1763
+ if (!bytes.length) throw new Error("Generated image is empty.");
1764
+ if (bytes.length > maxBytes) throw new Error(`Generated image exceeds the ${maxBytes}-byte asset limit.`);
1765
+ if (bytes.toString("base64") !== encoded) throw new Error("Image data URL contains invalid base64 data.");
1766
+ return {
1767
+ bytes,
1768
+ hash: createHash("sha256").update(bytes).digest("hex"),
1769
+ mimeType
1770
+ };
1771
+ }
723
1772
  //#endregion
724
1773
  //#region src/asset-utils.ts
725
- const HASH_FILENAME_PATTERN = new RegExp(`^([a-f0-9]{8})(?:\\.[a-z0-9]+)?$`, "i");
726
- const MIME_EXTENSION_OVERRIDES = /* @__PURE__ */ new Map([["image/jpeg", "jpg"]]);
1774
+ const HASH_FILENAME_PATTERN = new RegExp(`^([a-f0-9]{64}|[a-f0-9]{8})(?:\\.[a-z0-9]+)?$`);
727
1775
  const SAFE_IMAGE_EXTENSION_PATTERN = /^[a-z0-9-]+$/;
728
1776
  function normalizeMimeType(mimeType) {
729
1777
  if (!mimeType) return "application/octet-stream";
@@ -733,8 +1781,7 @@ function normalizeMimeType(mimeType) {
733
1781
  function getImageExtension(mimeType) {
734
1782
  const normalized = normalizeMimeType(mimeType);
735
1783
  if (!normalized.startsWith("image/")) return "";
736
- const override = MIME_EXTENSION_OVERRIDES.get(normalized);
737
- if (override) return `.${override}`;
1784
+ if (normalized === "image/jpeg") return ".jpg";
738
1785
  const subtype = normalized.slice(6);
739
1786
  if (!subtype) return "";
740
1787
  const ext = subtype.split("+", 1)[0] || subtype;
@@ -751,6 +1798,7 @@ function getHashFromAssetFilename(filename) {
751
1798
  }
752
1799
  //#endregion
753
1800
  //#region src/config.ts
1801
+ const PAGE_STRUCTURE_TIMEOUT_MS = 45e3;
754
1802
  function parsePositiveInt(envValue, fallback) {
755
1803
  const parsed = envValue ? Number.parseInt(envValue, 10) : NaN;
756
1804
  return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
@@ -759,8 +1807,8 @@ function parseNonNegativeInt(envValue, fallback) {
759
1807
  const parsed = envValue ? Number.parseInt(envValue, 10) : NaN;
760
1808
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
761
1809
  }
762
- function resolveToolTimeoutMs() {
763
- return parsePositiveInt(process.env.TEMPAD_MCP_TOOL_TIMEOUT, MCP_TOOL_TIMEOUT_MS);
1810
+ function resolveToolTimeoutMs(specializedValue, fallback = MCP_TOOL_TIMEOUT_MS) {
1811
+ return parsePositiveInt(specializedValue, parsePositiveInt(process.env.TEMPAD_MCP_TOOL_TIMEOUT, fallback));
764
1812
  }
765
1813
  function resolveAutoActivateGraceMs() {
766
1814
  return parsePositiveInt(process.env.TEMPAD_MCP_AUTO_ACTIVATE_GRACE, MCP_AUTO_ACTIVATE_GRACE_MS);
@@ -784,6 +1832,10 @@ function getMcpServerConfig() {
784
1832
  return {
785
1833
  wsPortCandidates: [...MCP_PORT_CANDIDATES],
786
1834
  toolTimeoutMs: resolveToolTimeoutMs(),
1835
+ getCodeTimeoutMs: resolveToolTimeoutMs(process.env.TEMPAD_MCP_GET_CODE_TIMEOUT, MCP_GET_CODE_TIMEOUT_MS),
1836
+ getDesignSystemTimeoutMs: resolveToolTimeoutMs(process.env.TEMPAD_MCP_GET_DESIGN_SYSTEM_TIMEOUT, MCP_GET_DESIGN_SYSTEM_TIMEOUT_MS),
1837
+ pageStructureTimeoutMs: resolveToolTimeoutMs(process.env.TEMPAD_MCP_PAGE_STRUCTURE_TIMEOUT, PAGE_STRUCTURE_TIMEOUT_MS),
1838
+ applyCanvasTimeoutMs: resolveToolTimeoutMs(process.env.TEMPAD_MCP_APPLY_CANVAS_TIMEOUT, MCP_APPLY_CANVAS_TIMEOUT_MS),
787
1839
  maxPayloadBytes: MCP_MAX_PAYLOAD_BYTES,
788
1840
  autoActivateGraceMs: resolveAutoActivateGraceMs(),
789
1841
  maxAssetSizeBytes: resolveMaxAssetSizeBytes(),
@@ -838,7 +1890,6 @@ function isChromeExtensionOrigin(origin) {
838
1890
  //#endregion
839
1891
  //#region src/asset-http-server.ts
840
1892
  const LOOPBACK_HOST = "127.0.0.1";
841
- const HASH_HEX_PATTERN = new RegExp(`^[a-f0-9]{8}$`, "i");
842
1893
  const ASSET_REQUEST_TIMEOUT_MS = 15e3;
843
1894
  const ASSET_HEADERS_TIMEOUT_MS = 5e3;
844
1895
  const ASSET_KEEP_ALIVE_TIMEOUT_MS = 5e3;
@@ -848,6 +1899,7 @@ const ASSET_MAX_CONCURRENT_DOWNLOADS = 128;
848
1899
  function createAssetHttpServer(store, options = {}) {
849
1900
  const config = getMcpServerConfig();
850
1901
  const accessToken = options.accessToken ?? createCapabilityToken();
1902
+ const legacyAccessToken = createCapabilityToken();
851
1903
  const maxAssetSizeBytes = options.maxAssetSizeBytes ?? config.maxAssetSizeBytes;
852
1904
  const maxAssetStoreBytes = options.maxAssetStoreBytes ?? config.maxAssetStoreBytes;
853
1905
  const maxConcurrentUploads = options.maxConcurrentUploads ?? config.maxConcurrentAssetUploads;
@@ -888,9 +1940,9 @@ function createAssetHttpServer(store, options = {}) {
888
1940
  server.close();
889
1941
  port = null;
890
1942
  }
891
- function getBaseUrl() {
1943
+ function getBaseUrl(legacy = false) {
892
1944
  if (port === null) throw new Error("Asset HTTP server is not running.");
893
- return `http://${LOOPBACK_HOST}:${port}/${accessToken}`;
1945
+ return `http://${LOOPBACK_HOST}:${port}/${legacy ? legacyAccessToken : accessToken}`;
894
1946
  }
895
1947
  function handleRequest(req, res) {
896
1948
  const startedAt = Date.now();
@@ -907,7 +1959,8 @@ function createAssetHttpServer(store, options = {}) {
907
1959
  return;
908
1960
  }
909
1961
  const segments = new URL$1(req.url, getBaseUrl()).pathname.split("/").filter(Boolean);
910
- if (segments.length !== 3 || !secretsEqual(segments[0] ?? "", accessToken) || segments[1] !== "assets") {
1962
+ const legacy = secretsEqual(segments[0] ?? "", legacyAccessToken);
1963
+ if (segments.length !== 3 || !legacy && !secretsEqual(segments[0] ?? "", accessToken) || segments[1] !== "assets") {
911
1964
  sendError(res, 404, "Not Found");
912
1965
  return;
913
1966
  }
@@ -934,6 +1987,10 @@ function createAssetHttpServer(store, options = {}) {
934
1987
  return;
935
1988
  }
936
1989
  if (req.method === "POST") {
1990
+ if (!legacy && hash.length !== 64) {
1991
+ sendError(res, 400, "Legacy Asset Hashes Are Read-Only");
1992
+ return;
1993
+ }
937
1994
  handleUpload(req, res, hash);
938
1995
  return;
939
1996
  }
@@ -1004,11 +2061,6 @@ function createAssetHttpServer(store, options = {}) {
1004
2061
  stream.pipe(res);
1005
2062
  }
1006
2063
  function handleUpload(req, res, hash) {
1007
- if (!HASH_HEX_PATTERN.test(hash)) {
1008
- req.resume();
1009
- sendError(res, 400, "Invalid Hash");
1010
- return;
1011
- }
1012
2064
  const declaredSize = parseContentLength(req);
1013
2065
  if (declaredSize === "invalid") {
1014
2066
  req.resume();
@@ -1021,7 +2073,8 @@ function createAssetHttpServer(store, options = {}) {
1021
2073
  return;
1022
2074
  }
1023
2075
  const mimeType = normalizeMimeType(getHeader(req, "content-type"));
1024
- const filePath = join(ASSET_DIR, buildAssetFilename(hash, mimeType));
2076
+ const filename = buildAssetFilename(hash, mimeType);
2077
+ const filePath = join(ASSET_DIR, filename);
1025
2078
  const width = parseInt(getHeader(req, "x-asset-width") ?? "", 10);
1026
2079
  const height = parseInt(getHeader(req, "x-asset-height") ?? "", 10);
1027
2080
  const themeable = getHeader(req, "x-asset-themeable") === "true";
@@ -1031,7 +2084,7 @@ function createAssetHttpServer(store, options = {}) {
1031
2084
  if (themeable) metadata.themeable = true;
1032
2085
  const assetMetadata = Object.keys(metadata).length ? metadata : void 0;
1033
2086
  const existing = store.get(hash);
1034
- if (existing) {
2087
+ if (existing && hash.length === 64) {
1035
2088
  let existingPath = existing.filePath;
1036
2089
  if (!existsSync(existingPath) && existsSync(filePath)) {
1037
2090
  existing.filePath = filePath;
@@ -1087,7 +2140,7 @@ function createAssetHttpServer(store, options = {}) {
1087
2140
  }, "Failed to cleanup temp file.");
1088
2141
  }
1089
2142
  };
1090
- pipeline(req, new Transform({ transform(chunk, encoding, callback) {
2143
+ const monitor = new Transform({ transform(chunk, encoding, callback) {
1091
2144
  size += chunk.length;
1092
2145
  if (size > maxAssetSizeBytes) {
1093
2146
  callback(/* @__PURE__ */ new Error("PayloadTooLarge"));
@@ -1095,7 +2148,8 @@ function createAssetHttpServer(store, options = {}) {
1095
2148
  }
1096
2149
  hasher.update(chunk);
1097
2150
  callback(null, chunk);
1098
- } }), writeStream, (err) => {
2151
+ } });
2152
+ pipeline(req, monitor, writeStream, (err) => {
1099
2153
  activeUploads -= 1;
1100
2154
  reservedUploadBytes -= reservationBytes;
1101
2155
  if (err) {
@@ -1113,7 +2167,8 @@ function createAssetHttpServer(store, options = {}) {
1113
2167
  }
1114
2168
  return;
1115
2169
  }
1116
- if (hasher.digest("hex").slice(0, 8) !== hash) {
2170
+ const computedHash = hasher.digest("hex");
2171
+ if (computedHash.slice(0, hash.length) !== hash) {
1117
2172
  cleanup();
1118
2173
  sendError(res, 400, "Hash Mismatch");
1119
2174
  return;
@@ -1124,6 +2179,27 @@ function createAssetHttpServer(store, options = {}) {
1124
2179
  return;
1125
2180
  }
1126
2181
  try {
2182
+ if (hash.length !== 64) {
2183
+ const previous = store.get(hash);
2184
+ if (previous && existsSync(previous.filePath)) {
2185
+ const previousHash = createHash("sha256").update(readFileSync(previous.filePath)).digest("hex");
2186
+ cleanup();
2187
+ if (previousHash !== computedHash) {
2188
+ sendError(res, 409, "Legacy Asset Hash Collision; update the TemPad Dev extension");
2189
+ return;
2190
+ }
2191
+ store.upsert({
2192
+ ...previous,
2193
+ metadata: {
2194
+ ...previous.metadata,
2195
+ ...assetMetadata
2196
+ },
2197
+ lastAccess: Date.now()
2198
+ });
2199
+ sendJson(res, 200, { message: "Asset Already Exists" });
2200
+ return;
2201
+ }
2202
+ }
1127
2203
  renameSync(tmpPath, filePath);
1128
2204
  } catch (error) {
1129
2205
  log.error({
@@ -1156,7 +2232,7 @@ function createAssetHttpServer(store, options = {}) {
1156
2232
  if (!requestUrl) return requestUrl;
1157
2233
  try {
1158
2234
  const segments = new URL$1(requestUrl, `http://${LOOPBACK_HOST}`).pathname.split("/").filter(Boolean);
1159
- if (segments.length >= 1 && secretsEqual(segments[0] ?? "", accessToken)) segments[0] = "<capability>";
2235
+ if (segments.length >= 1 && (secretsEqual(segments[0] ?? "", accessToken) || secretsEqual(segments[0] ?? "", legacyAccessToken))) segments[0] = "<capability>";
1160
2236
  return `/${segments.join("/")}`;
1161
2237
  } catch {
1162
2238
  return "<invalid>";
@@ -1215,7 +2291,8 @@ function readIndex(indexPath) {
1215
2291
  }
1216
2292
  }
1217
2293
  function writeIndex(indexPath, values) {
1218
- writeFileSync(indexPath, JSON.stringify(values, null, 2), "utf8");
2294
+ const payload = JSON.stringify(values, null, 2);
2295
+ writeFileSync(indexPath, payload, "utf8");
1219
2296
  }
1220
2297
  function createAssetStore(options = {}) {
1221
2298
  ensureDir(ASSET_DIR);
@@ -1286,75 +2363,570 @@ function createAssetStore(options = {}) {
1286
2363
  }, "Failed to remove asset file on delete.");
1287
2364
  }
1288
2365
  }
1289
- function reconcile() {
1290
- let changed = false;
1291
- for (const [hash, record] of records) if (!existsSync(record.filePath)) {
1292
- records.delete(hash);
1293
- changed = true;
2366
+ function reconcile() {
2367
+ let changed = false;
2368
+ for (const [hash, record] of records) if (!existsSync(record.filePath)) {
2369
+ records.delete(hash);
2370
+ changed = true;
2371
+ }
2372
+ try {
2373
+ const files = readdirSync(ASSET_DIR);
2374
+ const now = Date.now();
2375
+ for (const file of files) {
2376
+ if (file === INDEX_FILENAME) continue;
2377
+ if (file.includes(".tmp.")) {
2378
+ try {
2379
+ const filePath = join(ASSET_DIR, file);
2380
+ if (now - statSync(filePath).mtimeMs > 36e5) {
2381
+ rmSync(filePath, { force: true });
2382
+ log.info({ file }, "Cleaned up stale temp file.");
2383
+ }
2384
+ } catch (e) {
2385
+ log.debug({
2386
+ error: e,
2387
+ file
2388
+ }, "Failed to cleanup stale temp file.");
2389
+ }
2390
+ continue;
2391
+ }
2392
+ const hash = getHashFromAssetFilename(file);
2393
+ if (!hash) continue;
2394
+ if (!records.has(hash)) {
2395
+ const filePath = join(ASSET_DIR, file);
2396
+ try {
2397
+ const stat = statSync(filePath);
2398
+ records.set(hash, {
2399
+ hash,
2400
+ filePath,
2401
+ mimeType: "application/octet-stream",
2402
+ size: stat.size,
2403
+ uploadedAt: stat.birthtimeMs,
2404
+ lastAccess: stat.atimeMs
2405
+ });
2406
+ changed = true;
2407
+ log.info({ hash }, "Recovered orphan asset file.");
2408
+ } catch (e) {
2409
+ log.warn({
2410
+ error: e,
2411
+ file
2412
+ }, "Failed to stat orphan file.");
2413
+ }
2414
+ }
2415
+ }
2416
+ } catch (error) {
2417
+ log.warn({ error }, "Failed to scan asset directory for orphans.");
2418
+ }
2419
+ if (changed) flush();
2420
+ }
2421
+ loadExisting();
2422
+ reconcile();
2423
+ return {
2424
+ list,
2425
+ has,
2426
+ get,
2427
+ getMany,
2428
+ upsert,
2429
+ touch,
2430
+ remove,
2431
+ reconcile,
2432
+ flush
2433
+ };
2434
+ }
2435
+ //#endregion
2436
+ //#region src/design-task-store.ts
2437
+ const SnapshotSchema = z.object({
2438
+ revision: z.number().int().nonnegative(),
2439
+ current: z.record(z.string(), z.string()),
2440
+ records: z.array(z.object({
2441
+ task: DesignTaskSchema,
2442
+ requestId: z.string(),
2443
+ browser: z.object({
2444
+ browserId: z.string(),
2445
+ origin: z.string(),
2446
+ tabId: z.number(),
2447
+ documentId: z.string()
2448
+ }).optional(),
2449
+ resultNodeIds: z.array(z.string()).optional()
2450
+ }))
2451
+ });
2452
+ /** One lock-owning Hub writes a small atomic snapshot; transport and leases are never restored. */
2453
+ var DesignTaskStore = class {
2454
+ path;
2455
+ constructor(path) {
2456
+ this.path = path;
2457
+ }
2458
+ load() {
2459
+ try {
2460
+ return SnapshotSchema.parse(JSON.parse(readFileSync(this.path, "utf8")));
2461
+ } catch (error) {
2462
+ if (error.code === "ENOENT") return void 0;
2463
+ throw error;
2464
+ }
2465
+ }
2466
+ save(snapshot) {
2467
+ mkdirSync(dirname(this.path), {
2468
+ recursive: true,
2469
+ mode: 448
2470
+ });
2471
+ const temporary = `${this.path}.tmp`;
2472
+ writeFileSync(temporary, JSON.stringify(snapshot), {
2473
+ mode: 384,
2474
+ flush: true
2475
+ });
2476
+ renameSync(temporary, this.path);
2477
+ }
2478
+ };
2479
+ //#endregion
2480
+ //#region src/legacy-extension.ts
2481
+ function extensionUpgradeRequired() {
2482
+ return Object.assign(/* @__PURE__ */ new Error("This operation requires TemPad Dev extension 0.21.0 or later. 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 });
2483
+ }
2484
+ function legacyToolPayload(name, args) {
2485
+ const result = LegacyToolCallPayloadSchema.safeParse({
2486
+ name,
2487
+ args
2488
+ });
2489
+ if (!result.success) throw extensionUpgradeRequired();
2490
+ return result.data;
2491
+ }
2492
+ //#endregion
2493
+ //#region src/design-tasks.ts
2494
+ const ENDED_STATUSES = ["completed", "cancelled"];
2495
+ const RUNNING_STATUSES = ["active", "stopping"];
2496
+ function fail(code, message) {
2497
+ throw Object.assign(new Error(message), { code });
2498
+ }
2499
+ function resolveDesignTarget(tasks, extensions, activeExtensionId, ownerId, taskId, active = true, explicitSessionId) {
2500
+ const record = taskId ? tasks.owned(taskId, ownerId, active) : void 0;
2501
+ if (record && explicitSessionId && explicitSessionId !== record.task.target.sessionId) fail("DESIGN_TARGET_CHANGED", "The requested Figma session does not match this task.");
2502
+ 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);
2503
+ if (extension?.legacy) throw extensionUpgradeRequired();
2504
+ const sessionId = explicitSessionId ?? record?.task.target.sessionId ?? extension?.sessions?.activeSessionId;
2505
+ const session = extension?.sessions?.sessions.find((value) => value.sessionId === sessionId);
2506
+ 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.");
2507
+ if (record && record.task.target.fileKey !== session.fileKey) fail("DESIGN_TARGET_CHANGED", "The task file changed.");
2508
+ const busy = extensions.some((connection) => connection.sessions?.sessions.some((value) => value.fileKey === session.fileKey && value.busy));
2509
+ return {
2510
+ extension,
2511
+ session: {
2512
+ ...session,
2513
+ busy
2514
+ }
2515
+ };
2516
+ }
2517
+ /** One Hub coordinates file leases across its connected browser sessions. */
2518
+ var DesignTasks = class {
2519
+ options;
2520
+ records = /* @__PURE__ */ new Map();
2521
+ currentTaskIds = /* @__PURE__ */ new Map();
2522
+ operations = /* @__PURE__ */ new Map();
2523
+ now;
2524
+ leaseMs;
2525
+ revision = 0;
2526
+ constructor(options) {
2527
+ this.options = options;
2528
+ this.now = options.now ?? Date.now;
2529
+ this.leaseMs = options.leaseMs ?? 3e5;
2530
+ }
2531
+ retry(ownerId, requestId) {
2532
+ this.sweep();
2533
+ return [...this.records.values()].find((record) => record.ownerId === ownerId && record.requestId === requestId);
2534
+ }
2535
+ begin(ownerId, extensionId, session, title, requestId, client, capabilities, browser) {
2536
+ const retry = this.retry(ownerId, requestId);
2537
+ if (retry) {
2538
+ if (retry.task.title !== title) fail("DESIGN_TASK_INACTIVE", "This begin requestId was already used with another title.");
2539
+ return retry;
2540
+ }
2541
+ this.assertFileIdle(session);
2542
+ const occupant = this.occupant(session.fileKey);
2543
+ if (occupant) this.busy(occupant);
2544
+ const { busy: _busy, tabId, documentId, ...target } = session;
2545
+ const record = {
2546
+ ownerId,
2547
+ extensionId,
2548
+ requestId,
2549
+ ready: false,
2550
+ ...browser && tabId !== void 0 && documentId !== void 0 ? { browser: {
2551
+ ...browser,
2552
+ tabId,
2553
+ documentId
2554
+ } } : {},
2555
+ task: {
2556
+ taskId: this.options.createId(),
2557
+ title,
2558
+ target,
2559
+ status: "active",
2560
+ epoch: 0,
2561
+ ...client ? { client } : {},
2562
+ ...capabilities ? { capabilities } : {},
2563
+ operation: null,
2564
+ expiresAt: this.now() + this.leaseMs,
2565
+ revision: 0
2566
+ }
2567
+ };
2568
+ const previousTaskId = this.currentTaskIds.get(session.fileKey);
2569
+ this.records.set(record.task.taskId, record);
2570
+ this.currentTaskIds.set(session.fileKey, record.task.taskId);
2571
+ try {
2572
+ this.publish(record);
2573
+ } catch (error) {
2574
+ this.records.delete(record.task.taskId);
2575
+ if (previousTaskId) this.currentTaskIds.set(session.fileKey, previousTaskId);
2576
+ else this.currentTaskIds.delete(session.fileKey);
2577
+ throw error;
2578
+ }
2579
+ return record;
2580
+ }
2581
+ confirm(taskId, ownerId) {
2582
+ const record = this.owned(taskId, ownerId, true);
2583
+ record.ready = true;
2584
+ return record;
2585
+ }
2586
+ owned(taskId, ownerId, active = false) {
2587
+ const record = this.find(taskId);
2588
+ if (!record) fail("DESIGN_TASK_INACTIVE", "Unknown or expired task. Begin a new design task and reread its target.");
2589
+ if (record.ownerId !== ownerId) fail("DESIGN_TASK_OWNER_MISMATCH", "This task belongs to another MCP caller. Begin your own task.");
2590
+ if (active && record.task.reviewClosed) fail("DESIGN_TASK_INACTIVE", "This review is closed. Begin a new task before writing.");
2591
+ 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." : "Resume this task with resume_design and reread the target before writing; do not replay an old write."}`);
2592
+ return record;
2593
+ }
2594
+ /** Runtime identity may reconnect the same conversation, never a focused/last caller. */
2595
+ attachClient(ownerId, client, capabilities) {
2596
+ if (!client.sessionId || ["other", "unknown"].includes(client.kind)) return;
2597
+ for (const record of this.records.values()) {
2598
+ if (record.task.client?.kind !== client.kind || record.task.client.sessionId !== client.sessionId) continue;
2599
+ if (!RESUMABLE_DESIGN_TASK_STATUSES.includes(record.task.status) && record.ownerId !== ownerId) continue;
2600
+ const changed = record.ownerId !== ownerId || capabilities && !isDeepStrictEqual(record.task.capabilities, capabilities);
2601
+ record.ownerId = ownerId;
2602
+ record.task.client = client;
2603
+ if (capabilities) record.task.capabilities = capabilities;
2604
+ if (changed) this.publish(record);
2605
+ }
2606
+ }
2607
+ assertEpoch(taskId, ownerId, epoch) {
2608
+ const record = this.owned(taskId, ownerId);
2609
+ if ((epoch ?? 0) !== (record.task.epoch ?? 0)) fail("DESIGN_TASK_INACTIVE", "Stale task lease. Read get_design_task for the current epoch, resume_design if inactive, and reread the canvas before writing.");
2610
+ return record;
2611
+ }
2612
+ resume(taskId, ownerId, epoch, session) {
2613
+ const record = this.assertEpoch(taskId, ownerId, epoch);
2614
+ if (record.task.reviewClosed) fail("DESIGN_TASK_INACTIVE", "This review is closed.");
2615
+ if (record.task.status === "active") return record;
2616
+ if (!RESUMABLE_DESIGN_TASK_STATUSES.includes(record.task.status)) fail("DESIGN_TASK_INACTIVE", "This task cannot resume. Wait for any stopping operation to finish, then begin a new task with a fresh requestId.");
2617
+ if (this.current(record.task.target.fileKey) !== record) fail("DESIGN_TASK_INACTIVE", "This task was replaced by a newer task and cannot resume.");
2618
+ if (record.task.target.sessionId !== session.sessionId || record.task.target.fileKey !== session.fileKey) fail("DESIGN_TARGET_CHANGED", "The original Figma runtime is unavailable. No other session was selected.");
2619
+ this.assertFileIdle(session);
2620
+ record.ending = void 0;
2621
+ record.ready = false;
2622
+ record.task.status = "active";
2623
+ record.task.epoch = (record.task.epoch ?? 0) + 1;
2624
+ record.task.needsRead = true;
2625
+ this.renew(record);
2626
+ return record;
2627
+ }
2628
+ acknowledgeRead(taskId, ownerId, epoch) {
2629
+ const record = this.assertEpoch(taskId, ownerId, epoch);
2630
+ if (record.task.status !== "active" || !record.task.needsRead) return;
2631
+ record.task.needsRead = false;
2632
+ this.publish(record);
2633
+ }
2634
+ find(taskId) {
2635
+ this.sweep();
2636
+ return this.records.get(taskId);
2637
+ }
2638
+ list() {
2639
+ this.sweep();
2640
+ return [...this.records.values()];
2641
+ }
2642
+ /** Only the current claim may own a lease or the file's task UI. */
2643
+ current(fileKey) {
2644
+ const taskId = this.currentTaskIds.get(fileKey);
2645
+ return taskId ? this.records.get(taskId) : void 0;
2646
+ }
2647
+ occupant(fileKey) {
2648
+ const record = this.current(fileKey);
2649
+ return record && RUNNING_STATUSES.includes(record.task.status) ? record : void 0;
2650
+ }
2651
+ busy(record) {
2652
+ fail("DESIGN_TASK_BUSY", `This file is occupied by “${record.task.title}”. Stop that task in TemPad Dev to take over, or retry after its idle lease expires. No request was queued.`);
2653
+ }
2654
+ hasPendingOperation(fileKey) {
2655
+ return [...this.operations.values()].some((operation) => operation.target.fileKey === fileKey);
2656
+ }
2657
+ assertFileIdle(session) {
2658
+ if (session.busy || this.hasPendingOperation(session.fileKey)) fail("DESIGN_TASK_BUSY", "An operation in this file has not finished. Wait for its definitive result; if its runtime is stuck, reload the executing Figma tab before taking over.");
2659
+ }
2660
+ checkOperation(ownerId, session, taskId, write = false) {
2661
+ this.sweep();
2662
+ this.assertFileIdle(session);
2663
+ const record = taskId ? this.owned(taskId, ownerId, true) : void 0;
2664
+ if (record && (!record.ready || record.task.target.sessionId !== session.sessionId)) fail("DESIGN_TARGET_CHANGED", "The task is not bound to this Figma session.");
2665
+ if (write && record?.task.needsRead) fail("DESIGN_TASK_INACTIVE", "Read the bound canvas with get_structure or get_code after resuming before writing.");
2666
+ const occupant = this.occupant(session.fileKey);
2667
+ if (write && occupant && occupant !== record) this.busy(occupant);
2668
+ if (write && !taskId && [...this.records.values()].some(({ task }) => task.target.fileKey === session.fileKey && task.status === "cancelled")) fail("DESIGN_TASK_INACTIVE", "This file has a stopped task. Begin a new task before writing.");
2669
+ }
2670
+ startOperation(requestId, ownerId, extensionId, browserId, session, taskId, write = false) {
2671
+ this.checkOperation(ownerId, session, taskId, write);
2672
+ const record = taskId ? this.records.get(taskId) : void 0;
2673
+ const { busy: _busy, tabId, documentId, ...target } = session;
2674
+ this.operations.set(requestId, {
2675
+ extensionId,
2676
+ browserId,
2677
+ target,
2678
+ taskId,
2679
+ uncertain: false,
2680
+ tabId,
2681
+ documentId
2682
+ });
2683
+ if (!record) return;
2684
+ record.task.operation = write ? "writing" : "reading";
2685
+ this.renew(record);
2686
+ }
2687
+ finishOperation(requestId, extensionId) {
2688
+ const operation = this.operations.get(requestId);
2689
+ if (!operation || operation.extensionId !== extensionId) return;
2690
+ this.operations.delete(requestId);
2691
+ if (!operation.taskId) return;
2692
+ const record = this.records.get(operation.taskId);
2693
+ if (!record) return;
2694
+ record.task.operation = null;
2695
+ if (record.ending) this.finish(record, record.ending);
2696
+ else if (record.task.status === "active") this.renew(record);
2697
+ }
2698
+ /** A transport failure is not evidence that page execution stopped. */
2699
+ uncertain(requestId, extensionId) {
2700
+ const operation = this.operations.get(requestId);
2701
+ if (operation?.extensionId === extensionId) operation.uncertain = true;
2702
+ }
2703
+ reconcileSessions(browserId, sessions, openTabIds) {
2704
+ for (const [requestId, operation] of this.operations) {
2705
+ if (!operation.uncertain) continue;
2706
+ const session = sessions.find((value) => value.sessionId === operation.target.sessionId);
2707
+ const sameBrowser = browserId === operation.browserId;
2708
+ const tabClosed = sameBrowser && operation.tabId !== void 0 && openTabIds !== void 0 && !openTabIds.includes(operation.tabId);
2709
+ const documentReplaced = sameBrowser && operation.tabId !== void 0 && operation.documentId !== void 0 && sessions.some((value) => value.tabId === operation.tabId && value.documentId !== void 0 && value.documentId !== operation.documentId);
2710
+ if (session && !session.busy || tabClosed || documentReplaced) this.finishOperation(requestId, operation.extensionId);
2711
+ }
2712
+ }
2713
+ /** A new document in the same browser tab can restore the task, never an old write. */
2714
+ recoverSessions(extensions) {
2715
+ const recovered = [];
2716
+ for (const record of this.list()) {
2717
+ const { task, browser } = record;
2718
+ if (!browser || task.reviewClosed || this.current(task.target.fileKey) !== record || !RESUMABLE_DESIGN_TASK_STATUSES.includes(task.status) || extensions.some((extension) => extension.sessions?.sessions.some((session) => session.sessionId === task.target.sessionId))) continue;
2719
+ const candidates = extensions.flatMap((extension) => {
2720
+ if (extension.origin !== browser.origin || extension.sessions?.browserId !== browser.browserId) return [];
2721
+ return extension.sessions.sessions.filter((session) => session.tabId === browser.tabId && session.documentId !== void 0 && session.documentId !== browser.documentId && session.fileKey === task.target.fileKey).map((session) => ({
2722
+ extension,
2723
+ session
2724
+ }));
2725
+ });
2726
+ if (candidates.length !== 1) continue;
2727
+ const { extension, session } = candidates[0];
2728
+ if (this.hasPendingOperation(session.fileKey) || extensions.some((connection) => connection.sessions?.sessions.some((value) => value.fileKey === session.fileKey && value.busy))) continue;
2729
+ record.extensionId = extension.id;
2730
+ record.browser = {
2731
+ ...browser,
2732
+ documentId: session.documentId
2733
+ };
2734
+ record.ready = false;
2735
+ task.target = {
2736
+ ...task.target,
2737
+ sessionId: session.sessionId,
2738
+ fileName: session.fileName
2739
+ };
2740
+ task.epoch = (task.epoch ?? 0) + 1;
2741
+ task.needsRead = true;
2742
+ if (task.status === "interrupted") {
2743
+ record.ending = void 0;
2744
+ task.status = "active";
2745
+ task.expiresAt = this.now() + this.leaseMs;
2746
+ recovered.push({
2747
+ record,
2748
+ extension,
2749
+ session
2750
+ });
2751
+ }
2752
+ this.publish(record);
2753
+ }
2754
+ return recovered;
2755
+ }
2756
+ captureResult(taskId, rootNodeId, removed) {
2757
+ const record = this.records.get(taskId);
2758
+ if (!record) return;
2759
+ const ids = (record.resultNodeIds ?? []).filter((id) => id !== rootNodeId);
2760
+ record.resultNodeIds = (removed ? ids : [...ids, rootNodeId]).slice(-20);
2761
+ this.persist();
2762
+ }
2763
+ snapshotResult(taskId, summary) {
2764
+ const record = this.records.get(taskId);
2765
+ if (!record || record.task.result) return;
2766
+ record.task.result = {
2767
+ nodeIds: record.resultNodeIds ?? [],
2768
+ capturedAt: this.now(),
2769
+ ...summary ? { summary } : {}
2770
+ };
2771
+ this.persist();
2772
+ }
2773
+ stop(taskId, outcome) {
2774
+ const record = this.records.get(taskId);
2775
+ if (!record || ENDED_STATUSES.includes(record.task.status)) return record?.task;
2776
+ if (!RUNNING_STATUSES.includes(record.task.status)) {
2777
+ if (outcome === "completed" || outcome === "cancelled") this.finish(record, outcome);
2778
+ return record.task;
2779
+ }
2780
+ if (outcome === "cancelled" || !record.ending) record.ending = outcome;
2781
+ if ([...this.operations.values()].some((value) => value.taskId === taskId)) {
2782
+ record.task.status = "stopping";
2783
+ this.publish(record);
2784
+ } else this.finish(record, record.ending);
2785
+ return record.task;
2786
+ }
2787
+ disconnectOwner(ownerId) {
2788
+ for (const record of this.records.values()) if (record.ownerId === ownerId) this.stop(record.task.taskId, "paused");
2789
+ }
2790
+ disconnectExtension(extensionId) {
2791
+ for (const operation of this.operations.values()) if (operation.extensionId === extensionId) operation.uncertain = true;
2792
+ for (const record of this.records.values()) if (record.extensionId === extensionId) this.stop(record.task.taskId, "interrupted");
2793
+ }
2794
+ updatePage(taskId, pageId) {
2795
+ const record = this.records.get(taskId);
2796
+ if (!record || record.task.status !== "active") return;
2797
+ record.task.target.pageId = pageId;
2798
+ this.publish(record);
2799
+ }
2800
+ touch(taskId, ownerId) {
2801
+ this.renew(this.owned(taskId, ownerId, true));
2802
+ }
2803
+ sweep() {
2804
+ const now = this.now();
2805
+ for (const record of this.records.values()) if (record.task.status === "active" && !record.task.operation && record.task.expiresAt <= now) this.finish(record, "expired");
2806
+ }
2807
+ renew(record) {
2808
+ record.task.expiresAt = this.now() + this.leaseMs;
2809
+ this.publish(record);
2810
+ }
2811
+ finish(record, status) {
2812
+ record.task.status = status;
2813
+ record.task.operation = null;
2814
+ this.publish(record);
2815
+ }
2816
+ publish(record) {
2817
+ record.task.revision = ++this.revision;
2818
+ this.persist();
2819
+ if (this.current(record.task.target.fileKey) === record) this.options.onChange?.(record);
2820
+ }
2821
+ /** Load only after acquiring the Hub lock. Every old lease remains inactive. */
2822
+ restore() {
2823
+ const snapshot = this.options.store?.load();
2824
+ if (!snapshot) return;
2825
+ this.revision = snapshot.revision;
2826
+ for (const saved of snapshot.records) {
2827
+ const task = {
2828
+ ...saved.task,
2829
+ operation: null,
2830
+ epoch: (saved.task.epoch ?? 0) + 1,
2831
+ needsRead: true,
2832
+ capabilities: void 0,
2833
+ expiresAt: this.now(),
2834
+ revision: ++this.revision
2835
+ };
2836
+ if (task.status === "stopping") task.status = "cancelled";
2837
+ else if (["active", "interrupted"].includes(task.status)) task.status = "paused";
2838
+ this.records.set(task.taskId, {
2839
+ ...saved,
2840
+ task,
2841
+ ownerId: `restored:${task.taskId}`,
2842
+ extensionId: "",
2843
+ ready: false
2844
+ });
1294
2845
  }
1295
- try {
1296
- const files = readdirSync(ASSET_DIR);
1297
- const now = Date.now();
1298
- for (const file of files) {
1299
- if (file === INDEX_FILENAME) continue;
1300
- if (file.includes(".tmp.")) {
1301
- try {
1302
- const filePath = join(ASSET_DIR, file);
1303
- if (now - statSync(filePath).mtimeMs > 3600 * 1e3) {
1304
- rmSync(filePath, { force: true });
1305
- log.info({ file }, "Cleaned up stale temp file.");
1306
- }
1307
- } catch (e) {
1308
- log.debug({
1309
- error: e,
1310
- file
1311
- }, "Failed to cleanup stale temp file.");
1312
- }
1313
- continue;
1314
- }
1315
- const hash = getHashFromAssetFilename(file);
1316
- if (!hash) continue;
1317
- if (!records.has(hash)) {
1318
- const filePath = join(ASSET_DIR, file);
1319
- try {
1320
- const stat = statSync(filePath);
1321
- records.set(hash, {
1322
- hash,
1323
- filePath,
1324
- mimeType: "application/octet-stream",
1325
- size: stat.size,
1326
- uploadedAt: stat.birthtimeMs,
1327
- lastAccess: stat.atimeMs
1328
- });
1329
- changed = true;
1330
- log.info({ hash }, "Recovered orphan asset file.");
1331
- } catch (e) {
1332
- log.warn({
1333
- error: e,
1334
- file
1335
- }, "Failed to stat orphan file.");
1336
- }
1337
- }
1338
- }
1339
- } catch (error) {
1340
- log.warn({ error }, "Failed to scan asset directory for orphans.");
2846
+ for (const [fileKey, taskId] of Object.entries(snapshot.current)) if (this.records.get(taskId)?.task.target.fileKey === fileKey) this.currentTaskIds.set(fileKey, taskId);
2847
+ this.persist();
2848
+ }
2849
+ /** A registered page can recover its saved review, never its execution authority. */
2850
+ restoreReview(saved, extension, session) {
2851
+ if (saved.target.fileKey !== session.fileKey || !extension.sessions) return;
2852
+ let record = this.records.get(saved.taskId);
2853
+ if (record && (record.task.target.fileKey !== saved.target.fileKey || record.task.client?.kind !== saved.client?.kind || record.task.client?.sessionId !== saved.client?.sessionId)) return;
2854
+ if (!record) {
2855
+ if (this.current(session.fileKey)) return;
2856
+ record = {
2857
+ task: {
2858
+ ...saved,
2859
+ status: saved.status === "cancelled" ? "cancelled" : saved.status === "completed" ? "completed" : "paused",
2860
+ operation: null,
2861
+ capabilities: void 0,
2862
+ epoch: (saved.epoch ?? 0) + 1,
2863
+ needsRead: true,
2864
+ expiresAt: this.now()
2865
+ },
2866
+ ownerId: `restored:${saved.taskId}`,
2867
+ extensionId: "",
2868
+ requestId: "",
2869
+ ready: false
2870
+ };
2871
+ this.records.set(saved.taskId, record);
2872
+ this.currentTaskIds.set(session.fileKey, saved.taskId);
2873
+ this.publish(record);
1341
2874
  }
1342
- if (changed) flush();
2875
+ if (saved.reviewClosed) {
2876
+ this.closeReview(saved.taskId);
2877
+ return;
2878
+ }
2879
+ if (saved.status === "cancelled") {
2880
+ this.stop(saved.taskId, "cancelled");
2881
+ return;
2882
+ }
2883
+ if (record.task.reviewClosed || this.current(session.fileKey) !== record) return;
2884
+ if (record.task.status === "interrupted" && record.browser && record.browser.tabId === session.tabId && session.documentId !== void 0 && record.browser.documentId !== session.documentId) return;
2885
+ if (extension.sessions.sessions.some((value) => value.sessionId === record.task.target.sessionId) && record.task.target.sessionId !== session.sessionId) return;
2886
+ if (record.browser && (record.browser.browserId !== extension.sessions.browserId || record.browser.origin !== extension.origin)) return;
2887
+ if (record.task.target.sessionId === session.sessionId && record.extensionId === extension.id) return;
2888
+ if (RUNNING_STATUSES.includes(record.task.status)) return;
2889
+ record.extensionId = extension.id;
2890
+ record.ready = false;
2891
+ record.task.target = {
2892
+ ...record.task.target,
2893
+ sessionId: session.sessionId,
2894
+ fileName: session.fileName
2895
+ };
2896
+ if (session.tabId !== void 0 && session.documentId !== void 0) record.browser = {
2897
+ browserId: extension.sessions.browserId,
2898
+ origin: extension.origin,
2899
+ tabId: session.tabId,
2900
+ documentId: session.documentId
2901
+ };
2902
+ this.publish(record);
1343
2903
  }
1344
- loadExisting();
1345
- reconcile();
1346
- return {
1347
- list,
1348
- has,
1349
- get,
1350
- getMany,
1351
- upsert,
1352
- touch,
1353
- remove,
1354
- reconcile,
1355
- flush
1356
- };
1357
- }
2904
+ closeReview(taskId) {
2905
+ const record = this.records.get(taskId);
2906
+ if (!record || record.task.reviewClosed) return;
2907
+ record.task.reviewClosed = true;
2908
+ if (!ENDED_STATUSES.includes(record.task.status)) this.stop(taskId, "cancelled");
2909
+ else this.publish(record);
2910
+ }
2911
+ persist() {
2912
+ if (!this.options.store) return;
2913
+ const snapshot = {
2914
+ revision: this.revision,
2915
+ current: Object.fromEntries(this.currentTaskIds),
2916
+ records: [...this.records.values()].map(({ task, requestId, browser, resultNodeIds }) => ({
2917
+ task: {
2918
+ ...task,
2919
+ capabilities: void 0,
2920
+ operation: null
2921
+ },
2922
+ requestId,
2923
+ browser,
2924
+ resultNodeIds
2925
+ }))
2926
+ };
2927
+ this.options.store.save(snapshot);
2928
+ }
2929
+ };
1358
2930
  //#endregion
1359
2931
  //#region src/extension-registry.ts
1360
2932
  var ExtensionRegistry = class {
@@ -1433,15 +3005,22 @@ function attachExtensionSocket(ws, options) {
1433
3005
  const extension = {
1434
3006
  id: options.createId(),
1435
3007
  origin: options.origin.toLowerCase(),
3008
+ connectedAt: (/* @__PURE__ */ new Date()).toISOString(),
3009
+ legacy: ws.protocol !== TEMPAD_MCP_BRIDGE_SUBPROTOCOL,
1436
3010
  ws
1437
3011
  };
1438
3012
  options.registry.add(extension);
1439
3013
  options.onConnected?.(extension.id);
1440
3014
  const registered = {
1441
3015
  id: extension.id,
3016
+ protocolVersion: 13,
3017
+ supportedProtocolVersions: [...TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS],
1442
3018
  type: "registered"
1443
3019
  };
1444
- ws.send(JSON.stringify(registered));
3020
+ ws.send(JSON.stringify(extension.legacy ? {
3021
+ type: "registered",
3022
+ id: extension.id
3023
+ } : registered));
1445
3024
  options.onStateChange();
1446
3025
  scheduleAutoActivation(options);
1447
3026
  ws.on("message", (raw, isBinary) => {
@@ -1463,7 +3042,7 @@ function attachExtensionSocket(ws, options) {
1463
3042
  });
1464
3043
  return;
1465
3044
  }
1466
- const parseResult = MessageFromExtensionSchema.safeParse(parsedJson);
3045
+ const parseResult = (extension.legacy ? LegacyMessageFromExtensionSchema : MessageFromExtensionSchema).safeParse(parsedJson);
1467
3046
  if (!parseResult.success) {
1468
3047
  options.onProtocolWarning?.({
1469
3048
  error: parseResult.error.flatten(),
@@ -1474,6 +3053,13 @@ function attachExtensionSocket(ws, options) {
1474
3053
  }
1475
3054
  const message = parseResult.data;
1476
3055
  switch (message.type) {
3056
+ case "sessions":
3057
+ extension.sessions = message;
3058
+ options.onSessions?.(extension);
3059
+ break;
3060
+ case "designAction":
3061
+ options.onDesignAction?.(extension, message.sessionId, message.action);
3062
+ break;
1477
3063
  case "activate":
1478
3064
  if (options.registry.activate(extension.id)) {
1479
3065
  options.onActivated?.(extension.id);
@@ -1488,7 +3074,20 @@ function attachExtensionSocket(ws, options) {
1488
3074
  if (message.error !== void 0) options.onToolError(message.id, extension.id, message.error);
1489
3075
  else options.onToolResult(message.id, extension.id, message.payload);
1490
3076
  break;
1491
- case "ping": break;
3077
+ case "runtimeHello":
3078
+ if (extension.runtime && (extension.runtime.version !== message.extensionVersion || extension.runtime.fingerprint !== message.extensionRuntimeFingerprint)) {
3079
+ options.onProtocolWarning?.({
3080
+ error: /* @__PURE__ */ new Error("Extension changed runtime identity on an open connection."),
3081
+ extensionId: extension.id,
3082
+ kind: "schema"
3083
+ });
3084
+ break;
3085
+ }
3086
+ extension.runtime = {
3087
+ version: message.extensionVersion,
3088
+ fingerprint: message.extensionRuntimeFingerprint
3089
+ };
3090
+ options.onRuntimeHello?.(extension);
1492
3091
  }
1493
3092
  });
1494
3093
  ws.on("error", (error) => {
@@ -1517,7 +3116,7 @@ function rawDataToBuffer(raw) {
1517
3116
  }
1518
3117
  //#endregion
1519
3118
  //#region src/instructions.md?raw
1520
- var instructions_default = "You are connected to a Figma design file via TemPad Dev MCP.\n\nTreat tool outputs as design facts. Refactor only to match the user’s repo conventions; do not invent key style values.\n\nRules:\n\n- For Figma authoring, combine Host design-system guidance with one `get_design_system` call. Prefer\n returned components and semantic variables, use primitives or literals only for gaps, then send\n one declarative `apply_canvas` result; do not emulate individual Figma Plugin API calls.\n- Reuse `nodeIdsByKey` returned by `apply_canvas` when refining existing generated content. Omitted\n fields and children are preserved; deletion is not supported.\n- Never output any `data-hint-*` attributes from tool outputs (hints only).\n- If `get_code` warns `depth-cap`, keep the returned parent code as composition evidence and use returned `data-hint-id` values to choose narrower `get_code` follow-ups.\n- If `get_code` warns `shell`, read the inline code comment for omitted direct child ids, then call `get_code` for those ids in order and fill the results back into the returned shell.\n- Use `get_structure` only to resolve layout/overlap uncertainty; do not derive numeric values from images.\n- Tokens: `get_code.tokens` keys are canonical names (`--...`). Multi‑mode values use `${collectionName}:${modeName}`. Nodes may hint per-node overrides via `data-hint-variable-mode=\"Collection=Mode;...\"`.\n- Vectors: `vectorMode=smart` is the default. Treat the emitted markup as the source of truth for the current response; vector code is emitted as `<svg data-src=\"...\">` placeholders, but if asset upload fails after export the tool may inline the SVG as a fallback to preserve source of truth.\n- Themeable vectors: `themeable=true` means the SVG can safely adopt one contextual color channel. In `smart` mode, that color is typically already evidenced on the emitted `svg` root markup for the placeholder. It does not mean the SVG exposes multiple independent color parameters.\n- Assets: download bytes via `asset.url`. Asset resources are not exposed via MCP `resources/read`. Use `asset.themeable` only when an SVG still needs repo asset handling after you account for the Host app's vector policy.\n";
3119
+ 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 `begin_design` 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 `begin_design` before research or writing, then 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;\nresume the same task with `resume_design`, 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.\n`end_design` is for a verified completed pass or explicit cancellation, not 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,\nbegin a fresh task with a new 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";
1521
3120
  //#endregion
1522
3121
  //#region src/request.ts
1523
3122
  const pendingCalls = /* @__PURE__ */ new Map();
@@ -1526,11 +3125,19 @@ function createToolError(code, message) {
1526
3125
  err.code = code;
1527
3126
  return err;
1528
3127
  }
1529
- function register(extensionId, timeout) {
3128
+ function register(extensionId, timeout, options = {}) {
1530
3129
  const requestId = nanoid();
1531
3130
  return {
1532
3131
  promise: new Promise((resolve, reject) => {
1533
3132
  const timer = setTimeout(() => {
3133
+ if (options.waitForDefinitiveResult) {
3134
+ log.warn({
3135
+ reqId: requestId,
3136
+ extId: extensionId,
3137
+ timeout
3138
+ }, "Extension call exceeded its warning threshold; waiting for a definitive result.");
3139
+ return;
3140
+ }
1534
3141
  pendingCalls.delete(requestId);
1535
3142
  reject(createToolError(TEMPAD_MCP_ERROR_CODES.EXTENSION_TIMEOUT, `Extension did not respond within ${timeout / 1e3}s.`));
1536
3143
  }, timeout);
@@ -1544,39 +3151,34 @@ function register(extensionId, timeout) {
1544
3151
  requestId
1545
3152
  };
1546
3153
  }
1547
- function resolve(requestId, extensionId, payload) {
3154
+ function pendingResponse(requestId, extensionId, outcome) {
1548
3155
  const call = pendingCalls.get(requestId);
1549
- if (call) {
1550
- if (call.extensionId !== extensionId) {
1551
- log.warn({
1552
- reqId: requestId,
1553
- expectedExtId: call.extensionId,
1554
- receivedExtId: extensionId
1555
- }, "Ignored tool result from the wrong extension.");
1556
- return;
1557
- }
1558
- const { timer, resolve: finish } = call;
1559
- clearTimeout(timer);
1560
- finish(payload);
1561
- pendingCalls.delete(requestId);
1562
- } else log.warn({ reqId: requestId }, "Received result for unknown/timed-out call.");
3156
+ if (!call) {
3157
+ log.warn({ reqId: requestId }, `Received ${outcome} for unknown/timed-out call.`);
3158
+ return;
3159
+ }
3160
+ if (call.extensionId !== extensionId) {
3161
+ log.warn({
3162
+ reqId: requestId,
3163
+ expectedExtId: call.extensionId,
3164
+ receivedExtId: extensionId
3165
+ }, `Ignored tool ${outcome} from the wrong extension.`);
3166
+ return;
3167
+ }
3168
+ clearTimeout(call.timer);
3169
+ return call;
3170
+ }
3171
+ function resolve$1(requestId, extensionId, payload) {
3172
+ const call = pendingResponse(requestId, extensionId, "result");
3173
+ if (!call) return;
3174
+ call.resolve(payload);
3175
+ pendingCalls.delete(requestId);
1563
3176
  }
1564
3177
  function reject(requestId, extensionId, error) {
1565
- const call = pendingCalls.get(requestId);
1566
- if (call) {
1567
- if (call.extensionId !== extensionId) {
1568
- log.warn({
1569
- reqId: requestId,
1570
- expectedExtId: call.extensionId,
1571
- receivedExtId: extensionId
1572
- }, "Ignored tool error from the wrong extension.");
1573
- return;
1574
- }
1575
- const { timer, reject: fail } = call;
1576
- clearTimeout(timer);
1577
- fail(error);
1578
- pendingCalls.delete(requestId);
1579
- } else log.warn({ reqId: requestId }, "Received error for unknown/timed-out call.");
3178
+ const call = pendingResponse(requestId, extensionId, "error");
3179
+ if (!call) return;
3180
+ call.reject(error);
3181
+ pendingCalls.delete(requestId);
1580
3182
  }
1581
3183
  function cleanupForExtension(extensionId) {
1582
3184
  for (const [reqId, call] of pendingCalls.entries()) {
@@ -1602,7 +3204,81 @@ function cleanupAll() {
1602
3204
  pendingCalls.clear();
1603
3205
  }
1604
3206
  //#endregion
3207
+ //#region src/runtime-identity.ts
3208
+ function fingerprintRuntimeFile(path) {
3209
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
3210
+ }
3211
+ function createHubRuntimeIdentity(entryPath, packageVersion, options = {}) {
3212
+ return {
3213
+ schemaVersion: 1,
3214
+ packageVersion,
3215
+ runtimeFingerprint: fingerprintRuntimeFile(entryPath),
3216
+ entryPath: resolve(entryPath),
3217
+ startedAt: (options.now ?? /* @__PURE__ */ new Date()).toISOString(),
3218
+ processId: options.processId ?? process.pid,
3219
+ activeExtension: null
3220
+ };
3221
+ }
3222
+ function isSha256(value) {
3223
+ return typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
3224
+ }
3225
+ function parseHubRuntimeIdentity(value) {
3226
+ if (!value || typeof value !== "object") return null;
3227
+ const candidate = value;
3228
+ const activeExtension = parseActiveExtensionRuntimeIdentity(candidate.activeExtension);
3229
+ if (candidate.schemaVersion !== 1 || typeof candidate.packageVersion !== "string" || !isSha256(candidate.runtimeFingerprint) || typeof candidate.entryPath !== "string" || typeof candidate.startedAt !== "string" || !Number.isFinite(Date.parse(candidate.startedAt)) || typeof candidate.processId !== "number" || !Number.isInteger(candidate.processId) || activeExtension === void 0) return null;
3230
+ return {
3231
+ ...candidate,
3232
+ activeExtension
3233
+ };
3234
+ }
3235
+ function parseActiveExtensionRuntimeIdentity(value) {
3236
+ if (value === void 0 || value === null) return null;
3237
+ if (!value || typeof value !== "object") return void 0;
3238
+ const candidate = value;
3239
+ if (typeof candidate.id !== "string" || typeof candidate.connectedAt !== "string" || !Number.isFinite(Date.parse(candidate.connectedAt)) || candidate.version !== null && typeof candidate.version !== "string" || candidate.fingerprint !== null && !isSha256(candidate.fingerprint)) return;
3240
+ return candidate;
3241
+ }
3242
+ function readHubRuntimeIdentity(path) {
3243
+ try {
3244
+ return parseHubRuntimeIdentity(JSON.parse(readFileSync(path, "utf8")));
3245
+ } catch {
3246
+ return null;
3247
+ }
3248
+ }
3249
+ function writeHubRuntimeIdentity(path, identity) {
3250
+ const temporaryPath = `${path}.${identity.processId}.tmp`;
3251
+ writeFileSync(temporaryPath, `${JSON.stringify(identity, null, 2)}\n`, { mode: 384 });
3252
+ renameSync(temporaryPath, path);
3253
+ }
3254
+ function removeHubRuntimeIdentityIfOwned(path, processId) {
3255
+ if (readHubRuntimeIdentity(path)?.processId !== processId) return;
3256
+ rmSync(path, { force: true });
3257
+ }
3258
+ function getExtensionRuntimeIssues(runtime) {
3259
+ if (!runtime) return ["Extension did not publish a runtime identity handshake"];
3260
+ return [];
3261
+ }
3262
+ //#endregion
1605
3263
  //#region src/tools.ts
3264
+ const READ_ONLY_ANNOTATIONS = {
3265
+ readOnlyHint: true,
3266
+ destructiveHint: false,
3267
+ idempotentHint: true,
3268
+ openWorldHint: false
3269
+ };
3270
+ const CANVAS_WRITE_ANNOTATIONS = {
3271
+ readOnlyHint: false,
3272
+ destructiveHint: true,
3273
+ idempotentHint: false,
3274
+ openWorldHint: true
3275
+ };
3276
+ const ASSET_WRITE_ANNOTATIONS = {
3277
+ readOnlyHint: false,
3278
+ destructiveHint: false,
3279
+ idempotentHint: true,
3280
+ openWorldHint: false
3281
+ };
1606
3282
  const CONNECTIVITY_ERROR_CODES = /* @__PURE__ */ new Set([
1607
3283
  TEMPAD_MCP_ERROR_CODES.NO_ACTIVE_EXTENSION,
1608
3284
  TEMPAD_MCP_ERROR_CODES.EXTENSION_TIMEOUT,
@@ -1614,17 +3290,15 @@ const SELECTION_ERROR_CODES = /* @__PURE__ */ new Set([TEMPAD_MCP_ERROR_CODES.IN
1614
3290
  const KNOWN_ERROR_CODES = new Set(Object.values(TEMPAD_MCP_ERROR_CODES));
1615
3291
  const CONNECTIVITY_TROUBLESHOOTING_LINES = [
1616
3292
  "Troubleshooting:",
1617
- "- In Figma, open TemPad Dev panel and enable the MCP server in Preferences → Agent integration.",
1618
- "- If multiple Figma tabs are open, click the MCP badge to activate this tab.",
1619
- "- Keep the Figma tab active/foreground while using the MCP server."
3293
+ "- 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.",
3294
+ "- 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.",
3295
+ "- If the connection is missing or reports a protocol mismatch, rebuild the affected runtime layers, reload the installed TemPad Dev browser extension, reload the same Figma tab, and start a fresh task."
1620
3296
  ];
1621
3297
  const SELECTION_TROUBLESHOOTING_LINE = "Tip: Select exactly one visible node, or pass nodeId.";
3298
+ const VERIFICATION_TROUBLESHOOTING_LINE = "Tip: TemPad rolls verification failures back. Correct the reported desired-state mismatch and retry the affected root while preserving unrelated design intent.";
1622
3299
  function isRecord(value) {
1623
3300
  return !!value && typeof value === "object" && !Array.isArray(value);
1624
3301
  }
1625
- function getRecordProperty$1(record, key) {
1626
- return isRecord(record) ? record[key] : void 0;
1627
- }
1628
3302
  function extTool(definition) {
1629
3303
  return definition;
1630
3304
  }
@@ -1632,23 +3306,75 @@ function hubTool(definition) {
1632
3306
  return definition;
1633
3307
  }
1634
3308
  const TOOL_DEFS = [
3309
+ hubTool({
3310
+ name: "get_design_task",
3311
+ description: "Read this conversation’s task state and current epoch for recovery or an explicit status request. Does not renew its lease. Do not poll it for routine progress.",
3312
+ annotations: READ_ONLY_ANNOTATIONS,
3313
+ parameters: z.object({ taskId: DesignTaskIdSchema }).strict(),
3314
+ target: "hub",
3315
+ outputSchema: DesignTaskSchema
3316
+ }),
3317
+ hubTool({
3318
+ name: "list_design_sessions",
3319
+ description: "List connected Figma targets before beginning a design or an exact-session read. Select an exact sessionId when more than one file is connected.",
3320
+ annotations: READ_ONLY_ANNOTATIONS,
3321
+ parameters: z.object({}).strict(),
3322
+ target: "hub",
3323
+ outputSchema: z.object({ sessions: z.array(FigmaSessionSchema) })
3324
+ }),
3325
+ hubTool({
3326
+ name: "resume_design",
3327
+ description: "Continue the current design task after pause, expiry, interruption, or completion awaiting review. Keep the same taskId and design region for follow-up comments until the user clicks Done. Cancelled, closed, or replaced tasks cannot resume. The original browser tab automatically rebinds after a page refresh; get_design_task returns its current epoch. Pass that epoch to resume. Pass the returned epoch as taskEpoch on subsequent calls, and read the bound canvas with get_structure or get_code before writing. Never replay an old write.",
3328
+ annotations: ASSET_WRITE_ANNOTATIONS,
3329
+ parameters: ResumeDesignParametersSchema,
3330
+ target: "hub",
3331
+ outputSchema: DesignTaskSchema
3332
+ }),
3333
+ hubTool({
3334
+ name: "begin_design",
3335
+ description: "Begin a new design task in the active Figma session before design research or writing. Returns a taskId bound to that file and session; pass it on subsequent task calls. No coordinates or progress reports are needed. Idle ownership expires after five minutes. Reuse requestId only when retrying this same begin. Stop a busy task in TemPad Dev before another task takes over. For follow-up comments on an open review, use resume_design on the same task, including after completion. Beginning a new task replaces the previous task for that file.",
3336
+ annotations: ASSET_WRITE_ANNOTATIONS,
3337
+ parameters: BeginDesignParametersSchema,
3338
+ target: "hub",
3339
+ outputSchema: DesignTaskSchema
3340
+ }),
3341
+ hubTool({
3342
+ name: "end_design",
3343
+ description: "Mark this design pass complete after the requested outcome and its verification. Releases file ownership and keeps the same task, design region, and review open for comments. Follow-up comments resume this task; only the user’s Done closes the review. Waiting for input before the outcome is ready or stopping a turn is a pause. Cancel when abandoning a task; already completed writes remain. Retrying within the same epoch is safe. Cancellation waits for a running operation to finish before handing over the file.",
3344
+ annotations: ASSET_WRITE_ANNOTATIONS,
3345
+ parameters: EndDesignParametersSchema,
3346
+ target: "hub",
3347
+ outputSchema: DesignTaskSchema
3348
+ }),
3349
+ extTool({
3350
+ name: "set_design_anchor",
3351
+ 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.",
3352
+ annotations: ASSET_WRITE_ANNOTATIONS,
3353
+ parameters: SetDesignAnchorParametersSchema,
3354
+ target: "extension",
3355
+ outputSchema: DesignAnchorSchema,
3356
+ format: createDesignAnchorToolResponse
3357
+ }),
1635
3358
  extTool({
1636
3359
  name: "get_code",
1637
- description: "High-fidelity code snapshot for nodeId/current single selection (omit nodeId to use selection): JSX/Vue markup + Tailwind-like classes, plus assets/tokens metadata and codegen config. `vectorMode=smart` (default) emits `<svg data-src=\"...\">` placeholders in code and preserves themeable instance color on the emitted SVG root markup for downstream adaptation; if asset upload fails after export, the tool may inline the SVG as a fallback to preserve source of truth. `vectorMode=snapshot` preserves vector assets for fidelity. Host apps should still refactor vector delivery to repo policy where needed (existing icon/component primitives, import-time SVG transforms, inline SVG, or asset-backed SVG usage). SVG asset metadata may include `themeable=true`, meaning the exported asset can safely adopt one contextual color channel. Start here, then refactor into repo conventions while preserving values/intent; strip any data-hint-* attributes (hints only). If warnings include depth-cap, use returned data-hint-id values to continue with narrower get_code calls. If warnings include shell, read the inline comment for omitted direct child ids and fetch them in order. If warnings include auto-layout (inferred), use get_structure to confirm hierarchy/overlap (do not derive numeric values from pixels). Tokens are keyed by canonical names like `--color-primary` (multi-mode keys use `${collection}:${mode}`; node overrides may appear as data-hint-variable-mode).",
3360
+ description: "Read implementation evidence for an existing Figma node or the current single selection as JSX/Vue markup, classes, tokens, assets, codegen facts, and bounded warnings.",
3361
+ annotations: READ_ONLY_ANNOTATIONS,
1638
3362
  parameters: GetCodeParametersSchema,
1639
3363
  target: "extension",
1640
3364
  format: createCodeToolResponse
1641
3365
  }),
1642
3366
  extTool({
1643
3367
  name: "get_design_system",
1644
- description: "Return a compact, query-ranked set of Figma components and variables from the current page/file. Reuse returned ids/keys in apply_canvas.",
3368
+ description: "Discover resources, file pages, or available fonts. For fonts, use scope: \"fonts\" with query to find families or families to read exact native styles; this reads the environment without scanning file resources and is allowed for independent designs. Resource discovery returns a bounded catalog with component tags, variable cssName and text-style className aliases. When existing-resource reuse is permitted and relevant, scope: \"pages\" lists page IDs cheaply; pageId loads that page and limits component discovery to it while local variables, styles, and shaders remain file-wide. Omit pageId for a quick scan; off-current pages may omit components even if queried successfully. Skip resource and page discovery when the user limits design evidence to the current page or requests an independent system. Continue catalogs by catalogId/cursor or inspect catalogId/ref.",
3369
+ annotations: READ_ONLY_ANNOTATIONS,
1645
3370
  parameters: GetDesignSystemParametersSchema,
1646
3371
  target: "extension",
1647
3372
  format: createDesignSystemToolResponse
1648
3373
  }),
1649
3374
  extTool({
1650
3375
  name: "apply_canvas",
1651
- description: "Apply one declarative canvas tree. Create adds a FRAME tree; update safely reconciles within targetNodeId, preserving omissions and skipping unchanged values. Requires Canvas writes.",
3376
+ description: "Create, update, remove, or activate exact Figma pages and managed roots. Canvas HTML supports documented Tailwind utilities without CSS cascade: resolve conflicting classes before sending. CSS variable classes bind through catalog aliases or theme; type-* classes bind native text styles. Define new resources with variableCollections/styles and use their stable keys in theme in the same call. Markup is optional for page-only operations and native-only updates inside an exact managed root. When markup is supplied, every native key must occur in that tree. Create auto-places a root; update preserves omitted live state and topology; remove accepts an exact managed root or page; activate changes editor context without a document mutation. Exact off-current-page writes do not require activation.",
3377
+ annotations: CANVAS_WRITE_ANNOTATIONS,
1652
3378
  parameters: ApplyCanvasParametersSchema,
1653
3379
  target: "extension",
1654
3380
  format: createApplyCanvasToolResponse
@@ -1656,6 +3382,7 @@ const TOOL_DEFS = [
1656
3382
  extTool({
1657
3383
  name: "get_token_defs",
1658
3384
  description: "Resolve canonical token names to literal values (optionally including all modes) for tokens referenced by get_code.",
3385
+ annotations: READ_ONLY_ANNOTATIONS,
1659
3386
  parameters: GetTokenDefsParametersSchema,
1660
3387
  target: "extension",
1661
3388
  format: createTokenDefsToolResponse,
@@ -1663,22 +3390,33 @@ const TOOL_DEFS = [
1663
3390
  }),
1664
3391
  extTool({
1665
3392
  name: "get_screenshot",
1666
- description: "Capture a rendered PNG screenshot for nodeId/current single selection for visual verification (layering/overlap/masks/effects).",
3393
+ description: "Capture one bounded rendered PNG asset for an exact node or the current single selection.",
3394
+ annotations: READ_ONLY_ANNOTATIONS,
1667
3395
  parameters: GetScreenshotParametersSchema,
1668
3396
  target: "extension",
1669
- format: createScreenshotToolResponse,
1670
- exposed: false
3397
+ format: createScreenshotToolResponse
1671
3398
  }),
1672
3399
  extTool({
1673
3400
  name: "get_structure",
1674
- description: "Get a compact structural + geometry outline for nodeId/current single selection to understand hierarchy and layout intent.",
3401
+ description: "Read a compact hierarchy and geometry outline for an exact node, exact page id/key, or the current single selection. Every x/y is relative to the node's actual Figma parent; page-query roots are page-relative. The outline includes stable keys on TemPad-managed nodes and exact page context when page identity is supplied. Set options.native for selected native read-back; it does not provide rendered pixels or general appearance.",
3402
+ annotations: READ_ONLY_ANNOTATIONS,
1675
3403
  parameters: GetStructureParametersSchema,
1676
3404
  target: "extension",
1677
3405
  format: createStructureToolResponse
1678
3406
  }),
3407
+ hubTool({
3408
+ name: "upload_asset",
3409
+ description: "Store a generated PNG, JPEG, or GIF data URL in the local Hub and return its content-addressed assetHash for apply_canvas. Compose this call directly with the image-generation result; never print or copy encoded bytes into prose.",
3410
+ annotations: ASSET_WRITE_ANNOTATIONS,
3411
+ parameters: UploadAssetParametersSchema,
3412
+ target: "hub",
3413
+ outputSchema: UploadAssetResultSchema,
3414
+ format: createUploadAssetToolResponse
3415
+ }),
1679
3416
  hubTool({
1680
3417
  name: "get_assets",
1681
3418
  description: "Resolve asset hashes to downloadable URLs and metadata for assets referenced by tool responses. SVG asset metadata may include `themeable=true` when the underlying vector can safely adopt one contextual color channel.",
3419
+ annotations: READ_ONLY_ANNOTATIONS,
1682
3420
  parameters: GetAssetsParametersSchema,
1683
3421
  target: "hub",
1684
3422
  outputSchema: GetAssetsResultSchema,
@@ -1686,9 +3424,10 @@ const TOOL_DEFS = [
1686
3424
  })
1687
3425
  ];
1688
3426
  function extractToolErrorCode(error) {
1689
- const code = getRecordProperty$1(error, "code");
3427
+ const code = getRecordProperty(error, "code");
1690
3428
  if (isTempadMcpErrorCode(code)) return code;
1691
- const causeCode = getRecordProperty$1(getRecordProperty$1(error, "cause"), "code");
3429
+ const cause = getRecordProperty(error, "cause");
3430
+ const causeCode = getRecordProperty(cause, "code");
1692
3431
  if (isTempadMcpErrorCode(causeCode)) return causeCode;
1693
3432
  }
1694
3433
  function isTempadMcpErrorCode(value) {
@@ -1697,9 +3436,8 @@ function isTempadMcpErrorCode(value) {
1697
3436
  function extractToolErrorMessage(error) {
1698
3437
  if (error instanceof Error) return error.message || "Unknown error occurred.";
1699
3438
  if (typeof error === "string") return error;
1700
- if (isRecord(error)) {
1701
- if (typeof error.message === "string" && error.message.trim()) return error.message;
1702
- }
3439
+ const message = getRecordProperty(error, "message");
3440
+ if (typeof message === "string" && message.trim()) return message;
1703
3441
  return "Unknown error occurred.";
1704
3442
  }
1705
3443
  function createToolErrorResponse(toolName, error) {
@@ -1717,10 +3455,11 @@ function buildTroubleshootingText(code, message) {
1717
3455
  const help = [];
1718
3456
  if (isConnectivityToolError(code, message)) help.push(...CONNECTIVITY_TROUBLESHOOTING_LINES);
1719
3457
  if (isSelectionToolError(code, message)) help.push(SELECTION_TROUBLESHOOTING_LINE);
3458
+ if (code === TEMPAD_MCP_ERROR_CODES.INVALID_CANVAS_SPEC && /verification failed/i.test(message)) help.push(VERIFICATION_TROUBLESHOOTING_LINE);
1720
3459
  return help.length ? `\n\n${help.join("\n")}` : "";
1721
3460
  }
1722
3461
  function isConnectivityToolError(code, message) {
1723
- return (code ? CONNECTIVITY_ERROR_CODES.has(code) : false) || /no active tempad dev extension/i.test(message) || /asset server url is not configured/i.test(message) || /websocket/i.test(message);
3462
+ return (code ? CONNECTIVITY_ERROR_CODES.has(code) : false) || /no active tempad dev extension/i.test(message) || /asset server url is not configured/i.test(message) || /\bwebsocket (?:connection )?(?:closed|disconnected|failed|unavailable|error)\b/i.test(message);
1724
3463
  }
1725
3464
  function isSelectionToolError(code, message) {
1726
3465
  return (code ? SELECTION_ERROR_CODES.has(code) : false) || /select exactly one visible node/i.test(message) || /no visible node found/i.test(message);
@@ -1751,10 +3490,10 @@ function isScreenshotResult(payload) {
1751
3490
  return isRecord(payload) && isRecord(payload.asset) && typeof payload.width === "number" && typeof payload.height === "number" && typeof payload.scale === "number" && typeof payload.bytes === "number" && typeof payload.format === "string";
1752
3491
  }
1753
3492
  function isDesignSystemResult(payload) {
1754
- return isRecord(payload) && isRecord(payload.page) && Array.isArray(payload.components) && Array.isArray(payload.variables);
3493
+ return GetDesignSystemResultSchema.safeParse(payload).success;
1755
3494
  }
1756
3495
  function isApplyCanvasResult(payload) {
1757
- return isRecord(payload) && typeof payload.rootNodeId === "string" && isRecord(payload.nodeIdsByKey) && Array.isArray(payload.createdNodeIds) && Array.isArray(payload.updatedNodeIds) && typeof payload.mutationCount === "number";
3496
+ return ApplyCanvasResultSchema.safeParse(payload).success;
1758
3497
  }
1759
3498
  function isCodeResult(payload) {
1760
3499
  return isRecord(payload) && typeof payload.code === "string" && typeof payload.lang === "string" && (payload.assets === void 0 || Array.isArray(payload.assets));
@@ -1777,12 +3516,36 @@ function coercePayloadToToolResponse(payload) {
1777
3516
  function createAssetsToolResponse(payload) {
1778
3517
  return toCallToolResult(buildGetAssetsToolResult(payload));
1779
3518
  }
3519
+ function createUploadAssetToolResponse(payload) {
3520
+ return toCallToolResult(buildUploadAssetToolResult(payload));
3521
+ }
3522
+ function createDesignTaskToolResponse(payload) {
3523
+ const task = DesignTaskSchema.parse(payload);
3524
+ return {
3525
+ content: [{
3526
+ type: "text",
3527
+ text: JSON.stringify(task)
3528
+ }],
3529
+ structuredContent: task
3530
+ };
3531
+ }
3532
+ function createDesignAnchorToolResponse(payload) {
3533
+ const anchor = DesignAnchorSchema.parse(payload);
3534
+ return {
3535
+ content: [{
3536
+ type: "text",
3537
+ text: JSON.stringify(anchor)
3538
+ }],
3539
+ structuredContent: anchor
3540
+ };
3541
+ }
1780
3542
  function createInlineBudgetExceededToolResponse(toolName, actualBytes) {
3543
+ const guidance = getBudgetRetryGuidance(toolName);
1781
3544
  return {
1782
3545
  isError: true,
1783
3546
  content: [{
1784
3547
  type: "text",
1785
- text: `Tool "${toolName}" exceeded the 64 KiB inline budget (${actualBytes} UTF-8 bytes > ${MCP_TOOL_INLINE_BUDGET_BYTES}). ${getBudgetRetryGuidance(toolName)}`
3548
+ text: `Tool "${toolName}" exceeded the 64 KiB inline budget (${actualBytes} UTF-8 bytes > ${MCP_TOOL_INLINE_BUDGET_BYTES}). ${guidance}`
1786
3549
  }]
1787
3550
  };
1788
3551
  }
@@ -1791,14 +3554,20 @@ function toCallToolResult(result) {
1791
3554
  }
1792
3555
  function getBudgetRetryGuidance(toolName) {
1793
3556
  switch (toolName) {
3557
+ case "get_design_task":
3558
+ case "list_design_sessions":
3559
+ case "begin_design":
3560
+ case "resume_design":
3561
+ case "end_design":
3562
+ case "set_design_anchor": return "Retry the same task lifecycle request without changing its identity.";
1794
3563
  case "apply_canvas": return "Submit a smaller desired subtree and retry.";
1795
3564
  case "get_code": return "Reduce selection size or request a smaller nodeId subtree and retry.";
1796
- case "get_design_system": return "Use a narrower design-system query and retry.";
3565
+ case "get_design_system": return "Continue from another catalog cursor or avoid the oversized exact definition.";
1797
3566
  case "get_structure": return "Reduce selection size or pass a smaller depth and retry.";
1798
3567
  case "get_token_defs": return "Reduce requested names or split them into smaller batches and retry.";
1799
- case "get_screenshot": return "Reduce selection size or scale and retry.";
3568
+ case "get_screenshot": return "Pass a smaller nodeId and retry.";
1800
3569
  case "get_assets": return "Request fewer hashes in a single call and retry.";
1801
- default: return "Retry with a narrower request.";
3570
+ case "upload_asset": return "Generate a smaller PNG, JPEG, or GIF and retry without printing its data URL.";
1802
3571
  }
1803
3572
  }
1804
3573
  //#endregion
@@ -1809,12 +3578,14 @@ async function startExtensionWebSocketServer({ maxPayloadBytes, maxConnections,
1809
3578
  host: "127.0.0.1",
1810
3579
  port: candidate,
1811
3580
  maxPayload: maxPayloadBytes,
3581
+ handleProtocols: (protocols) => protocols.has("tempad-mcp") ? TEMPAD_MCP_BRIDGE_SUBPROTOCOL : false,
1812
3582
  verifyClient: (info) => {
1813
3583
  if (server.clients.size >= maxConnections) {
1814
3584
  onConnectionLimit?.(maxConnections);
1815
3585
  return false;
1816
3586
  }
1817
- const allowed = isAllowedWebSocketRequest(info.origin, info.req.url, originPolicy);
3587
+ const protocol = info.req.headers["sec-websocket-protocol"];
3588
+ const allowed = isAllowedWebSocketRequest(info.origin, info.req.url, originPolicy) && (!protocol || protocol.split(",").some((value) => value.trim() === "tempad-mcp"));
1818
3589
  if (!allowed) onRejectedHandshake?.(info.origin, info.req.url);
1819
3590
  return allowed;
1820
3591
  }
@@ -1859,20 +3630,42 @@ function resolveListeningPort(server, candidate) {
1859
3630
  //#region src/hub.ts
1860
3631
  const SHUTDOWN_TIMEOUT = 2e3;
1861
3632
  const SOCKET_PROBE_TIMEOUT_MS = 300;
1862
- const { wsPortCandidates, toolTimeoutMs, maxPayloadBytes, maxExtensionConnections, autoActivateGraceMs, assetTtlMs, allowedExtensionOrigins } = getMcpServerConfig();
3633
+ const EXACT_SESSION_READ_TOOLS = /* @__PURE__ */ new Set([
3634
+ "get_code",
3635
+ "get_structure",
3636
+ "get_screenshot",
3637
+ "get_design_system",
3638
+ "get_token_defs"
3639
+ ]);
3640
+ const { wsPortCandidates, toolTimeoutMs, getCodeTimeoutMs, getDesignSystemTimeoutMs, pageStructureTimeoutMs, applyCanvasTimeoutMs, maxPayloadBytes, maxAssetSizeBytes, maxExtensionConnections, autoActivateGraceMs, assetTtlMs, allowedExtensionOrigins } = getMcpServerConfig();
1863
3641
  const extensionOriginPolicy = createExtensionOriginPolicy(allowedExtensionOrigins);
1864
3642
  log.info({ version: PACKAGE_VERSION }, "TemPad MCP Hub starting...");
1865
3643
  const extensionRegistry = new ExtensionRegistry(autoActivateGraceMs);
3644
+ const taskStateDirectory = join(homedir(), ".tempad-dev", "state");
3645
+ const designTasks = new DesignTasks({
3646
+ createId: randomUUID,
3647
+ onChange: publishDesignTask,
3648
+ store: new DesignTaskStore(join(taskStateDirectory, "design-tasks.json"))
3649
+ });
3650
+ const agentClients = new AgentClients(designTasks, new CodexAppFeedback(join(taskStateDirectory, "codex-feedback")), (changed) => new CodexAppLifecycle(changed));
3651
+ let refreshingCapabilities = false;
3652
+ const clientCapabilityTimer = setInterval(() => {
3653
+ if (refreshingCapabilities) return;
3654
+ refreshingCapabilities = true;
3655
+ agentClients.refreshCapabilities().catch((error) => log.warn({ error }, "Could not refresh agent capabilities.")).finally(() => {
3656
+ refreshingCapabilities = false;
3657
+ });
3658
+ }, 1e4);
3659
+ const pendingDesignBindings = /* @__PURE__ */ new Map();
3660
+ const designTaskTimer = setInterval(() => designTasks.sweep(), 1e3);
3661
+ designTaskTimer.unref();
1866
3662
  let consumerCount = 0;
1867
3663
  let selectedWsPort = 0;
1868
3664
  let releaseHubLock = null;
1869
3665
  let shuttingDown = false;
1870
3666
  let wss = null;
3667
+ let hubRuntimeIdentity = null;
1871
3668
  const consumerSessions = /* @__PURE__ */ new Set();
1872
- function getRecordProperty(record, key) {
1873
- if (!record || typeof record !== "object") return;
1874
- return Reflect.get(record, key);
1875
- }
1876
3669
  function classifySocketProbeError(error) {
1877
3670
  if (error.code === "ENOENT") return "missing";
1878
3671
  if (error.code === "ECONNREFUSED" || error.code === "ENOTSOCK") return { staleCode: error.code };
@@ -1955,10 +3748,44 @@ async function cleanSocketPath() {
1955
3748
  function enrichToolDefinition(tool) {
1956
3749
  if (tool.target === "extension") return tool;
1957
3750
  switch (tool.name) {
3751
+ case "get_design_task": return {
3752
+ ...tool,
3753
+ handler: async (args, ownerId) => createDesignTaskToolResponse(designTasks.owned(args.taskId, ownerId).task)
3754
+ };
3755
+ case "list_design_sessions": return {
3756
+ ...tool,
3757
+ handler: async () => {
3758
+ const result = { sessions: extensionRegistry.list().flatMap((value) => value.sessions?.sessions ?? []) };
3759
+ if (!result.sessions.length && extensionRegistry.list().some((value) => value.legacy)) throw extensionUpgradeRequired();
3760
+ return {
3761
+ content: [{
3762
+ type: "text",
3763
+ text: JSON.stringify(result)
3764
+ }],
3765
+ structuredContent: result
3766
+ };
3767
+ }
3768
+ };
3769
+ case "resume_design": return {
3770
+ ...tool,
3771
+ handler: handleResumeDesign
3772
+ };
3773
+ case "begin_design": return {
3774
+ ...tool,
3775
+ handler: handleBeginDesign
3776
+ };
3777
+ case "end_design": return {
3778
+ ...tool,
3779
+ handler: handleEndDesign
3780
+ };
1958
3781
  case "get_assets": return {
1959
3782
  ...tool,
1960
3783
  handler: handleGetAssets
1961
3784
  };
3785
+ case "upload_asset": return {
3786
+ ...tool,
3787
+ handler: handleUploadAsset
3788
+ };
1962
3789
  default: throw new Error("No handler configured for hub tool.");
1963
3790
  }
1964
3791
  }
@@ -2003,7 +3830,7 @@ function scheduleAssetCleanup() {
2003
3830
  return;
2004
3831
  }
2005
3832
  pruneExpiredAssets(assetTtlMs);
2006
- const intervalMs = Math.min(assetTtlMs, 1440 * 60 * 1e3);
3833
+ const intervalMs = Math.min(assetTtlMs, 864e5);
2007
3834
  unrefTimer(setInterval(() => {
2008
3835
  pruneExpiredAssets(assetTtlMs);
2009
3836
  }, intervalMs));
@@ -2036,6 +3863,7 @@ function buildAssetDescriptor(record) {
2036
3863
  return {
2037
3864
  hash: record.hash,
2038
3865
  url: `${assetHttpServer.getBaseUrl()}/assets/${filename}`,
3866
+ localPath: record.filePath,
2039
3867
  mimeType: record.mimeType,
2040
3868
  size: record.size,
2041
3869
  width: record.metadata?.width,
@@ -2043,52 +3871,202 @@ function buildAssetDescriptor(record) {
2043
3871
  ...record.metadata?.themeable ? { themeable: true } : {}
2044
3872
  };
2045
3873
  }
2046
- function createMcpServer() {
3874
+ function publishDesignTask({ task }) {
3875
+ const message = JSON.stringify({
3876
+ type: "designTaskState",
3877
+ task
3878
+ });
3879
+ for (const extension of extensionRegistry.list()) {
3880
+ if (!extension.sessions?.sessions.some((session) => session.fileKey === task.target.fileKey)) continue;
3881
+ try {
3882
+ extension.ws.send(message);
3883
+ } catch (error) {
3884
+ log.warn({
3885
+ error,
3886
+ taskId: task.taskId
3887
+ }, "Failed to synchronize design task.");
3888
+ }
3889
+ }
3890
+ }
3891
+ function resolveDesignRoute(ownerId, taskId, active = true, explicitSessionId) {
3892
+ return resolveDesignTarget(designTasks, extensionRegistry.list(), extensionRegistry.getActiveId(), ownerId, taskId, active, explicitSessionId);
3893
+ }
3894
+ async function handleBeginDesign(args, ownerId) {
3895
+ let record = designTasks.retry(ownerId, args.requestId);
3896
+ if (record) {
3897
+ if (record.task.title !== args.title || args.sessionId && args.sessionId !== record.task.target.sessionId) throw createCodedError(TEMPAD_MCP_ERROR_CODES.DESIGN_TASK_INACTIVE, "requestId already has another title or Figma target.");
3898
+ await pendingDesignBindings.get(record.task.taskId);
3899
+ return createDesignTaskToolResponse(record.task);
3900
+ }
3901
+ const { extension, session } = resolveDesignRoute(ownerId, void 0, true, args.sessionId);
3902
+ const issues = getExtensionRuntimeIssues(extension.runtime);
3903
+ if (issues.length) throw createCodedError(TEMPAD_MCP_ERROR_CODES.RUNTIME_IDENTITY_MISMATCH, issues.join("; "));
3904
+ const { client, capabilities } = await agentClients.describe(ownerId);
3905
+ record = designTasks.begin(ownerId, extension.id, session, args.title, args.requestId, client, capabilities, extension.sessions ? {
3906
+ browserId: extension.sessions.browserId,
3907
+ origin: extension.origin
3908
+ } : void 0);
3909
+ const task = record.task;
3910
+ const binding = bindDesignTask(record, extension, session);
3911
+ pendingDesignBindings.set(task.taskId, binding);
3912
+ try {
3913
+ await binding;
3914
+ return createDesignTaskToolResponse(task);
3915
+ } finally {
3916
+ if (pendingDesignBindings.get(task.taskId) === binding) pendingDesignBindings.delete(task.taskId);
3917
+ }
3918
+ }
3919
+ async function bindDesignTask({ task, ownerId }, extension, session) {
3920
+ const epoch = task.epoch ?? 0;
3921
+ const registration = register(extension.id, toolTimeoutMs);
3922
+ try {
3923
+ const message = {
3924
+ type: "toolCall",
3925
+ id: registration.requestId,
3926
+ route: {
3927
+ gatewayId: extension.id,
3928
+ sessionId: session.sessionId,
3929
+ fileKey: session.fileKey
3930
+ },
3931
+ payload: {
3932
+ name: "__begin_design",
3933
+ args: task
3934
+ }
3935
+ };
3936
+ extension.ws.send(JSON.stringify(message));
3937
+ const bound = DesignTaskSchema.parse(await registration.promise);
3938
+ if (bound.taskId !== task.taskId || bound.target.sessionId !== session.sessionId || bound.target.fileKey !== session.fileKey || bound.target.pageId !== task.target.pageId || (bound.epoch ?? 0) !== epoch) throw createCodedError(TEMPAD_MCP_ERROR_CODES.DESIGN_TARGET_CHANGED, "The page acknowledged a different design target.");
3939
+ designTasks.assertEpoch(task.taskId, ownerId, epoch);
3940
+ designTasks.confirm(task.taskId, ownerId);
3941
+ } catch (error) {
3942
+ reject(registration.requestId, extension.id, coerceToolError(error));
3943
+ await registration.promise.catch(() => void 0);
3944
+ if ((task.epoch ?? 0) === epoch && task.target.sessionId === session.sessionId) designTasks.stop(task.taskId, "interrupted");
3945
+ throw error;
3946
+ }
3947
+ }
3948
+ async function handleResumeDesign(args, ownerId) {
3949
+ const { extension, session } = resolveDesignRoute(ownerId, args.taskId, false);
3950
+ const { client, capabilities } = await agentClients.describe(ownerId);
3951
+ designTasks.attachClient(ownerId, client, capabilities);
3952
+ const record = designTasks.resume(args.taskId, ownerId, args.epoch, session);
3953
+ record.extensionId = extension.id;
3954
+ if (!record.ready) await (pendingDesignBindings.get(args.taskId) ?? bindDesignTask(record, extension, session));
3955
+ return createDesignTaskToolResponse(record.task);
3956
+ }
3957
+ async function handleEndDesign(args, ownerId) {
3958
+ const record = designTasks.assertEpoch(args.taskId, ownerId, args.taskEpoch);
3959
+ if (args.outcome === "completed" && record.task.operation) throw createCodedError(TEMPAD_MCP_ERROR_CODES.DESIGN_TASK_BUSY, "Wait for the running operation before completing the design task.");
3960
+ if (args.outcome === "cancelled") agentClients.cancelFeedback(args.taskId, true).catch(() => {});
3961
+ designTasks.snapshotResult(args.taskId, args.summary);
3962
+ designTasks.stop(args.taskId, args.outcome);
3963
+ return createDesignTaskToolResponse(record.task);
3964
+ }
3965
+ function createMcpServer(ownerId) {
2047
3966
  const mcp = new McpServer({
2048
3967
  name: "tempad-dev",
2049
3968
  title: "TemPad Dev",
2050
3969
  version: PACKAGE_VERSION
2051
3970
  }, { instructions: instructions_default });
3971
+ mcp.server.setNotificationHandler(ClientEventSchema, (notification) => agentClients.event(ownerId, notification));
3972
+ mcp.server.setRequestHandler(ClientHookRequestSchema, (request) => agentClients.clientHook(request.params));
2052
3973
  const registered = [];
2053
3974
  for (const tool of TOOL_DEFINITIONS) {
2054
3975
  if ("exposed" in tool && tool.exposed === false) continue;
2055
- registerTool(mcp, tool);
3976
+ registerTool(mcp, tool, ownerId);
2056
3977
  registered.push(tool.name);
2057
3978
  }
2058
3979
  log.info({ tools: registered }, "Registered tools.");
2059
3980
  return mcp;
2060
3981
  }
2061
- function registerTool(mcp, tool) {
2062
- if (tool.target === "extension") registerProxiedTool(mcp, tool);
2063
- else registerLocalTool(mcp, tool);
3982
+ function registerTool(mcp, tool, ownerId) {
3983
+ if (tool.target === "extension") registerProxiedTool(mcp, tool, ownerId);
3984
+ else registerLocalTool(mcp, tool, ownerId);
2064
3985
  }
2065
- function registerProxiedTool(mcp, tool) {
3986
+ function registerProxiedTool(mcp, tool, ownerId) {
2066
3987
  const registerToolFn = mcp.registerTool.bind(mcp);
2067
3988
  const schema = tool.parameters;
2068
- const handler = async (args) => {
3989
+ const connectionId = ownerId;
3990
+ const handler = async (args, extra) => {
3991
+ const ownerId = await agentClients.owner(connectionId, extra._meta, mcp.server.getClientVersion());
2069
3992
  let requestId;
2070
3993
  try {
2071
- const parsedArgs = schema.parse(args);
2072
- const activeExt = extensionRegistry.getActive();
2073
- if (!activeExt) throw createCodedError(TEMPAD_MCP_ERROR_CODES.NO_ACTIVE_EXTENSION, "No active TemPad Dev extension available.");
2074
- const registration = register(activeExt.id, toolTimeoutMs);
3994
+ const parsed = schema.parse(args);
3995
+ const { taskId, taskEpoch, ...parsedArgs } = parsed;
3996
+ const readSessionId = EXACT_SESSION_READ_TOOLS.has(tool.name) ? getRecordProperty(parsedArgs, "sessionId") : void 0;
3997
+ const explicitSessionId = typeof readSessionId === "string" ? readSessionId : void 0;
3998
+ if (explicitSessionId) delete parsedArgs.sessionId;
3999
+ if (taskId) designTasks.assertEpoch(taskId, ownerId, taskEpoch);
4000
+ let timeoutMs = toolTimeoutMs;
4001
+ if (tool.name === "get_code") timeoutMs = getCodeTimeoutMs;
4002
+ else if (tool.name === "get_design_system" && getRecordProperty(parsedArgs, "scope") !== "fonts" && getRecordProperty(parsedArgs, "scope") !== "pages" && !getRecordProperty(parsedArgs, "catalogId")) timeoutMs = getDesignSystemTimeoutMs;
4003
+ else if (tool.name === "get_structure" && (getRecordProperty(parsedArgs, "pageId") || getRecordProperty(parsedArgs, "pageKey"))) timeoutMs = pageStructureTimeoutMs;
4004
+ else if (tool.name === "apply_canvas") timeoutMs = applyCanvasTimeoutMs;
4005
+ const legacy = !taskId && !explicitSessionId ? extensionRegistry.getActive() : void 0;
4006
+ if (legacy?.legacy) {
4007
+ const payload = legacyToolPayload(tool.name, parsed);
4008
+ const registration = register(legacy.id, timeoutMs);
4009
+ requestId = registration.requestId;
4010
+ try {
4011
+ legacy.ws.send(JSON.stringify({
4012
+ type: "toolCall",
4013
+ id: requestId,
4014
+ payload
4015
+ }));
4016
+ } catch (error) {
4017
+ reject(requestId, legacy.id, coerceToolError(error));
4018
+ }
4019
+ return createToolResponse(tool.name, await registration.promise);
4020
+ }
4021
+ const { extension: activeExt, session } = resolveDesignRoute(ownerId, taskId, true, explicitSessionId);
4022
+ const runtimeIssues = getExtensionRuntimeIssues(activeExt.runtime);
4023
+ if (runtimeIssues.length) throw createCodedError(TEMPAD_MCP_ERROR_CODES.RUNTIME_IDENTITY_MISMATCH, `${runtimeIssues.join("; ")}. Rebuild/reload the extension and start a fresh agent task.`);
4024
+ const runtime = tool.name === "apply_canvas" ? buildAuthoringRuntimeEvidence(activeExt) : void 0;
4025
+ 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.");
4026
+ designTasks.checkOperation(ownerId, session, taskId, tool.name === "apply_canvas");
4027
+ const registration = register(activeExt.id, timeoutMs, { waitForDefinitiveResult: tool.name === "apply_canvas" });
2075
4028
  requestId = registration.requestId;
2076
4029
  const message = {
2077
4030
  type: "toolCall",
2078
4031
  id: registration.requestId,
4032
+ route: {
4033
+ gatewayId: activeExt.id,
4034
+ sessionId: session.sessionId,
4035
+ fileKey: session.fileKey,
4036
+ ...taskId ? {
4037
+ taskId,
4038
+ epoch: taskEpoch ?? 0
4039
+ } : {}
4040
+ },
2079
4041
  payload: {
2080
4042
  name: tool.name,
2081
4043
  args: parsedArgs
2082
4044
  }
2083
4045
  };
2084
- activeExt.ws.send(JSON.stringify(message));
4046
+ try {
4047
+ designTasks.startOperation(requestId, ownerId, activeExt.id, activeExt.sessions.browserId, session, taskId, tool.name === "apply_canvas");
4048
+ activeExt.ws.send(JSON.stringify(message));
4049
+ } catch (error) {
4050
+ designTasks.finishOperation(requestId, activeExt.id);
4051
+ reject(requestId, activeExt.id, coerceToolError(error));
4052
+ }
2085
4053
  log.info({
2086
4054
  tool: tool.name,
2087
4055
  req: registration.requestId,
2088
4056
  extId: activeExt.id
2089
4057
  }, "Forwarded tool call.");
2090
4058
  const payload = await registration.promise;
2091
- return createToolResponse(tool.name, payload);
4059
+ if (taskId && ["get_structure", "get_code"].includes(tool.name)) designTasks.acknowledgeRead(taskId, ownerId, taskEpoch);
4060
+ if (taskId && tool.name === "apply_canvas") {
4061
+ const rootNodeId = getRecordProperty(payload, "rootNodeId");
4062
+ if (typeof rootNodeId === "string") designTasks.captureResult(taskId, rootNodeId, getRecordProperty(payload, "rootRemoved") === true);
4063
+ const page = getRecordProperty(payload, "page");
4064
+ if (getRecordProperty(page, "active") === true) {
4065
+ const pageId = getRecordProperty(page, "id");
4066
+ if (typeof pageId === "string") designTasks.updatePage(taskId, pageId);
4067
+ }
4068
+ }
4069
+ return createToolResponse(tool.name, payload, runtime);
2092
4070
  } catch (error) {
2093
4071
  const normalized = coerceToolError(error);
2094
4072
  log.error({
@@ -2101,23 +4079,36 @@ function registerProxiedTool(mcp, tool) {
2101
4079
  }
2102
4080
  };
2103
4081
  registerToolFn(tool.name, {
4082
+ annotations: tool.annotations,
2104
4083
  description: tool.description,
2105
4084
  inputSchema: schema
2106
4085
  }, handler);
2107
4086
  }
2108
- function registerLocalTool(mcp, tool) {
4087
+ function registerLocalTool(mcp, tool, ownerId) {
2109
4088
  const schema = tool.parameters;
2110
4089
  const handler = tool.handler;
2111
4090
  const registerToolFn = mcp.registerTool.bind(mcp);
2112
4091
  const registrationOptions = {
4092
+ annotations: tool.annotations,
2113
4093
  description: tool.description,
2114
4094
  inputSchema: schema
2115
4095
  };
2116
4096
  if (tool.outputSchema) registrationOptions.outputSchema = tool.outputSchema;
2117
- const registerHandler = async (args) => {
4097
+ const connectionId = ownerId;
4098
+ const registerHandler = async (args, extra) => {
4099
+ const ownerId = await agentClients.owner(connectionId, extra._meta, mcp.server.getClientVersion());
2118
4100
  try {
2119
4101
  const parsed = schema.parse(args);
2120
- return await handler(parsed);
4102
+ const taskId = getRecordProperty(parsed, "taskId");
4103
+ if (![
4104
+ "end_design",
4105
+ "resume_design",
4106
+ "get_design_task"
4107
+ ].includes(tool.name) && typeof taskId === "string") {
4108
+ designTasks.assertEpoch(taskId, ownerId, getRecordProperty(parsed, "taskEpoch"));
4109
+ designTasks.touch(taskId, ownerId);
4110
+ }
4111
+ return await handler(parsed, ownerId);
2121
4112
  } catch (error) {
2122
4113
  log.error({
2123
4114
  tool: tool.name,
@@ -2128,23 +4119,44 @@ function registerLocalTool(mcp, tool) {
2128
4119
  };
2129
4120
  registerToolFn(tool.name, registrationOptions, registerHandler);
2130
4121
  }
2131
- function createToolResponse(toolName, payload) {
2132
- const rawResult = (() => {
2133
- const definition = getToolDefinition(toolName);
2134
- if (definition && hasFormatter(definition)) try {
2135
- const formatter = definition.format;
2136
- return formatter(payload);
2137
- } catch (error) {
2138
- log.warn({
2139
- tool: toolName,
2140
- error
2141
- }, "Failed to format tool result; returning raw payload.");
2142
- return coercePayloadToToolResponse(payload);
4122
+ function createToolResponse(toolName, payload, runtime, includeLocalAssetPaths = true) {
4123
+ const enrichedPayload = (() => {
4124
+ if (toolName === "get_screenshot" && includeLocalAssetPaths) {
4125
+ const screenshot = payload;
4126
+ return {
4127
+ ...screenshot,
4128
+ asset: addLocalAssetPath(screenshot.asset)
4129
+ };
4130
+ }
4131
+ if (toolName === "get_code" && includeLocalAssetPaths) {
4132
+ const code = payload;
4133
+ return code.assets ? {
4134
+ ...code,
4135
+ assets: code.assets.map((asset) => addLocalAssetPath(asset))
4136
+ } : code;
2143
4137
  }
2144
- return coercePayloadToToolResponse(payload);
4138
+ if (toolName === "apply_canvas" && runtime) return {
4139
+ ...payload,
4140
+ runtime
4141
+ };
4142
+ return payload;
2145
4143
  })();
4144
+ let rawResult;
4145
+ const definition = getToolDefinition(toolName);
4146
+ if (definition && hasFormatter(definition)) try {
4147
+ const formatter = definition.format;
4148
+ rawResult = formatter(enrichedPayload);
4149
+ } catch (error) {
4150
+ log.warn({
4151
+ tool: toolName,
4152
+ error
4153
+ }, "Failed to format tool result; returning raw payload.");
4154
+ rawResult = coercePayloadToToolResponse(enrichedPayload);
4155
+ }
4156
+ else rawResult = coercePayloadToToolResponse(enrichedPayload);
2146
4157
  const resultBytes = measureCallToolResultBytes(rawResult);
2147
4158
  if (resultBytes > 65536) {
4159
+ if (includeLocalAssetPaths && (toolName === "get_code" || toolName === "get_screenshot")) return createToolResponse(toolName, payload, runtime, false);
2148
4160
  log.warn({
2149
4161
  tool: toolName,
2150
4162
  resultBytes,
@@ -2154,6 +4166,34 @@ function createToolResponse(toolName, payload) {
2154
4166
  }
2155
4167
  return rawResult;
2156
4168
  }
4169
+ function buildAuthoringRuntimeEvidence(extension) {
4170
+ const runtime = extension.runtime;
4171
+ const issues = getExtensionRuntimeIssues(runtime);
4172
+ if (!hubRuntimeIdentity) issues.unshift("Hub runtime identity is unavailable");
4173
+ return {
4174
+ protocolVersion: 13,
4175
+ locked: false,
4176
+ valid: issues.length === 0,
4177
+ issues,
4178
+ hub: {
4179
+ packageVersion: hubRuntimeIdentity?.packageVersion ?? PACKAGE_VERSION,
4180
+ runtimeFingerprint: hubRuntimeIdentity?.runtimeFingerprint ?? "0".repeat(64),
4181
+ startedAt: hubRuntimeIdentity?.startedAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
4182
+ },
4183
+ extension: {
4184
+ version: runtime?.version ?? "<missing>",
4185
+ runtimeFingerprint: runtime?.fingerprint ?? "0".repeat(64),
4186
+ connectedAt: extension.connectedAt
4187
+ }
4188
+ };
4189
+ }
4190
+ function addLocalAssetPath(asset) {
4191
+ const record = assetStore.get(asset.hash);
4192
+ return record && existsSync(record.filePath) ? {
4193
+ ...asset,
4194
+ localPath: record.filePath
4195
+ } : asset;
4196
+ }
2157
4197
  async function handleGetAssets({ hashes }) {
2158
4198
  if (hashes.length > 100) throw new Error("Too many hashes requested. Limit is 100.");
2159
4199
  const unique = Array.from(new Set(hashes));
@@ -2168,6 +4208,27 @@ async function handleGetAssets({ hashes }) {
2168
4208
  missing: unique.filter((hash) => !found.has(hash))
2169
4209
  }));
2170
4210
  }
4211
+ async function handleUploadAsset({ dataUrl }) {
4212
+ const decoded = decodeImageDataUrl(dataUrl, maxAssetSizeBytes);
4213
+ const filename = buildAssetFilename(decoded.hash, decoded.mimeType);
4214
+ const response = await fetch(`${assetHttpServer.getBaseUrl()}/assets/${filename}`, {
4215
+ method: "POST",
4216
+ headers: {
4217
+ "Content-Length": String(decoded.bytes.length),
4218
+ "Content-Type": decoded.mimeType
4219
+ },
4220
+ body: new Uint8Array(decoded.bytes)
4221
+ });
4222
+ if (!response.ok) {
4223
+ const detail = (await response.text()).slice(0, 500);
4224
+ throw new Error(`Hub asset import failed (${response.status}): ${detail}`);
4225
+ }
4226
+ return createUploadAssetToolResponse({
4227
+ assetHash: decoded.hash,
4228
+ mimeType: decoded.mimeType,
4229
+ size: decoded.bytes.length
4230
+ });
4231
+ }
2171
4232
  function unrefTimer(timer) {
2172
4233
  if (typeof timer === "object" && timer !== null) {
2173
4234
  const handle = timer;
@@ -2175,21 +4236,41 @@ function unrefTimer(timer) {
2175
4236
  }
2176
4237
  }
2177
4238
  function broadcastState() {
4239
+ publishHubRuntimeIdentity();
2178
4240
  const activeId = extensionRegistry.getActiveId();
2179
- const message = {
2180
- type: "state",
2181
- activeId,
2182
- assetServerUrl: assetHttpServer.getBaseUrl()
2183
- };
2184
- extensionRegistry.list().forEach((ext) => ext.ws.send(JSON.stringify(message)));
4241
+ for (const extension of extensionRegistry.list()) {
4242
+ const message = {
4243
+ type: "state",
4244
+ activeId,
4245
+ assetServerUrl: assetHttpServer.getBaseUrl(extension.legacy)
4246
+ };
4247
+ extension.ws.send(JSON.stringify(message));
4248
+ }
2185
4249
  log.debug({
2186
4250
  activeId,
2187
4251
  count: extensionRegistry.size
2188
4252
  }, "Broadcasted state.");
2189
4253
  }
4254
+ function publishHubRuntimeIdentity() {
4255
+ if (!hubRuntimeIdentity) return;
4256
+ const activeExtension = extensionRegistry.getActive();
4257
+ hubRuntimeIdentity = {
4258
+ ...hubRuntimeIdentity,
4259
+ activeExtension: activeExtension ? {
4260
+ id: activeExtension.id,
4261
+ connectedAt: activeExtension.connectedAt,
4262
+ version: activeExtension.runtime?.version ?? null,
4263
+ fingerprint: activeExtension.runtime?.fingerprint ?? null
4264
+ } : null
4265
+ };
4266
+ writeHubRuntimeIdentity(HUB_RUNTIME_IDENTITY_PATH, hubRuntimeIdentity);
4267
+ }
2190
4268
  function shutdown() {
2191
4269
  if (shuttingDown) return;
2192
4270
  shuttingDown = true;
4271
+ clearInterval(designTaskTimer);
4272
+ clearInterval(clientCapabilityTimer);
4273
+ agentClients.close();
2193
4274
  log.info("Hub is shutting down...");
2194
4275
  consumerSessions.forEach((session) => {
2195
4276
  session.close().catch((err) => {
@@ -2203,6 +4284,7 @@ function shutdown() {
2203
4284
  netServer.close(() => log.info("Net server closed."));
2204
4285
  wss?.close(() => log.info("WebSocket server closed."));
2205
4286
  cleanupAll();
4287
+ removeHubRuntimeIdentityIfOwned(HUB_RUNTIME_IDENTITY_PATH, process.pid);
2206
4288
  releaseHubLockIfNeeded();
2207
4289
  unrefTimer(setTimeout(() => {
2208
4290
  log.warn("Shutdown timed out. Forcing exit.");
@@ -2210,7 +4292,8 @@ function shutdown() {
2210
4292
  }, SHUTDOWN_TIMEOUT));
2211
4293
  }
2212
4294
  const netServer = createServer((sock) => {
2213
- const mcp = createMcpServer();
4295
+ const ownerId = randomUUID();
4296
+ const mcp = createMcpServer(ownerId);
2214
4297
  consumerSessions.add(mcp);
2215
4298
  consumerCount++;
2216
4299
  log.info(`Consumer connected. Total: ${consumerCount}`);
@@ -2227,6 +4310,7 @@ const netServer = createServer((sock) => {
2227
4310
  transport.close().catch((closeErr) => log.warn({ err: closeErr }, "Transport close failed."));
2228
4311
  });
2229
4312
  sock.on("close", async () => {
4313
+ agentClients.disconnect(ownerId);
2230
4314
  await transport.close().catch((closeErr) => log.warn({ err: closeErr }, "Transport close failed."));
2231
4315
  await mcp.close().catch((closeErr) => log.warn({ err: closeErr }, "MCP session close failed."));
2232
4316
  consumerSessions.delete(mcp);
@@ -2242,7 +4326,10 @@ async function initializeHubRuntime() {
2242
4326
  ensureDir(RUNTIME_DIR);
2243
4327
  if (await probeSocketPath() === "live") await exitExistingHub();
2244
4328
  releaseHubLock = await acquireHubLock();
4329
+ designTasks.restore();
2245
4330
  await cleanSocketPath();
4331
+ hubRuntimeIdentity = createHubRuntimeIdentity(fileURLToPath(import.meta.url), PACKAGE_VERSION);
4332
+ writeHubRuntimeIdentity(HUB_RUNTIME_IDENTITY_PATH, hubRuntimeIdentity);
2246
4333
  await assetHttpServer.start();
2247
4334
  scheduleAssetCleanup();
2248
4335
  }
@@ -2308,6 +4395,7 @@ async function startHubRuntime() {
2308
4395
  async function abortStartup(error) {
2309
4396
  log.error({ err: error }, "Failed to initialize Hub runtime.");
2310
4397
  assetHttpServer.stop();
4398
+ removeHubRuntimeIdentityIfOwned(HUB_RUNTIME_IDENTITY_PATH, process.pid);
2311
4399
  await releaseHubLockIfNeeded();
2312
4400
  process.exit(1);
2313
4401
  }
@@ -2338,6 +4426,7 @@ activeWss.on("connection", (ws, request) => {
2338
4426
  },
2339
4427
  onDisconnected: (extensionId, wasActive) => {
2340
4428
  log.info({ id: extensionId }, `Extension disconnected. Remaining: ${extensionRegistry.size}`);
4429
+ designTasks.disconnectExtension(extensionId);
2341
4430
  cleanupForExtension(extensionId);
2342
4431
  if (wasActive) log.warn({ id: extensionId }, "Active extension disconnected.");
2343
4432
  },
@@ -2352,6 +4441,76 @@ activeWss.on("connection", (ws, request) => {
2352
4441
  extId: warning.extensionId
2353
4442
  }, "Invalid message shape.");
2354
4443
  },
4444
+ onRuntimeHello: (extension) => {
4445
+ publishHubRuntimeIdentity();
4446
+ log.info({
4447
+ extId: extension.id,
4448
+ extensionVersion: extension.runtime?.version,
4449
+ extensionRuntimeFingerprint: extension.runtime?.fingerprint
4450
+ }, "Extension runtime identity received.");
4451
+ },
4452
+ onSessions: (extension) => {
4453
+ const snapshot = extension.sessions;
4454
+ for (const review of snapshot.reviews ?? []) {
4455
+ const session = snapshot.sessions.find((value) => value.sessionId === review.sessionId);
4456
+ if (!session) continue;
4457
+ designTasks.restoreReview(review.task, extension, session);
4458
+ if (review.task.reviewClosed || review.task.status === "cancelled") agentClients.cancelFeedback(review.task.taskId, true).catch(() => {});
4459
+ }
4460
+ designTasks.reconcileSessions(snapshot.browserId, snapshot.sessions, snapshot.openTabIds);
4461
+ for (const record of designTasks.list()) {
4462
+ if (designTasks.current(record.task.target.fileKey) === record && snapshot.sessions.some((session) => session.fileKey === record.task.target.fileKey)) extension.ws.send(JSON.stringify({
4463
+ type: "designTaskState",
4464
+ task: record.task
4465
+ }));
4466
+ if (record.extensionId === extension.id && !snapshot.sessions.some((session) => session.sessionId === record.task.target.sessionId)) designTasks.stop(record.task.taskId, "interrupted");
4467
+ }
4468
+ for (const { record, extension: target, session } of designTasks.recoverSessions(extensionRegistry.list())) {
4469
+ const taskId = record.task.taskId;
4470
+ const binding = bindDesignTask(record, target, session);
4471
+ pendingDesignBindings.set(taskId, binding);
4472
+ binding.catch((error) => log.warn({
4473
+ error,
4474
+ taskId
4475
+ }, "Failed to restore a refreshed Figma tab.")).finally(() => {
4476
+ if (pendingDesignBindings.get(taskId) === binding) pendingDesignBindings.delete(taskId);
4477
+ });
4478
+ }
4479
+ },
4480
+ onDesignAction: (extension, sessionId, action) => {
4481
+ const session = extension.sessions?.sessions.find((value) => value.sessionId === sessionId);
4482
+ const record = designTasks.find(action.taskId);
4483
+ const reply = (result) => {
4484
+ try {
4485
+ extension.ws.send(JSON.stringify({
4486
+ type: "designActionResult",
4487
+ sessionId,
4488
+ result
4489
+ }));
4490
+ } catch {}
4491
+ };
4492
+ if (!session || record?.task.target.fileKey !== session.fileKey || ["feedback", "steer"].includes(action.action) && record.task.target.sessionId !== sessionId) {
4493
+ reply({
4494
+ requestId: action.requestId,
4495
+ taskId: action.taskId,
4496
+ status: "failed",
4497
+ message: "This action belongs to another Figma file."
4498
+ });
4499
+ return;
4500
+ }
4501
+ const accepted = () => reply({
4502
+ requestId: action.requestId,
4503
+ taskId: action.taskId,
4504
+ status: "accepted",
4505
+ message: action.action === "stop" ? "Stopping design task…" : "Sending feedback…"
4506
+ });
4507
+ agentClients.action(action, accepted).then(reply).catch((error) => reply({
4508
+ requestId: action.requestId,
4509
+ taskId: action.taskId,
4510
+ status: "failed",
4511
+ message: String(error).slice(0, 500)
4512
+ }));
4513
+ },
2355
4514
  onSocketError: (extensionId, error) => {
2356
4515
  log.warn({
2357
4516
  err: error,
@@ -2360,6 +4519,8 @@ activeWss.on("connection", (ws, request) => {
2360
4519
  },
2361
4520
  onStateChange: broadcastState,
2362
4521
  onToolError: (requestId, extensionId, error) => {
4522
+ if (error.code === TEMPAD_MCP_ERROR_CODES.EXTENSION_DISCONNECTED) designTasks.uncertain(requestId, extensionId);
4523
+ else designTasks.finishOperation(requestId, extensionId);
2363
4524
  const normalized = coerceToolError(error);
2364
4525
  log.warn({
2365
4526
  toolReq: requestId,
@@ -2370,7 +4531,8 @@ activeWss.on("connection", (ws, request) => {
2370
4531
  reject(requestId, extensionId, normalized);
2371
4532
  },
2372
4533
  onToolResult: (requestId, extensionId, payload) => {
2373
- resolve(requestId, extensionId, payload);
4534
+ designTasks.finishOperation(requestId, extensionId);
4535
+ resolve$1(requestId, extensionId, payload);
2374
4536
  }
2375
4537
  });
2376
4538
  });