@tempad-dev/mcp 0.8.0-alpha.0 → 0.8.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 TEMPAD_MCP_BRIDGE_SUBPROTOCOL, 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_PAYLOAD_BYTES, H as MCP_GET_CODE_TIMEOUT_MS, I as LegacyToolCallPayloadSchema, J as MCP_TOOL_TIMEOUT_MS, K as MCP_PORT_CANDIDATES, M as GetScreenshotParametersSchema, N as GetStructureParametersSchema, O as GetAssetsResultSchema, P as GetTokenDefsParametersSchema, Q as SetDesignAnchorParametersSchema, R as MCP_APPLY_CANVAS_TIMEOUT_MS, S as DesignAnchorSchema, T as EndDesignParametersSchema, U as MCP_MAX_ASSET_BYTES, W as MCP_MAX_ASSET_STORE_BYTES, X as RESUMABLE_DESIGN_TASK_STATUSES, Y as MessageFromExtensionSchema, Z as ResumeDesignParametersSchema, a as HUB_RUNTIME_IDENTITY_PATH, at as buildGetAssetsToolResult, b as ApplyCanvasResultSchema, c as RUNTIME_DIR, ct as buildGetScreenshotToolResult, d as ensureFile, dt as buildUploadAssetToolResult, et as TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS, f as getRecordProperty, ft as formatDesignFeedback, g as clientDescriptor, h as bindRequestMetadata, i as HUB_LOCK_UPDATE_MS, it as buildApplyCanvasToolResult, j as GetDesignSystemResultSchema, k as GetCodeParametersSchema, l as SOCK_PATH, lt as buildGetStructureToolResult, m as ClientEventSchema, mt as utf8Bytes, n as HUB_LOCK_PATH, nt as UploadAssetParametersSchema, ot as buildGetCodeToolResult, p as log, pt as measureCallToolResultBytes, q as MCP_TOOL_INLINE_BUDGET_BYTES, r as HUB_LOCK_STALE_MS, rt as UploadAssetResultSchema, s as PACKAGE_VERSION, st as buildGetDesignSystemToolResult, t as ASSET_DIR, tt as TEMPAD_MCP_ERROR_CODES, u as ensureDir, ut as buildGetTokenDefsToolResult, v as AGENT_CLIENTS, w as DesignTaskSchema, x as BeginDesignParametersSchema, y as ApplyCanvasParametersSchema, z as MCP_ASSET_TTL_MS } from "./shared--YD93aQ6.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 > 256 * 1024 * 1024) {
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() + 5 * 6e4;
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
+ }
910
+ }
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
+ }
668
919
  }
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
- ]
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;
@@ -759,8 +1806,8 @@ function parseNonNegativeInt(envValue, fallback) {
759
1806
  const parsed = envValue ? Number.parseInt(envValue, 10) : NaN;
760
1807
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
761
1808
  }
762
- function resolveToolTimeoutMs() {
763
- return parsePositiveInt(process.env.TEMPAD_MCP_TOOL_TIMEOUT, MCP_TOOL_TIMEOUT_MS);
1809
+ function resolveToolTimeoutMs(specializedValue, fallback = MCP_TOOL_TIMEOUT_MS) {
1810
+ return parsePositiveInt(specializedValue, parsePositiveInt(process.env.TEMPAD_MCP_TOOL_TIMEOUT, fallback));
764
1811
  }
765
1812
  function resolveAutoActivateGraceMs() {
766
1813
  return parsePositiveInt(process.env.TEMPAD_MCP_AUTO_ACTIVATE_GRACE, MCP_AUTO_ACTIVATE_GRACE_MS);
@@ -784,6 +1831,8 @@ function getMcpServerConfig() {
784
1831
  return {
785
1832
  wsPortCandidates: [...MCP_PORT_CANDIDATES],
786
1833
  toolTimeoutMs: resolveToolTimeoutMs(),
1834
+ getCodeTimeoutMs: resolveToolTimeoutMs(process.env.TEMPAD_MCP_GET_CODE_TIMEOUT, MCP_GET_CODE_TIMEOUT_MS),
1835
+ applyCanvasTimeoutMs: resolveToolTimeoutMs(process.env.TEMPAD_MCP_APPLY_CANVAS_TIMEOUT, MCP_APPLY_CANVAS_TIMEOUT_MS),
787
1836
  maxPayloadBytes: MCP_MAX_PAYLOAD_BYTES,
788
1837
  autoActivateGraceMs: resolveAutoActivateGraceMs(),
789
1838
  maxAssetSizeBytes: resolveMaxAssetSizeBytes(),
@@ -838,7 +1887,6 @@ function isChromeExtensionOrigin(origin) {
838
1887
  //#endregion
839
1888
  //#region src/asset-http-server.ts
840
1889
  const LOOPBACK_HOST = "127.0.0.1";
841
- const HASH_HEX_PATTERN = new RegExp(`^[a-f0-9]{8}$`, "i");
842
1890
  const ASSET_REQUEST_TIMEOUT_MS = 15e3;
843
1891
  const ASSET_HEADERS_TIMEOUT_MS = 5e3;
844
1892
  const ASSET_KEEP_ALIVE_TIMEOUT_MS = 5e3;
@@ -848,6 +1896,7 @@ const ASSET_MAX_CONCURRENT_DOWNLOADS = 128;
848
1896
  function createAssetHttpServer(store, options = {}) {
849
1897
  const config = getMcpServerConfig();
850
1898
  const accessToken = options.accessToken ?? createCapabilityToken();
1899
+ const legacyAccessToken = createCapabilityToken();
851
1900
  const maxAssetSizeBytes = options.maxAssetSizeBytes ?? config.maxAssetSizeBytes;
852
1901
  const maxAssetStoreBytes = options.maxAssetStoreBytes ?? config.maxAssetStoreBytes;
853
1902
  const maxConcurrentUploads = options.maxConcurrentUploads ?? config.maxConcurrentAssetUploads;
@@ -888,9 +1937,9 @@ function createAssetHttpServer(store, options = {}) {
888
1937
  server.close();
889
1938
  port = null;
890
1939
  }
891
- function getBaseUrl() {
1940
+ function getBaseUrl(legacy = false) {
892
1941
  if (port === null) throw new Error("Asset HTTP server is not running.");
893
- return `http://${LOOPBACK_HOST}:${port}/${accessToken}`;
1942
+ return `http://${LOOPBACK_HOST}:${port}/${legacy ? legacyAccessToken : accessToken}`;
894
1943
  }
895
1944
  function handleRequest(req, res) {
896
1945
  const startedAt = Date.now();
@@ -907,7 +1956,8 @@ function createAssetHttpServer(store, options = {}) {
907
1956
  return;
908
1957
  }
909
1958
  const segments = new URL$1(req.url, getBaseUrl()).pathname.split("/").filter(Boolean);
910
- if (segments.length !== 3 || !secretsEqual(segments[0] ?? "", accessToken) || segments[1] !== "assets") {
1959
+ const legacy = secretsEqual(segments[0] ?? "", legacyAccessToken);
1960
+ if (segments.length !== 3 || !legacy && !secretsEqual(segments[0] ?? "", accessToken) || segments[1] !== "assets") {
911
1961
  sendError(res, 404, "Not Found");
912
1962
  return;
913
1963
  }
@@ -934,6 +1984,10 @@ function createAssetHttpServer(store, options = {}) {
934
1984
  return;
935
1985
  }
936
1986
  if (req.method === "POST") {
1987
+ if (!legacy && hash.length !== 64) {
1988
+ sendError(res, 400, "Legacy Asset Hashes Are Read-Only");
1989
+ return;
1990
+ }
937
1991
  handleUpload(req, res, hash);
938
1992
  return;
939
1993
  }
@@ -1004,11 +2058,6 @@ function createAssetHttpServer(store, options = {}) {
1004
2058
  stream.pipe(res);
1005
2059
  }
1006
2060
  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
2061
  const declaredSize = parseContentLength(req);
1013
2062
  if (declaredSize === "invalid") {
1014
2063
  req.resume();
@@ -1031,7 +2080,7 @@ function createAssetHttpServer(store, options = {}) {
1031
2080
  if (themeable) metadata.themeable = true;
1032
2081
  const assetMetadata = Object.keys(metadata).length ? metadata : void 0;
1033
2082
  const existing = store.get(hash);
1034
- if (existing) {
2083
+ if (existing && hash.length === 64) {
1035
2084
  let existingPath = existing.filePath;
1036
2085
  if (!existsSync(existingPath) && existsSync(filePath)) {
1037
2086
  existing.filePath = filePath;
@@ -1113,7 +2162,8 @@ function createAssetHttpServer(store, options = {}) {
1113
2162
  }
1114
2163
  return;
1115
2164
  }
1116
- if (hasher.digest("hex").slice(0, 8) !== hash) {
2165
+ const computedHash = hasher.digest("hex");
2166
+ if (computedHash.slice(0, hash.length) !== hash) {
1117
2167
  cleanup();
1118
2168
  sendError(res, 400, "Hash Mismatch");
1119
2169
  return;
@@ -1124,6 +2174,27 @@ function createAssetHttpServer(store, options = {}) {
1124
2174
  return;
1125
2175
  }
1126
2176
  try {
2177
+ if (hash.length !== 64) {
2178
+ const previous = store.get(hash);
2179
+ if (previous && existsSync(previous.filePath)) {
2180
+ const previousHash = createHash("sha256").update(readFileSync(previous.filePath)).digest("hex");
2181
+ cleanup();
2182
+ if (previousHash !== computedHash) {
2183
+ sendError(res, 409, "Legacy Asset Hash Collision; update the TemPad Dev extension");
2184
+ return;
2185
+ }
2186
+ store.upsert({
2187
+ ...previous,
2188
+ metadata: {
2189
+ ...previous.metadata,
2190
+ ...assetMetadata
2191
+ },
2192
+ lastAccess: Date.now()
2193
+ });
2194
+ sendJson(res, 200, { message: "Asset Already Exists" });
2195
+ return;
2196
+ }
2197
+ }
1127
2198
  renameSync(tmpPath, filePath);
1128
2199
  } catch (error) {
1129
2200
  log.error({
@@ -1156,7 +2227,7 @@ function createAssetHttpServer(store, options = {}) {
1156
2227
  if (!requestUrl) return requestUrl;
1157
2228
  try {
1158
2229
  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>";
2230
+ if (segments.length >= 1 && (secretsEqual(segments[0] ?? "", accessToken) || secretsEqual(segments[0] ?? "", legacyAccessToken))) segments[0] = "<capability>";
1160
2231
  return `/${segments.join("/")}`;
1161
2232
  } catch {
1162
2233
  return "<invalid>";
@@ -1286,75 +2357,569 @@ function createAssetStore(options = {}) {
1286
2357
  }, "Failed to remove asset file on delete.");
1287
2358
  }
1288
2359
  }
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;
2360
+ function reconcile() {
2361
+ let changed = false;
2362
+ for (const [hash, record] of records) if (!existsSync(record.filePath)) {
2363
+ records.delete(hash);
2364
+ changed = true;
2365
+ }
2366
+ try {
2367
+ const files = readdirSync(ASSET_DIR);
2368
+ const now = Date.now();
2369
+ for (const file of files) {
2370
+ if (file === INDEX_FILENAME) continue;
2371
+ if (file.includes(".tmp.")) {
2372
+ try {
2373
+ const filePath = join(ASSET_DIR, file);
2374
+ if (now - statSync(filePath).mtimeMs > 3600 * 1e3) {
2375
+ rmSync(filePath, { force: true });
2376
+ log.info({ file }, "Cleaned up stale temp file.");
2377
+ }
2378
+ } catch (e) {
2379
+ log.debug({
2380
+ error: e,
2381
+ file
2382
+ }, "Failed to cleanup stale temp file.");
2383
+ }
2384
+ continue;
2385
+ }
2386
+ const hash = getHashFromAssetFilename(file);
2387
+ if (!hash) continue;
2388
+ if (!records.has(hash)) {
2389
+ const filePath = join(ASSET_DIR, file);
2390
+ try {
2391
+ const stat = statSync(filePath);
2392
+ records.set(hash, {
2393
+ hash,
2394
+ filePath,
2395
+ mimeType: "application/octet-stream",
2396
+ size: stat.size,
2397
+ uploadedAt: stat.birthtimeMs,
2398
+ lastAccess: stat.atimeMs
2399
+ });
2400
+ changed = true;
2401
+ log.info({ hash }, "Recovered orphan asset file.");
2402
+ } catch (e) {
2403
+ log.warn({
2404
+ error: e,
2405
+ file
2406
+ }, "Failed to stat orphan file.");
2407
+ }
2408
+ }
2409
+ }
2410
+ } catch (error) {
2411
+ log.warn({ error }, "Failed to scan asset directory for orphans.");
2412
+ }
2413
+ if (changed) flush();
2414
+ }
2415
+ loadExisting();
2416
+ reconcile();
2417
+ return {
2418
+ list,
2419
+ has,
2420
+ get,
2421
+ getMany,
2422
+ upsert,
2423
+ touch,
2424
+ remove,
2425
+ reconcile,
2426
+ flush
2427
+ };
2428
+ }
2429
+ //#endregion
2430
+ //#region src/design-task-store.ts
2431
+ const SnapshotSchema = z.object({
2432
+ revision: z.number().int().nonnegative(),
2433
+ current: z.record(z.string(), z.string()),
2434
+ records: z.array(z.object({
2435
+ task: DesignTaskSchema,
2436
+ requestId: z.string(),
2437
+ browser: z.object({
2438
+ browserId: z.string(),
2439
+ origin: z.string(),
2440
+ tabId: z.number(),
2441
+ documentId: z.string()
2442
+ }).optional(),
2443
+ resultNodeIds: z.array(z.string()).optional()
2444
+ }))
2445
+ });
2446
+ /** One lock-owning Hub writes a small atomic snapshot; transport and leases are never restored. */
2447
+ var DesignTaskStore = class {
2448
+ path;
2449
+ constructor(path) {
2450
+ this.path = path;
2451
+ }
2452
+ load() {
2453
+ try {
2454
+ return SnapshotSchema.parse(JSON.parse(readFileSync(this.path, "utf8")));
2455
+ } catch (error) {
2456
+ if (error.code === "ENOENT") return void 0;
2457
+ throw error;
2458
+ }
2459
+ }
2460
+ save(snapshot) {
2461
+ mkdirSync(dirname(this.path), {
2462
+ recursive: true,
2463
+ mode: 448
2464
+ });
2465
+ const temporary = `${this.path}.tmp`;
2466
+ writeFileSync(temporary, JSON.stringify(snapshot), {
2467
+ mode: 384,
2468
+ flush: true
2469
+ });
2470
+ renameSync(temporary, this.path);
2471
+ }
2472
+ };
2473
+ //#endregion
2474
+ //#region src/legacy-extension.ts
2475
+ function extensionUpgradeRequired() {
2476
+ 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 });
2477
+ }
2478
+ function legacyToolPayload(name, args) {
2479
+ const result = LegacyToolCallPayloadSchema.safeParse({
2480
+ name,
2481
+ args
2482
+ });
2483
+ if (!result.success) throw extensionUpgradeRequired();
2484
+ return result.data;
2485
+ }
2486
+ //#endregion
2487
+ //#region src/design-tasks.ts
2488
+ const ENDED_STATUSES = ["completed", "cancelled"];
2489
+ const RUNNING_STATUSES = ["active", "stopping"];
2490
+ function fail(code, message) {
2491
+ throw Object.assign(new Error(message), { code });
2492
+ }
2493
+ function resolveDesignTarget(tasks, extensions, activeExtensionId, ownerId, taskId, active = true, explicitSessionId) {
2494
+ const record = taskId ? tasks.owned(taskId, ownerId, active) : void 0;
2495
+ const extension = extensions.find((value) => explicitSessionId ? 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);
2496
+ if (extension?.legacy) throw extensionUpgradeRequired();
2497
+ const sessionId = explicitSessionId ?? record?.task.target.sessionId ?? extension?.sessions?.activeSessionId;
2498
+ const session = extension?.sessions?.sessions.find((value) => value.sessionId === sessionId);
2499
+ 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." : "No active Figma session. Activate the intended file with its TemPad Dev MCP badge.");
2500
+ if (record && record.task.target.fileKey !== session.fileKey) fail("DESIGN_TARGET_CHANGED", "The task file changed.");
2501
+ const busy = extensions.some((connection) => connection.sessions?.sessions.some((value) => value.fileKey === session.fileKey && value.busy));
2502
+ return {
2503
+ extension,
2504
+ session: {
2505
+ ...session,
2506
+ busy
2507
+ }
2508
+ };
2509
+ }
2510
+ /** One Hub coordinates file leases across its connected browser sessions. */
2511
+ var DesignTasks = class {
2512
+ options;
2513
+ records = /* @__PURE__ */ new Map();
2514
+ currentTaskIds = /* @__PURE__ */ new Map();
2515
+ operations = /* @__PURE__ */ new Map();
2516
+ now;
2517
+ leaseMs;
2518
+ revision = 0;
2519
+ constructor(options) {
2520
+ this.options = options;
2521
+ this.now = options.now ?? Date.now;
2522
+ this.leaseMs = options.leaseMs ?? 3e5;
2523
+ }
2524
+ retry(ownerId, requestId) {
2525
+ this.sweep();
2526
+ return [...this.records.values()].find((record) => record.ownerId === ownerId && record.requestId === requestId);
2527
+ }
2528
+ begin(ownerId, extensionId, session, title, requestId, client, capabilities, browser) {
2529
+ const retry = this.retry(ownerId, requestId);
2530
+ if (retry) {
2531
+ if (retry.task.title !== title) fail("DESIGN_TASK_INACTIVE", "This begin requestId was already used with another title.");
2532
+ return retry;
2533
+ }
2534
+ this.assertFileIdle(session);
2535
+ const occupant = this.occupant(session.fileKey);
2536
+ if (occupant) this.busy(occupant);
2537
+ const { busy: _busy, tabId, documentId, ...target } = session;
2538
+ const record = {
2539
+ ownerId,
2540
+ extensionId,
2541
+ requestId,
2542
+ ready: false,
2543
+ ...browser && tabId !== void 0 && documentId !== void 0 ? { browser: {
2544
+ ...browser,
2545
+ tabId,
2546
+ documentId
2547
+ } } : {},
2548
+ task: {
2549
+ taskId: this.options.createId(),
2550
+ title,
2551
+ target,
2552
+ status: "active",
2553
+ epoch: 0,
2554
+ ...client ? { client } : {},
2555
+ ...capabilities ? { capabilities } : {},
2556
+ operation: null,
2557
+ expiresAt: this.now() + this.leaseMs,
2558
+ revision: 0
2559
+ }
2560
+ };
2561
+ const previousTaskId = this.currentTaskIds.get(session.fileKey);
2562
+ this.records.set(record.task.taskId, record);
2563
+ this.currentTaskIds.set(session.fileKey, record.task.taskId);
2564
+ try {
2565
+ this.publish(record);
2566
+ } catch (error) {
2567
+ this.records.delete(record.task.taskId);
2568
+ if (previousTaskId) this.currentTaskIds.set(session.fileKey, previousTaskId);
2569
+ else this.currentTaskIds.delete(session.fileKey);
2570
+ throw error;
2571
+ }
2572
+ return record;
2573
+ }
2574
+ confirm(taskId, ownerId) {
2575
+ const record = this.owned(taskId, ownerId, true);
2576
+ record.ready = true;
2577
+ return record;
2578
+ }
2579
+ owned(taskId, ownerId, active = false) {
2580
+ const record = this.find(taskId);
2581
+ if (!record) fail("DESIGN_TASK_INACTIVE", "Unknown or expired task. Begin a new design task and reread its target.");
2582
+ if (record.ownerId !== ownerId) fail("DESIGN_TASK_OWNER_MISMATCH", "This task belongs to another MCP caller. Begin your own task.");
2583
+ if (active && record.task.reviewClosed) fail("DESIGN_TASK_INACTIVE", "This review is closed. Begin a new task before writing.");
2584
+ 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."}`);
2585
+ return record;
2586
+ }
2587
+ /** Runtime identity may reconnect the same conversation, never a focused/last caller. */
2588
+ attachClient(ownerId, client, capabilities) {
2589
+ if (!client.sessionId || ["other", "unknown"].includes(client.kind)) return;
2590
+ for (const record of this.records.values()) {
2591
+ if (record.task.client?.kind !== client.kind || record.task.client.sessionId !== client.sessionId) continue;
2592
+ if (!RESUMABLE_DESIGN_TASK_STATUSES.includes(record.task.status) && record.ownerId !== ownerId) continue;
2593
+ const changed = record.ownerId !== ownerId || capabilities && !isDeepStrictEqual(record.task.capabilities, capabilities);
2594
+ record.ownerId = ownerId;
2595
+ record.task.client = client;
2596
+ if (capabilities) record.task.capabilities = capabilities;
2597
+ if (changed) this.publish(record);
2598
+ }
2599
+ }
2600
+ assertEpoch(taskId, ownerId, epoch) {
2601
+ const record = this.owned(taskId, ownerId);
2602
+ 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.");
2603
+ return record;
2604
+ }
2605
+ resume(taskId, ownerId, epoch, session) {
2606
+ const record = this.assertEpoch(taskId, ownerId, epoch);
2607
+ if (record.task.reviewClosed) fail("DESIGN_TASK_INACTIVE", "This review is closed.");
2608
+ if (record.task.status === "active") return record;
2609
+ 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.");
2610
+ if (this.current(record.task.target.fileKey) !== record) fail("DESIGN_TASK_INACTIVE", "This task was replaced by a newer task and cannot resume.");
2611
+ 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.");
2612
+ this.assertFileIdle(session);
2613
+ record.ending = void 0;
2614
+ record.ready = false;
2615
+ record.task.status = "active";
2616
+ record.task.epoch = (record.task.epoch ?? 0) + 1;
2617
+ record.task.needsRead = true;
2618
+ this.renew(record);
2619
+ return record;
2620
+ }
2621
+ acknowledgeRead(taskId, ownerId, epoch) {
2622
+ const record = this.assertEpoch(taskId, ownerId, epoch);
2623
+ if (record.task.status !== "active" || !record.task.needsRead) return;
2624
+ record.task.needsRead = false;
2625
+ this.publish(record);
2626
+ }
2627
+ find(taskId) {
2628
+ this.sweep();
2629
+ return this.records.get(taskId);
2630
+ }
2631
+ list() {
2632
+ this.sweep();
2633
+ return [...this.records.values()];
2634
+ }
2635
+ /** Only the current claim may own a lease or the file's task UI. */
2636
+ current(fileKey) {
2637
+ const taskId = this.currentTaskIds.get(fileKey);
2638
+ return taskId ? this.records.get(taskId) : void 0;
2639
+ }
2640
+ occupant(fileKey) {
2641
+ const record = this.current(fileKey);
2642
+ return record && RUNNING_STATUSES.includes(record.task.status) ? record : void 0;
2643
+ }
2644
+ busy(record) {
2645
+ 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.`);
2646
+ }
2647
+ hasPendingOperation(fileKey) {
2648
+ return [...this.operations.values()].some((operation) => operation.target.fileKey === fileKey);
2649
+ }
2650
+ assertFileIdle(session) {
2651
+ 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.");
2652
+ }
2653
+ checkOperation(ownerId, session, taskId, write = false) {
2654
+ this.sweep();
2655
+ this.assertFileIdle(session);
2656
+ const record = taskId ? this.owned(taskId, ownerId, true) : void 0;
2657
+ if (record && (!record.ready || record.task.target.sessionId !== session.sessionId)) fail("DESIGN_TARGET_CHANGED", "The task is not bound to this Figma session.");
2658
+ if (write && record?.task.needsRead) fail("DESIGN_TASK_INACTIVE", "Read the bound canvas with get_structure or get_code after resuming before writing.");
2659
+ const occupant = this.occupant(session.fileKey);
2660
+ if (write && occupant && occupant !== record) this.busy(occupant);
2661
+ 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.");
2662
+ }
2663
+ startOperation(requestId, ownerId, extensionId, browserId, session, taskId, write = false) {
2664
+ this.checkOperation(ownerId, session, taskId, write);
2665
+ const record = taskId ? this.records.get(taskId) : void 0;
2666
+ const { busy: _busy, tabId, documentId, ...target } = session;
2667
+ this.operations.set(requestId, {
2668
+ extensionId,
2669
+ browserId,
2670
+ target,
2671
+ taskId,
2672
+ uncertain: false,
2673
+ tabId,
2674
+ documentId
2675
+ });
2676
+ if (!record) return;
2677
+ record.task.operation = write ? "writing" : "reading";
2678
+ this.renew(record);
2679
+ }
2680
+ finishOperation(requestId, extensionId) {
2681
+ const operation = this.operations.get(requestId);
2682
+ if (!operation || operation.extensionId !== extensionId) return;
2683
+ this.operations.delete(requestId);
2684
+ if (!operation.taskId) return;
2685
+ const record = this.records.get(operation.taskId);
2686
+ if (!record) return;
2687
+ record.task.operation = null;
2688
+ if (record.ending) this.finish(record, record.ending);
2689
+ else if (record.task.status === "active") this.renew(record);
2690
+ }
2691
+ /** A transport failure is not evidence that page execution stopped. */
2692
+ uncertain(requestId, extensionId) {
2693
+ const operation = this.operations.get(requestId);
2694
+ if (operation?.extensionId === extensionId) operation.uncertain = true;
2695
+ }
2696
+ reconcileSessions(browserId, sessions, openTabIds) {
2697
+ for (const [requestId, operation] of this.operations) {
2698
+ if (!operation.uncertain) continue;
2699
+ const session = sessions.find((value) => value.sessionId === operation.target.sessionId);
2700
+ const sameBrowser = browserId === operation.browserId;
2701
+ const tabClosed = sameBrowser && operation.tabId !== void 0 && openTabIds !== void 0 && !openTabIds.includes(operation.tabId);
2702
+ 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);
2703
+ if (session && !session.busy || tabClosed || documentReplaced) this.finishOperation(requestId, operation.extensionId);
2704
+ }
2705
+ }
2706
+ /** A new document in the same browser tab can restore the task, never an old write. */
2707
+ recoverSessions(extensions) {
2708
+ const recovered = [];
2709
+ for (const record of this.list()) {
2710
+ const { task, browser } = record;
2711
+ 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;
2712
+ const candidates = extensions.flatMap((extension) => {
2713
+ if (extension.origin !== browser.origin || extension.sessions?.browserId !== browser.browserId) return [];
2714
+ 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) => ({
2715
+ extension,
2716
+ session
2717
+ }));
2718
+ });
2719
+ if (candidates.length !== 1) continue;
2720
+ const { extension, session } = candidates[0];
2721
+ if (this.hasPendingOperation(session.fileKey) || extensions.some((connection) => connection.sessions?.sessions.some((value) => value.fileKey === session.fileKey && value.busy))) continue;
2722
+ record.extensionId = extension.id;
2723
+ record.browser = {
2724
+ ...browser,
2725
+ documentId: session.documentId
2726
+ };
2727
+ record.ready = false;
2728
+ task.target = {
2729
+ ...task.target,
2730
+ sessionId: session.sessionId,
2731
+ fileName: session.fileName
2732
+ };
2733
+ task.epoch = (task.epoch ?? 0) + 1;
2734
+ task.needsRead = true;
2735
+ if (task.status === "interrupted") {
2736
+ record.ending = void 0;
2737
+ task.status = "active";
2738
+ task.expiresAt = this.now() + this.leaseMs;
2739
+ recovered.push({
2740
+ record,
2741
+ extension,
2742
+ session
2743
+ });
2744
+ }
2745
+ this.publish(record);
2746
+ }
2747
+ return recovered;
2748
+ }
2749
+ captureResult(taskId, rootNodeId, removed) {
2750
+ const record = this.records.get(taskId);
2751
+ if (!record) return;
2752
+ const ids = (record.resultNodeIds ?? []).filter((id) => id !== rootNodeId);
2753
+ record.resultNodeIds = (removed ? ids : [...ids, rootNodeId]).slice(-20);
2754
+ this.persist();
2755
+ }
2756
+ snapshotResult(taskId, summary) {
2757
+ const record = this.records.get(taskId);
2758
+ if (!record || record.task.result) return;
2759
+ record.task.result = {
2760
+ nodeIds: record.resultNodeIds ?? [],
2761
+ capturedAt: this.now(),
2762
+ ...summary ? { summary } : {}
2763
+ };
2764
+ this.persist();
2765
+ }
2766
+ stop(taskId, outcome) {
2767
+ const record = this.records.get(taskId);
2768
+ if (!record || ENDED_STATUSES.includes(record.task.status)) return record?.task;
2769
+ if (!RUNNING_STATUSES.includes(record.task.status)) {
2770
+ if (outcome === "completed" || outcome === "cancelled") this.finish(record, outcome);
2771
+ return record.task;
2772
+ }
2773
+ if (outcome === "cancelled" || !record.ending) record.ending = outcome;
2774
+ if ([...this.operations.values()].some((value) => value.taskId === taskId)) {
2775
+ record.task.status = "stopping";
2776
+ this.publish(record);
2777
+ } else this.finish(record, record.ending);
2778
+ return record.task;
2779
+ }
2780
+ disconnectOwner(ownerId) {
2781
+ for (const record of this.records.values()) if (record.ownerId === ownerId) this.stop(record.task.taskId, "paused");
2782
+ }
2783
+ disconnectExtension(extensionId) {
2784
+ for (const operation of this.operations.values()) if (operation.extensionId === extensionId) operation.uncertain = true;
2785
+ for (const record of this.records.values()) if (record.extensionId === extensionId) this.stop(record.task.taskId, "interrupted");
2786
+ }
2787
+ updatePage(taskId, pageId) {
2788
+ const record = this.records.get(taskId);
2789
+ if (!record || record.task.status !== "active") return;
2790
+ record.task.target.pageId = pageId;
2791
+ this.publish(record);
2792
+ }
2793
+ touch(taskId, ownerId) {
2794
+ this.renew(this.owned(taskId, ownerId, true));
2795
+ }
2796
+ sweep() {
2797
+ const now = this.now();
2798
+ for (const record of this.records.values()) if (record.task.status === "active" && !record.task.operation && record.task.expiresAt <= now) this.finish(record, "expired");
2799
+ }
2800
+ renew(record) {
2801
+ record.task.expiresAt = this.now() + this.leaseMs;
2802
+ this.publish(record);
2803
+ }
2804
+ finish(record, status) {
2805
+ record.task.status = status;
2806
+ record.task.operation = null;
2807
+ this.publish(record);
2808
+ }
2809
+ publish(record) {
2810
+ record.task.revision = ++this.revision;
2811
+ this.persist();
2812
+ if (this.current(record.task.target.fileKey) === record) this.options.onChange?.(record);
2813
+ }
2814
+ /** Load only after acquiring the Hub lock. Every old lease remains inactive. */
2815
+ restore() {
2816
+ const snapshot = this.options.store?.load();
2817
+ if (!snapshot) return;
2818
+ this.revision = snapshot.revision;
2819
+ for (const saved of snapshot.records) {
2820
+ const task = {
2821
+ ...saved.task,
2822
+ operation: null,
2823
+ epoch: (saved.task.epoch ?? 0) + 1,
2824
+ needsRead: true,
2825
+ capabilities: void 0,
2826
+ expiresAt: this.now(),
2827
+ revision: ++this.revision
2828
+ };
2829
+ if (task.status === "stopping") task.status = "cancelled";
2830
+ else if (["active", "interrupted"].includes(task.status)) task.status = "paused";
2831
+ this.records.set(task.taskId, {
2832
+ ...saved,
2833
+ task,
2834
+ ownerId: `restored:${task.taskId}`,
2835
+ extensionId: "",
2836
+ ready: false
2837
+ });
1294
2838
  }
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.");
2839
+ for (const [fileKey, taskId] of Object.entries(snapshot.current)) if (this.records.get(taskId)?.task.target.fileKey === fileKey) this.currentTaskIds.set(fileKey, taskId);
2840
+ this.persist();
2841
+ }
2842
+ /** A registered page can recover its saved review, never its execution authority. */
2843
+ restoreReview(saved, extension, session) {
2844
+ if (saved.target.fileKey !== session.fileKey || !extension.sessions) return;
2845
+ let record = this.records.get(saved.taskId);
2846
+ if (record && (record.task.target.fileKey !== saved.target.fileKey || record.task.client?.kind !== saved.client?.kind || record.task.client?.sessionId !== saved.client?.sessionId)) return;
2847
+ if (!record) {
2848
+ if (this.current(session.fileKey)) return;
2849
+ record = {
2850
+ task: {
2851
+ ...saved,
2852
+ status: saved.status === "cancelled" ? "cancelled" : saved.status === "completed" ? "completed" : "paused",
2853
+ operation: null,
2854
+ capabilities: void 0,
2855
+ epoch: (saved.epoch ?? 0) + 1,
2856
+ needsRead: true,
2857
+ expiresAt: this.now()
2858
+ },
2859
+ ownerId: `restored:${saved.taskId}`,
2860
+ extensionId: "",
2861
+ requestId: "",
2862
+ ready: false
2863
+ };
2864
+ this.records.set(saved.taskId, record);
2865
+ this.currentTaskIds.set(session.fileKey, saved.taskId);
2866
+ this.publish(record);
1341
2867
  }
1342
- if (changed) flush();
2868
+ if (saved.reviewClosed) {
2869
+ this.closeReview(saved.taskId);
2870
+ return;
2871
+ }
2872
+ if (saved.status === "cancelled") {
2873
+ this.stop(saved.taskId, "cancelled");
2874
+ return;
2875
+ }
2876
+ if (record.task.reviewClosed || this.current(session.fileKey) !== record) return;
2877
+ if (record.task.status === "interrupted" && record.browser && record.browser.tabId === session.tabId && session.documentId !== void 0 && record.browser.documentId !== session.documentId) return;
2878
+ if (extension.sessions.sessions.some((value) => value.sessionId === record.task.target.sessionId) && record.task.target.sessionId !== session.sessionId) return;
2879
+ if (record.browser && (record.browser.browserId !== extension.sessions.browserId || record.browser.origin !== extension.origin)) return;
2880
+ if (record.task.target.sessionId === session.sessionId && record.extensionId === extension.id) return;
2881
+ if (RUNNING_STATUSES.includes(record.task.status)) return;
2882
+ record.extensionId = extension.id;
2883
+ record.ready = false;
2884
+ record.task.target = {
2885
+ ...record.task.target,
2886
+ sessionId: session.sessionId,
2887
+ fileName: session.fileName
2888
+ };
2889
+ if (session.tabId !== void 0 && session.documentId !== void 0) record.browser = {
2890
+ browserId: extension.sessions.browserId,
2891
+ origin: extension.origin,
2892
+ tabId: session.tabId,
2893
+ documentId: session.documentId
2894
+ };
2895
+ this.publish(record);
1343
2896
  }
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
- }
2897
+ closeReview(taskId) {
2898
+ const record = this.records.get(taskId);
2899
+ if (!record || record.task.reviewClosed) return;
2900
+ record.task.reviewClosed = true;
2901
+ if (!ENDED_STATUSES.includes(record.task.status)) this.stop(taskId, "cancelled");
2902
+ else this.publish(record);
2903
+ }
2904
+ persist() {
2905
+ if (!this.options.store) return;
2906
+ const snapshot = {
2907
+ revision: this.revision,
2908
+ current: Object.fromEntries(this.currentTaskIds),
2909
+ records: [...this.records.values()].map(({ task, requestId, browser, resultNodeIds }) => ({
2910
+ task: {
2911
+ ...task,
2912
+ capabilities: void 0,
2913
+ operation: null
2914
+ },
2915
+ requestId,
2916
+ browser,
2917
+ resultNodeIds
2918
+ }))
2919
+ };
2920
+ this.options.store.save(snapshot);
2921
+ }
2922
+ };
1358
2923
  //#endregion
1359
2924
  //#region src/extension-registry.ts
1360
2925
  var ExtensionRegistry = class {
@@ -1433,15 +2998,22 @@ function attachExtensionSocket(ws, options) {
1433
2998
  const extension = {
1434
2999
  id: options.createId(),
1435
3000
  origin: options.origin.toLowerCase(),
3001
+ connectedAt: (/* @__PURE__ */ new Date()).toISOString(),
3002
+ legacy: ws.protocol !== TEMPAD_MCP_BRIDGE_SUBPROTOCOL,
1436
3003
  ws
1437
3004
  };
1438
3005
  options.registry.add(extension);
1439
3006
  options.onConnected?.(extension.id);
1440
3007
  const registered = {
1441
3008
  id: extension.id,
3009
+ protocolVersion: 13,
3010
+ supportedProtocolVersions: [...TEMPAD_MCP_BRIDGE_SUPPORTED_PROTOCOL_VERSIONS],
1442
3011
  type: "registered"
1443
3012
  };
1444
- ws.send(JSON.stringify(registered));
3013
+ ws.send(JSON.stringify(extension.legacy ? {
3014
+ type: "registered",
3015
+ id: extension.id
3016
+ } : registered));
1445
3017
  options.onStateChange();
1446
3018
  scheduleAutoActivation(options);
1447
3019
  ws.on("message", (raw, isBinary) => {
@@ -1463,7 +3035,7 @@ function attachExtensionSocket(ws, options) {
1463
3035
  });
1464
3036
  return;
1465
3037
  }
1466
- const parseResult = MessageFromExtensionSchema.safeParse(parsedJson);
3038
+ const parseResult = (extension.legacy ? LegacyMessageFromExtensionSchema : MessageFromExtensionSchema).safeParse(parsedJson);
1467
3039
  if (!parseResult.success) {
1468
3040
  options.onProtocolWarning?.({
1469
3041
  error: parseResult.error.flatten(),
@@ -1474,6 +3046,13 @@ function attachExtensionSocket(ws, options) {
1474
3046
  }
1475
3047
  const message = parseResult.data;
1476
3048
  switch (message.type) {
3049
+ case "sessions":
3050
+ extension.sessions = message;
3051
+ options.onSessions?.(extension);
3052
+ break;
3053
+ case "designAction":
3054
+ options.onDesignAction?.(extension, message.sessionId, message.action);
3055
+ break;
1477
3056
  case "activate":
1478
3057
  if (options.registry.activate(extension.id)) {
1479
3058
  options.onActivated?.(extension.id);
@@ -1488,6 +3067,21 @@ function attachExtensionSocket(ws, options) {
1488
3067
  if (message.error !== void 0) options.onToolError(message.id, extension.id, message.error);
1489
3068
  else options.onToolResult(message.id, extension.id, message.payload);
1490
3069
  break;
3070
+ case "runtimeHello":
3071
+ if (extension.runtime && (extension.runtime.version !== message.extensionVersion || extension.runtime.fingerprint !== message.extensionRuntimeFingerprint)) {
3072
+ options.onProtocolWarning?.({
3073
+ error: /* @__PURE__ */ new Error("Extension changed runtime identity on an open connection."),
3074
+ extensionId: extension.id,
3075
+ kind: "schema"
3076
+ });
3077
+ break;
3078
+ }
3079
+ extension.runtime = {
3080
+ version: message.extensionVersion,
3081
+ fingerprint: message.extensionRuntimeFingerprint
3082
+ };
3083
+ options.onRuntimeHello?.(extension);
3084
+ break;
1491
3085
  case "ping": break;
1492
3086
  }
1493
3087
  });
@@ -1517,7 +3111,7 @@ function rawDataToBuffer(raw) {
1517
3111
  }
1518
3112
  //#endregion
1519
3113
  //#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";
3114
+ var instructions_default = "You are connected to Figma through TemPad Dev. Badge activation selects the default target;\nforegrounding a tab does not select it. Use `list_design_sessions` and pass an exact `sessionId`\nto `begin_design` when the intended target is unclear.\n\nFor new design work, begin with `begin_design` and carry its `taskId` on related calls.\nBegin before choosing a canvas location. Use `set_design_anchor` for a known existing\nFrame; otherwise the first created top-level Frame anchors automatically. The region\nstays stable until explicitly changed with `set_design_anchor`.\nTask identity outlives a turn. A lifecycle pause or idle lease expiry releases canvas ownership without\ncancelling the design. Resume with `resume_design`, carry its returned `epoch` as `taskEpoch`,\nand reread the relevant canvas with `get_structure` or `get_code` before writing. Use\n`get_design_task` for recovery, not routine polling. Task targets never follow browser focus.\nCompletion releases canvas ownership while leaving the review open. Follow-up comments\ncontinue that same task with `resume_design`, preserving its design region until the user\nclicks Done. Cancelled, closed, or replaced tasks cannot resume. Do not automatically\nbegin a replacement task for comments whose original review is no longer current.\nNo progress or heartbeat calls are needed. Never replay stale writes or queue writes against\nan occupied file. The Figma Stop control permanently cancels the current task after any running operation settles. Never resume\nthat cancelled task or automatically replace it. If further design work is necessary or\nthe user requests it, explicitly call `begin_design` with a fresh requestId. No separate\nFigma unlock or new user turn is required.\nIndependent reads need no task.\nRun calls against the same Figma file sequentially, including reads such as `get_screenshot`\nand `get_structure`; await each result before starting the next file operation.\n\nUse `end_design` only after this design pass and its verification are complete, or explicitly\ncancel when abandoning it. Waiting for input is a pause. Figma feedback batches\ncontain individually numbered elements captured when their drafts were saved. Reread each\nexact node before acting on the batch; do not substitute the current selection.\nSupported hosts receive submitted feedback through native conversation messages. Do not poll for feedback,\nstart helper processes, or configure a host 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 define mechanical affordances; the applicable\nhost skill owns task workflow, representation choice, and design judgment.\n\n- For Figma-to-code, use `get_code` as visible implementation evidence. Use `get_structure` only for\n hierarchy, geometry, managed authoring-key uncertainty, or targeted mask, IMAGE paint,\n layout-grid, and frame-guide read-back through `options.native`.\n- For canvas authoring, choose the Figma representation through the applicable skill, then use\n `apply_canvas` to describe one declarative desired result. Canvas HTML serializes ordinary layers;\n typed fields carry selected native state, resources, and bindings. Never emit raw Plugin API\n operations or arbitrary JavaScript. `get_design_system` is optional discovery for relevant,\n permitted reuse; new local resources do not require it. Font queries with `scope: \"fonts\"` read\n environment availability independently of resource reuse. Use catalog CSS names or a call-scoped\n `theme` for variable utilities and native text-style classes. Load the skill's progressive references\n for exact shapes only after choosing the native concept.\n\nWhen the user limits design evidence to the current page or requests an independent system without\npre-existing resource reuse, stay on the Direct path: do not discover resource catalogs, inspect other\npages, or use catalog refs. `get_design_system` with `scope: \"fonts\"` remains available. Local variables and styles remain file-wide Figma resources, and the\nextension may still perform file-wide identity checks internally for safe reconciliation.\n\nCreate operations add and automatically place one new root. Updates are scoped by exact node\nidentity: omission preserves live state, while explicit removal removes managed content. Read\nstructural verification and resolve warnings before claiming native authoring is complete.\n\nUse `get_screenshot` when rendered pixels affect a decision, and open the returned image before\nclaiming visual verification. Use a returned `asset.localPath` directly when present; otherwise use\n`asset.url`. Native media hashes are identities inside the current Figma file, not preview bytes.\n\nNever ship `data-hint-*` attributes from read-tool output.\n";
1521
3115
  //#endregion
1522
3116
  //#region src/request.ts
1523
3117
  const pendingCalls = /* @__PURE__ */ new Map();
@@ -1526,11 +3120,19 @@ function createToolError(code, message) {
1526
3120
  err.code = code;
1527
3121
  return err;
1528
3122
  }
1529
- function register(extensionId, timeout) {
3123
+ function register(extensionId, timeout, options = {}) {
1530
3124
  const requestId = nanoid();
1531
3125
  return {
1532
3126
  promise: new Promise((resolve, reject) => {
1533
3127
  const timer = setTimeout(() => {
3128
+ if (options.waitForDefinitiveResult) {
3129
+ log.warn({
3130
+ reqId: requestId,
3131
+ extId: extensionId,
3132
+ timeout
3133
+ }, "Extension call exceeded its warning threshold; waiting for a definitive result.");
3134
+ return;
3135
+ }
1534
3136
  pendingCalls.delete(requestId);
1535
3137
  reject(createToolError(TEMPAD_MCP_ERROR_CODES.EXTENSION_TIMEOUT, `Extension did not respond within ${timeout / 1e3}s.`));
1536
3138
  }, timeout);
@@ -1544,39 +3146,34 @@ function register(extensionId, timeout) {
1544
3146
  requestId
1545
3147
  };
1546
3148
  }
1547
- function resolve(requestId, extensionId, payload) {
3149
+ function pendingResponse(requestId, extensionId, outcome) {
1548
3150
  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.");
3151
+ if (!call) {
3152
+ log.warn({ reqId: requestId }, `Received ${outcome} for unknown/timed-out call.`);
3153
+ return;
3154
+ }
3155
+ if (call.extensionId !== extensionId) {
3156
+ log.warn({
3157
+ reqId: requestId,
3158
+ expectedExtId: call.extensionId,
3159
+ receivedExtId: extensionId
3160
+ }, `Ignored tool ${outcome} from the wrong extension.`);
3161
+ return;
3162
+ }
3163
+ clearTimeout(call.timer);
3164
+ return call;
3165
+ }
3166
+ function resolve$1(requestId, extensionId, payload) {
3167
+ const call = pendingResponse(requestId, extensionId, "result");
3168
+ if (!call) return;
3169
+ call.resolve(payload);
3170
+ pendingCalls.delete(requestId);
1563
3171
  }
1564
3172
  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.");
3173
+ const call = pendingResponse(requestId, extensionId, "error");
3174
+ if (!call) return;
3175
+ call.reject(error);
3176
+ pendingCalls.delete(requestId);
1580
3177
  }
1581
3178
  function cleanupForExtension(extensionId) {
1582
3179
  for (const [reqId, call] of pendingCalls.entries()) {
@@ -1602,7 +3199,81 @@ function cleanupAll() {
1602
3199
  pendingCalls.clear();
1603
3200
  }
1604
3201
  //#endregion
3202
+ //#region src/runtime-identity.ts
3203
+ function fingerprintRuntimeFile(path) {
3204
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
3205
+ }
3206
+ function createHubRuntimeIdentity(entryPath, packageVersion, options = {}) {
3207
+ return {
3208
+ schemaVersion: 1,
3209
+ packageVersion,
3210
+ runtimeFingerprint: fingerprintRuntimeFile(entryPath),
3211
+ entryPath: resolve(entryPath),
3212
+ startedAt: (options.now ?? /* @__PURE__ */ new Date()).toISOString(),
3213
+ processId: options.processId ?? process.pid,
3214
+ activeExtension: null
3215
+ };
3216
+ }
3217
+ function isSha256(value) {
3218
+ return typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
3219
+ }
3220
+ function parseHubRuntimeIdentity(value) {
3221
+ if (!value || typeof value !== "object") return null;
3222
+ const candidate = value;
3223
+ const activeExtension = parseActiveExtensionRuntimeIdentity(candidate.activeExtension);
3224
+ 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;
3225
+ return {
3226
+ ...candidate,
3227
+ activeExtension
3228
+ };
3229
+ }
3230
+ function parseActiveExtensionRuntimeIdentity(value) {
3231
+ if (value === void 0 || value === null) return null;
3232
+ if (!value || typeof value !== "object") return void 0;
3233
+ const candidate = value;
3234
+ 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;
3235
+ return candidate;
3236
+ }
3237
+ function readHubRuntimeIdentity(path) {
3238
+ try {
3239
+ return parseHubRuntimeIdentity(JSON.parse(readFileSync(path, "utf8")));
3240
+ } catch {
3241
+ return null;
3242
+ }
3243
+ }
3244
+ function writeHubRuntimeIdentity(path, identity) {
3245
+ const temporaryPath = `${path}.${identity.processId}.tmp`;
3246
+ writeFileSync(temporaryPath, `${JSON.stringify(identity, null, 2)}\n`, { mode: 384 });
3247
+ renameSync(temporaryPath, path);
3248
+ }
3249
+ function removeHubRuntimeIdentityIfOwned(path, processId) {
3250
+ if (readHubRuntimeIdentity(path)?.processId !== processId) return;
3251
+ rmSync(path, { force: true });
3252
+ }
3253
+ function getExtensionRuntimeIssues(runtime) {
3254
+ if (!runtime) return ["Extension did not publish a runtime identity handshake"];
3255
+ return [];
3256
+ }
3257
+ //#endregion
1605
3258
  //#region src/tools.ts
3259
+ const READ_ONLY_ANNOTATIONS = {
3260
+ readOnlyHint: true,
3261
+ destructiveHint: false,
3262
+ idempotentHint: true,
3263
+ openWorldHint: false
3264
+ };
3265
+ const CANVAS_WRITE_ANNOTATIONS = {
3266
+ readOnlyHint: false,
3267
+ destructiveHint: true,
3268
+ idempotentHint: false,
3269
+ openWorldHint: true
3270
+ };
3271
+ const ASSET_WRITE_ANNOTATIONS = {
3272
+ readOnlyHint: false,
3273
+ destructiveHint: false,
3274
+ idempotentHint: true,
3275
+ openWorldHint: false
3276
+ };
1606
3277
  const CONNECTIVITY_ERROR_CODES = /* @__PURE__ */ new Set([
1607
3278
  TEMPAD_MCP_ERROR_CODES.NO_ACTIVE_EXTENSION,
1608
3279
  TEMPAD_MCP_ERROR_CODES.EXTENSION_TIMEOUT,
@@ -1614,17 +3285,15 @@ const SELECTION_ERROR_CODES = /* @__PURE__ */ new Set([TEMPAD_MCP_ERROR_CODES.IN
1614
3285
  const KNOWN_ERROR_CODES = new Set(Object.values(TEMPAD_MCP_ERROR_CODES));
1615
3286
  const CONNECTIVITY_TROUBLESHOOTING_LINES = [
1616
3287
  "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."
3288
+ "- 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.",
3289
+ "- Confirm that the panel header MCP badge is active. If multiple Figma tabs are open, click the intended tab's badge; foregrounding it alone does not activate it.",
3290
+ "- If the badge is missing, shows an error, 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
3291
  ];
1621
3292
  const SELECTION_TROUBLESHOOTING_LINE = "Tip: Select exactly one visible node, or pass nodeId.";
3293
+ 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
3294
  function isRecord(value) {
1623
3295
  return !!value && typeof value === "object" && !Array.isArray(value);
1624
3296
  }
1625
- function getRecordProperty$1(record, key) {
1626
- return isRecord(record) ? record[key] : void 0;
1627
- }
1628
3297
  function extTool(definition) {
1629
3298
  return definition;
1630
3299
  }
@@ -1632,23 +3301,75 @@ function hubTool(definition) {
1632
3301
  return definition;
1633
3302
  }
1634
3303
  const TOOL_DEFS = [
3304
+ hubTool({
3305
+ name: "get_design_task",
3306
+ 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.",
3307
+ annotations: READ_ONLY_ANNOTATIONS,
3308
+ parameters: z.object({ taskId: DesignTaskIdSchema }).strict(),
3309
+ target: "hub",
3310
+ outputSchema: DesignTaskSchema
3311
+ }),
3312
+ hubTool({
3313
+ name: "list_design_sessions",
3314
+ description: "List connected Figma targets before beginning a design. Select an exact sessionId when more than one file is connected.",
3315
+ annotations: READ_ONLY_ANNOTATIONS,
3316
+ parameters: z.object({}).strict(),
3317
+ target: "hub",
3318
+ outputSchema: z.object({ sessions: z.array(FigmaSessionSchema) })
3319
+ }),
3320
+ hubTool({
3321
+ name: "resume_design",
3322
+ 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.",
3323
+ annotations: ASSET_WRITE_ANNOTATIONS,
3324
+ parameters: ResumeDesignParametersSchema,
3325
+ target: "hub",
3326
+ outputSchema: DesignTaskSchema
3327
+ }),
3328
+ hubTool({
3329
+ name: "begin_design",
3330
+ 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.",
3331
+ annotations: ASSET_WRITE_ANNOTATIONS,
3332
+ parameters: BeginDesignParametersSchema,
3333
+ target: "hub",
3334
+ outputSchema: DesignTaskSchema
3335
+ }),
3336
+ hubTool({
3337
+ name: "end_design",
3338
+ 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.",
3339
+ annotations: ASSET_WRITE_ANNOTATIONS,
3340
+ parameters: EndDesignParametersSchema,
3341
+ target: "hub",
3342
+ outputSchema: DesignTaskSchema
3343
+ }),
3344
+ extTool({
3345
+ name: "set_design_anchor",
3346
+ 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.",
3347
+ annotations: ASSET_WRITE_ANNOTATIONS,
3348
+ parameters: SetDesignAnchorParametersSchema,
3349
+ target: "extension",
3350
+ outputSchema: DesignAnchorSchema,
3351
+ format: createDesignAnchorToolResponse
3352
+ }),
1635
3353
  extTool({
1636
3354
  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).",
3355
+ 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.",
3356
+ annotations: READ_ONLY_ANNOTATIONS,
1638
3357
  parameters: GetCodeParametersSchema,
1639
3358
  target: "extension",
1640
3359
  format: createCodeToolResponse
1641
3360
  }),
1642
3361
  extTool({
1643
3362
  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.",
3363
+ description: "Discover resources 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. Use resource discovery only when existing-resource reuse is permitted and relevant; skip it when the user limits design evidence to the current page or requests an independent system. Start without arguments; continue by catalogId/cursor or inspect catalogId/ref.",
3364
+ annotations: READ_ONLY_ANNOTATIONS,
1645
3365
  parameters: GetDesignSystemParametersSchema,
1646
3366
  target: "extension",
1647
3367
  format: createDesignSystemToolResponse
1648
3368
  }),
1649
3369
  extTool({
1650
3370
  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.",
3371
+ 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.",
3372
+ annotations: CANVAS_WRITE_ANNOTATIONS,
1652
3373
  parameters: ApplyCanvasParametersSchema,
1653
3374
  target: "extension",
1654
3375
  format: createApplyCanvasToolResponse
@@ -1656,6 +3377,7 @@ const TOOL_DEFS = [
1656
3377
  extTool({
1657
3378
  name: "get_token_defs",
1658
3379
  description: "Resolve canonical token names to literal values (optionally including all modes) for tokens referenced by get_code.",
3380
+ annotations: READ_ONLY_ANNOTATIONS,
1659
3381
  parameters: GetTokenDefsParametersSchema,
1660
3382
  target: "extension",
1661
3383
  format: createTokenDefsToolResponse,
@@ -1663,22 +3385,33 @@ const TOOL_DEFS = [
1663
3385
  }),
1664
3386
  extTool({
1665
3387
  name: "get_screenshot",
1666
- description: "Capture a rendered PNG screenshot for nodeId/current single selection for visual verification (layering/overlap/masks/effects).",
3388
+ description: "Capture one bounded rendered PNG asset for an exact node or the current single selection.",
3389
+ annotations: READ_ONLY_ANNOTATIONS,
1667
3390
  parameters: GetScreenshotParametersSchema,
1668
3391
  target: "extension",
1669
- format: createScreenshotToolResponse,
1670
- exposed: false
3392
+ format: createScreenshotToolResponse
1671
3393
  }),
1672
3394
  extTool({
1673
3395
  name: "get_structure",
1674
- description: "Get a compact structural + geometry outline for nodeId/current single selection to understand hierarchy and layout intent.",
3396
+ 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.",
3397
+ annotations: READ_ONLY_ANNOTATIONS,
1675
3398
  parameters: GetStructureParametersSchema,
1676
3399
  target: "extension",
1677
3400
  format: createStructureToolResponse
1678
3401
  }),
3402
+ hubTool({
3403
+ name: "upload_asset",
3404
+ 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.",
3405
+ annotations: ASSET_WRITE_ANNOTATIONS,
3406
+ parameters: UploadAssetParametersSchema,
3407
+ target: "hub",
3408
+ outputSchema: UploadAssetResultSchema,
3409
+ format: createUploadAssetToolResponse
3410
+ }),
1679
3411
  hubTool({
1680
3412
  name: "get_assets",
1681
3413
  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.",
3414
+ annotations: READ_ONLY_ANNOTATIONS,
1682
3415
  parameters: GetAssetsParametersSchema,
1683
3416
  target: "hub",
1684
3417
  outputSchema: GetAssetsResultSchema,
@@ -1686,9 +3419,9 @@ const TOOL_DEFS = [
1686
3419
  })
1687
3420
  ];
1688
3421
  function extractToolErrorCode(error) {
1689
- const code = getRecordProperty$1(error, "code");
3422
+ const code = getRecordProperty(error, "code");
1690
3423
  if (isTempadMcpErrorCode(code)) return code;
1691
- const causeCode = getRecordProperty$1(getRecordProperty$1(error, "cause"), "code");
3424
+ const causeCode = getRecordProperty(getRecordProperty(error, "cause"), "code");
1692
3425
  if (isTempadMcpErrorCode(causeCode)) return causeCode;
1693
3426
  }
1694
3427
  function isTempadMcpErrorCode(value) {
@@ -1697,9 +3430,8 @@ function isTempadMcpErrorCode(value) {
1697
3430
  function extractToolErrorMessage(error) {
1698
3431
  if (error instanceof Error) return error.message || "Unknown error occurred.";
1699
3432
  if (typeof error === "string") return error;
1700
- if (isRecord(error)) {
1701
- if (typeof error.message === "string" && error.message.trim()) return error.message;
1702
- }
3433
+ const message = getRecordProperty(error, "message");
3434
+ if (typeof message === "string" && message.trim()) return message;
1703
3435
  return "Unknown error occurred.";
1704
3436
  }
1705
3437
  function createToolErrorResponse(toolName, error) {
@@ -1717,10 +3449,11 @@ function buildTroubleshootingText(code, message) {
1717
3449
  const help = [];
1718
3450
  if (isConnectivityToolError(code, message)) help.push(...CONNECTIVITY_TROUBLESHOOTING_LINES);
1719
3451
  if (isSelectionToolError(code, message)) help.push(SELECTION_TROUBLESHOOTING_LINE);
3452
+ if (code === TEMPAD_MCP_ERROR_CODES.INVALID_CANVAS_SPEC && /verification failed/i.test(message)) help.push(VERIFICATION_TROUBLESHOOTING_LINE);
1720
3453
  return help.length ? `\n\n${help.join("\n")}` : "";
1721
3454
  }
1722
3455
  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);
3456
+ 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
3457
  }
1725
3458
  function isSelectionToolError(code, message) {
1726
3459
  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 +3484,10 @@ function isScreenshotResult(payload) {
1751
3484
  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
3485
  }
1753
3486
  function isDesignSystemResult(payload) {
1754
- return isRecord(payload) && isRecord(payload.page) && Array.isArray(payload.components) && Array.isArray(payload.variables);
3487
+ return GetDesignSystemResultSchema.safeParse(payload).success;
1755
3488
  }
1756
3489
  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";
3490
+ return ApplyCanvasResultSchema.safeParse(payload).success;
1758
3491
  }
1759
3492
  function isCodeResult(payload) {
1760
3493
  return isRecord(payload) && typeof payload.code === "string" && typeof payload.lang === "string" && (payload.assets === void 0 || Array.isArray(payload.assets));
@@ -1777,6 +3510,29 @@ function coercePayloadToToolResponse(payload) {
1777
3510
  function createAssetsToolResponse(payload) {
1778
3511
  return toCallToolResult(buildGetAssetsToolResult(payload));
1779
3512
  }
3513
+ function createUploadAssetToolResponse(payload) {
3514
+ return toCallToolResult(buildUploadAssetToolResult(payload));
3515
+ }
3516
+ function createDesignTaskToolResponse(payload) {
3517
+ const task = DesignTaskSchema.parse(payload);
3518
+ return {
3519
+ content: [{
3520
+ type: "text",
3521
+ text: JSON.stringify(task)
3522
+ }],
3523
+ structuredContent: task
3524
+ };
3525
+ }
3526
+ function createDesignAnchorToolResponse(payload) {
3527
+ const anchor = DesignAnchorSchema.parse(payload);
3528
+ return {
3529
+ content: [{
3530
+ type: "text",
3531
+ text: JSON.stringify(anchor)
3532
+ }],
3533
+ structuredContent: anchor
3534
+ };
3535
+ }
1780
3536
  function createInlineBudgetExceededToolResponse(toolName, actualBytes) {
1781
3537
  return {
1782
3538
  isError: true,
@@ -1791,14 +3547,20 @@ function toCallToolResult(result) {
1791
3547
  }
1792
3548
  function getBudgetRetryGuidance(toolName) {
1793
3549
  switch (toolName) {
3550
+ case "get_design_task":
3551
+ case "list_design_sessions":
3552
+ case "begin_design":
3553
+ case "resume_design":
3554
+ case "end_design":
3555
+ case "set_design_anchor": return "Retry the same task lifecycle request without changing its identity.";
1794
3556
  case "apply_canvas": return "Submit a smaller desired subtree and retry.";
1795
3557
  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.";
3558
+ case "get_design_system": return "Continue from another catalog cursor or avoid the oversized exact definition.";
1797
3559
  case "get_structure": return "Reduce selection size or pass a smaller depth and retry.";
1798
3560
  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.";
3561
+ case "get_screenshot": return "Pass a smaller nodeId and retry.";
1800
3562
  case "get_assets": return "Request fewer hashes in a single call and retry.";
1801
- default: return "Retry with a narrower request.";
3563
+ case "upload_asset": return "Generate a smaller PNG, JPEG, or GIF and retry without printing its data URL.";
1802
3564
  }
1803
3565
  }
1804
3566
  //#endregion
@@ -1809,12 +3571,14 @@ async function startExtensionWebSocketServer({ maxPayloadBytes, maxConnections,
1809
3571
  host: "127.0.0.1",
1810
3572
  port: candidate,
1811
3573
  maxPayload: maxPayloadBytes,
3574
+ handleProtocols: (protocols) => protocols.has("tempad-mcp") ? TEMPAD_MCP_BRIDGE_SUBPROTOCOL : false,
1812
3575
  verifyClient: (info) => {
1813
3576
  if (server.clients.size >= maxConnections) {
1814
3577
  onConnectionLimit?.(maxConnections);
1815
3578
  return false;
1816
3579
  }
1817
- const allowed = isAllowedWebSocketRequest(info.origin, info.req.url, originPolicy);
3580
+ const protocol = info.req.headers["sec-websocket-protocol"];
3581
+ const allowed = isAllowedWebSocketRequest(info.origin, info.req.url, originPolicy) && (!protocol || protocol.split(",").some((value) => value.trim() === "tempad-mcp"));
1818
3582
  if (!allowed) onRejectedHandshake?.(info.origin, info.req.url);
1819
3583
  return allowed;
1820
3584
  }
@@ -1859,20 +3623,35 @@ function resolveListeningPort(server, candidate) {
1859
3623
  //#region src/hub.ts
1860
3624
  const SHUTDOWN_TIMEOUT = 2e3;
1861
3625
  const SOCKET_PROBE_TIMEOUT_MS = 300;
1862
- const { wsPortCandidates, toolTimeoutMs, maxPayloadBytes, maxExtensionConnections, autoActivateGraceMs, assetTtlMs, allowedExtensionOrigins } = getMcpServerConfig();
3626
+ const { wsPortCandidates, toolTimeoutMs, getCodeTimeoutMs, applyCanvasTimeoutMs, maxPayloadBytes, maxAssetSizeBytes, maxExtensionConnections, autoActivateGraceMs, assetTtlMs, allowedExtensionOrigins } = getMcpServerConfig();
1863
3627
  const extensionOriginPolicy = createExtensionOriginPolicy(allowedExtensionOrigins);
1864
3628
  log.info({ version: PACKAGE_VERSION }, "TemPad MCP Hub starting...");
1865
3629
  const extensionRegistry = new ExtensionRegistry(autoActivateGraceMs);
3630
+ const taskStateDirectory = join(homedir(), ".tempad-dev", "state");
3631
+ const designTasks = new DesignTasks({
3632
+ createId: randomUUID,
3633
+ onChange: publishDesignTask,
3634
+ store: new DesignTaskStore(join(taskStateDirectory, "design-tasks.json"))
3635
+ });
3636
+ const agentClients = new AgentClients(designTasks, new CodexAppFeedback(join(taskStateDirectory, "codex-feedback")), (changed) => new CodexAppLifecycle(changed));
3637
+ let refreshingCapabilities = false;
3638
+ const clientCapabilityTimer = setInterval(() => {
3639
+ if (refreshingCapabilities) return;
3640
+ refreshingCapabilities = true;
3641
+ agentClients.refreshCapabilities().catch((error) => log.warn({ error }, "Could not refresh agent capabilities.")).finally(() => {
3642
+ refreshingCapabilities = false;
3643
+ });
3644
+ }, 1e4);
3645
+ const pendingDesignBindings = /* @__PURE__ */ new Map();
3646
+ const designTaskTimer = setInterval(() => designTasks.sweep(), 1e3);
3647
+ designTaskTimer.unref();
1866
3648
  let consumerCount = 0;
1867
3649
  let selectedWsPort = 0;
1868
3650
  let releaseHubLock = null;
1869
3651
  let shuttingDown = false;
1870
3652
  let wss = null;
3653
+ let hubRuntimeIdentity = null;
1871
3654
  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
3655
  function classifySocketProbeError(error) {
1877
3656
  if (error.code === "ENOENT") return "missing";
1878
3657
  if (error.code === "ECONNREFUSED" || error.code === "ENOTSOCK") return { staleCode: error.code };
@@ -1955,10 +3734,44 @@ async function cleanSocketPath() {
1955
3734
  function enrichToolDefinition(tool) {
1956
3735
  if (tool.target === "extension") return tool;
1957
3736
  switch (tool.name) {
3737
+ case "get_design_task": return {
3738
+ ...tool,
3739
+ handler: async (args, ownerId) => createDesignTaskToolResponse(designTasks.owned(args.taskId, ownerId).task)
3740
+ };
3741
+ case "list_design_sessions": return {
3742
+ ...tool,
3743
+ handler: async () => {
3744
+ const result = { sessions: extensionRegistry.list().flatMap((value) => value.sessions?.sessions ?? []) };
3745
+ if (!result.sessions.length && extensionRegistry.list().some((value) => value.legacy)) throw extensionUpgradeRequired();
3746
+ return {
3747
+ content: [{
3748
+ type: "text",
3749
+ text: JSON.stringify(result)
3750
+ }],
3751
+ structuredContent: result
3752
+ };
3753
+ }
3754
+ };
3755
+ case "resume_design": return {
3756
+ ...tool,
3757
+ handler: handleResumeDesign
3758
+ };
3759
+ case "begin_design": return {
3760
+ ...tool,
3761
+ handler: handleBeginDesign
3762
+ };
3763
+ case "end_design": return {
3764
+ ...tool,
3765
+ handler: handleEndDesign
3766
+ };
1958
3767
  case "get_assets": return {
1959
3768
  ...tool,
1960
3769
  handler: handleGetAssets
1961
3770
  };
3771
+ case "upload_asset": return {
3772
+ ...tool,
3773
+ handler: handleUploadAsset
3774
+ };
1962
3775
  default: throw new Error("No handler configured for hub tool.");
1963
3776
  }
1964
3777
  }
@@ -2036,6 +3849,7 @@ function buildAssetDescriptor(record) {
2036
3849
  return {
2037
3850
  hash: record.hash,
2038
3851
  url: `${assetHttpServer.getBaseUrl()}/assets/${filename}`,
3852
+ localPath: record.filePath,
2039
3853
  mimeType: record.mimeType,
2040
3854
  size: record.size,
2041
3855
  width: record.metadata?.width,
@@ -2043,52 +3857,195 @@ function buildAssetDescriptor(record) {
2043
3857
  ...record.metadata?.themeable ? { themeable: true } : {}
2044
3858
  };
2045
3859
  }
2046
- function createMcpServer() {
3860
+ function publishDesignTask({ task }) {
3861
+ const message = JSON.stringify({
3862
+ type: "designTaskState",
3863
+ task
3864
+ });
3865
+ for (const extension of extensionRegistry.list()) {
3866
+ if (!extension.sessions?.sessions.some((session) => session.fileKey === task.target.fileKey)) continue;
3867
+ try {
3868
+ extension.ws.send(message);
3869
+ } catch (error) {
3870
+ log.warn({
3871
+ error,
3872
+ taskId: task.taskId
3873
+ }, "Failed to synchronize design task.");
3874
+ }
3875
+ }
3876
+ }
3877
+ function resolveDesignRoute(ownerId, taskId, active = true, explicitSessionId) {
3878
+ return resolveDesignTarget(designTasks, extensionRegistry.list(), extensionRegistry.getActiveId(), ownerId, taskId, active, explicitSessionId);
3879
+ }
3880
+ async function handleBeginDesign(args, ownerId) {
3881
+ let record = designTasks.retry(ownerId, args.requestId);
3882
+ if (record) {
3883
+ 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.");
3884
+ await pendingDesignBindings.get(record.task.taskId);
3885
+ return createDesignTaskToolResponse(record.task);
3886
+ }
3887
+ const { extension, session } = resolveDesignRoute(ownerId, void 0, true, args.sessionId);
3888
+ const issues = getExtensionRuntimeIssues(extension.runtime);
3889
+ if (issues.length) throw createCodedError(TEMPAD_MCP_ERROR_CODES.RUNTIME_IDENTITY_MISMATCH, issues.join("; "));
3890
+ const { client, capabilities } = await agentClients.describe(ownerId);
3891
+ record = designTasks.begin(ownerId, extension.id, session, args.title, args.requestId, client, capabilities, extension.sessions ? {
3892
+ browserId: extension.sessions.browserId,
3893
+ origin: extension.origin
3894
+ } : void 0);
3895
+ const task = record.task;
3896
+ const binding = bindDesignTask(record, extension, session);
3897
+ pendingDesignBindings.set(task.taskId, binding);
3898
+ try {
3899
+ await binding;
3900
+ return createDesignTaskToolResponse(task);
3901
+ } finally {
3902
+ if (pendingDesignBindings.get(task.taskId) === binding) pendingDesignBindings.delete(task.taskId);
3903
+ }
3904
+ }
3905
+ async function bindDesignTask({ task, ownerId }, extension, session) {
3906
+ const epoch = task.epoch ?? 0;
3907
+ const registration = register(extension.id, toolTimeoutMs);
3908
+ try {
3909
+ const message = {
3910
+ type: "toolCall",
3911
+ id: registration.requestId,
3912
+ route: {
3913
+ gatewayId: extension.id,
3914
+ sessionId: session.sessionId,
3915
+ fileKey: session.fileKey
3916
+ },
3917
+ payload: {
3918
+ name: "__begin_design",
3919
+ args: task
3920
+ }
3921
+ };
3922
+ extension.ws.send(JSON.stringify(message));
3923
+ const bound = DesignTaskSchema.parse(await registration.promise);
3924
+ 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.");
3925
+ designTasks.assertEpoch(task.taskId, ownerId, epoch);
3926
+ designTasks.confirm(task.taskId, ownerId);
3927
+ } catch (error) {
3928
+ reject(registration.requestId, extension.id, coerceToolError(error));
3929
+ await registration.promise.catch(() => void 0);
3930
+ if ((task.epoch ?? 0) === epoch && task.target.sessionId === session.sessionId) designTasks.stop(task.taskId, "interrupted");
3931
+ throw error;
3932
+ }
3933
+ }
3934
+ async function handleResumeDesign(args, ownerId) {
3935
+ const { extension, session } = resolveDesignRoute(ownerId, args.taskId, false);
3936
+ const { client, capabilities } = await agentClients.describe(ownerId);
3937
+ designTasks.attachClient(ownerId, client, capabilities);
3938
+ const record = designTasks.resume(args.taskId, ownerId, args.epoch, session);
3939
+ record.extensionId = extension.id;
3940
+ if (!record.ready) await (pendingDesignBindings.get(args.taskId) ?? bindDesignTask(record, extension, session));
3941
+ return createDesignTaskToolResponse(record.task);
3942
+ }
3943
+ async function handleEndDesign(args, ownerId) {
3944
+ const record = designTasks.assertEpoch(args.taskId, ownerId, args.taskEpoch);
3945
+ 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.");
3946
+ if (args.outcome === "cancelled") agentClients.cancelFeedback(args.taskId, true).catch(() => {});
3947
+ designTasks.snapshotResult(args.taskId, args.summary);
3948
+ designTasks.stop(args.taskId, args.outcome);
3949
+ return createDesignTaskToolResponse(record.task);
3950
+ }
3951
+ function createMcpServer(ownerId) {
2047
3952
  const mcp = new McpServer({
2048
3953
  name: "tempad-dev",
2049
3954
  title: "TemPad Dev",
2050
3955
  version: PACKAGE_VERSION
2051
3956
  }, { instructions: instructions_default });
3957
+ mcp.server.setNotificationHandler(ClientEventSchema, (notification) => agentClients.event(ownerId, notification));
3958
+ mcp.server.setRequestHandler(ClientHookRequestSchema, (request) => agentClients.clientHook(request.params));
2052
3959
  const registered = [];
2053
3960
  for (const tool of TOOL_DEFINITIONS) {
2054
3961
  if ("exposed" in tool && tool.exposed === false) continue;
2055
- registerTool(mcp, tool);
3962
+ registerTool(mcp, tool, ownerId);
2056
3963
  registered.push(tool.name);
2057
3964
  }
2058
3965
  log.info({ tools: registered }, "Registered tools.");
2059
3966
  return mcp;
2060
3967
  }
2061
- function registerTool(mcp, tool) {
2062
- if (tool.target === "extension") registerProxiedTool(mcp, tool);
2063
- else registerLocalTool(mcp, tool);
3968
+ function registerTool(mcp, tool, ownerId) {
3969
+ if (tool.target === "extension") registerProxiedTool(mcp, tool, ownerId);
3970
+ else registerLocalTool(mcp, tool, ownerId);
2064
3971
  }
2065
- function registerProxiedTool(mcp, tool) {
3972
+ function registerProxiedTool(mcp, tool, ownerId) {
2066
3973
  const registerToolFn = mcp.registerTool.bind(mcp);
2067
3974
  const schema = tool.parameters;
2068
- const handler = async (args) => {
3975
+ const connectionId = ownerId;
3976
+ const handler = async (args, extra) => {
3977
+ const ownerId = await agentClients.owner(connectionId, extra._meta, mcp.server.getClientVersion());
2069
3978
  let requestId;
2070
3979
  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);
3980
+ const parsed = schema.parse(args);
3981
+ const { taskId, taskEpoch, ...parsedArgs } = parsed;
3982
+ if (taskId) designTasks.assertEpoch(taskId, ownerId, taskEpoch);
3983
+ const timeoutMs = tool.name === "get_code" ? getCodeTimeoutMs : tool.name === "apply_canvas" ? applyCanvasTimeoutMs : toolTimeoutMs;
3984
+ const legacy = !taskId ? extensionRegistry.getActive() : void 0;
3985
+ if (legacy?.legacy) {
3986
+ const payload = legacyToolPayload(tool.name, parsed);
3987
+ const registration = register(legacy.id, timeoutMs);
3988
+ requestId = registration.requestId;
3989
+ try {
3990
+ legacy.ws.send(JSON.stringify({
3991
+ type: "toolCall",
3992
+ id: requestId,
3993
+ payload
3994
+ }));
3995
+ } catch (error) {
3996
+ reject(requestId, legacy.id, coerceToolError(error));
3997
+ }
3998
+ return createToolResponse(tool.name, await registration.promise);
3999
+ }
4000
+ const { extension: activeExt, session } = resolveDesignRoute(ownerId, taskId);
4001
+ const runtimeIssues = getExtensionRuntimeIssues(activeExt.runtime);
4002
+ if (runtimeIssues.length) throw createCodedError(TEMPAD_MCP_ERROR_CODES.RUNTIME_IDENTITY_MISMATCH, `${runtimeIssues.join("; ")}. Rebuild/reload the extension and start a fresh agent task.`);
4003
+ const runtime = tool.name === "apply_canvas" ? buildAuthoringRuntimeEvidence(activeExt) : void 0;
4004
+ 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.");
4005
+ designTasks.checkOperation(ownerId, session, taskId, tool.name === "apply_canvas");
4006
+ const registration = register(activeExt.id, timeoutMs, { waitForDefinitiveResult: tool.name === "apply_canvas" });
2075
4007
  requestId = registration.requestId;
2076
4008
  const message = {
2077
4009
  type: "toolCall",
2078
4010
  id: registration.requestId,
4011
+ route: {
4012
+ gatewayId: activeExt.id,
4013
+ sessionId: session.sessionId,
4014
+ fileKey: session.fileKey,
4015
+ ...taskId ? {
4016
+ taskId,
4017
+ epoch: taskEpoch ?? 0
4018
+ } : {}
4019
+ },
2079
4020
  payload: {
2080
4021
  name: tool.name,
2081
4022
  args: parsedArgs
2082
4023
  }
2083
4024
  };
2084
- activeExt.ws.send(JSON.stringify(message));
4025
+ try {
4026
+ designTasks.startOperation(requestId, ownerId, activeExt.id, activeExt.sessions.browserId, session, taskId, tool.name === "apply_canvas");
4027
+ activeExt.ws.send(JSON.stringify(message));
4028
+ } catch (error) {
4029
+ designTasks.finishOperation(requestId, activeExt.id);
4030
+ reject(requestId, activeExt.id, coerceToolError(error));
4031
+ }
2085
4032
  log.info({
2086
4033
  tool: tool.name,
2087
4034
  req: registration.requestId,
2088
4035
  extId: activeExt.id
2089
4036
  }, "Forwarded tool call.");
2090
4037
  const payload = await registration.promise;
2091
- return createToolResponse(tool.name, payload);
4038
+ if (taskId && ["get_structure", "get_code"].includes(tool.name)) designTasks.acknowledgeRead(taskId, ownerId, taskEpoch);
4039
+ if (taskId && tool.name === "apply_canvas") {
4040
+ const rootNodeId = getRecordProperty(payload, "rootNodeId");
4041
+ if (typeof rootNodeId === "string") designTasks.captureResult(taskId, rootNodeId, getRecordProperty(payload, "rootRemoved") === true);
4042
+ const page = getRecordProperty(payload, "page");
4043
+ if (getRecordProperty(page, "active") === true) {
4044
+ const pageId = getRecordProperty(page, "id");
4045
+ if (typeof pageId === "string") designTasks.updatePage(taskId, pageId);
4046
+ }
4047
+ }
4048
+ return createToolResponse(tool.name, payload, runtime);
2092
4049
  } catch (error) {
2093
4050
  const normalized = coerceToolError(error);
2094
4051
  log.error({
@@ -2101,23 +4058,36 @@ function registerProxiedTool(mcp, tool) {
2101
4058
  }
2102
4059
  };
2103
4060
  registerToolFn(tool.name, {
4061
+ annotations: tool.annotations,
2104
4062
  description: tool.description,
2105
4063
  inputSchema: schema
2106
4064
  }, handler);
2107
4065
  }
2108
- function registerLocalTool(mcp, tool) {
4066
+ function registerLocalTool(mcp, tool, ownerId) {
2109
4067
  const schema = tool.parameters;
2110
4068
  const handler = tool.handler;
2111
4069
  const registerToolFn = mcp.registerTool.bind(mcp);
2112
4070
  const registrationOptions = {
4071
+ annotations: tool.annotations,
2113
4072
  description: tool.description,
2114
4073
  inputSchema: schema
2115
4074
  };
2116
4075
  if (tool.outputSchema) registrationOptions.outputSchema = tool.outputSchema;
2117
- const registerHandler = async (args) => {
4076
+ const connectionId = ownerId;
4077
+ const registerHandler = async (args, extra) => {
4078
+ const ownerId = await agentClients.owner(connectionId, extra._meta, mcp.server.getClientVersion());
2118
4079
  try {
2119
4080
  const parsed = schema.parse(args);
2120
- return await handler(parsed);
4081
+ const taskId = getRecordProperty(parsed, "taskId");
4082
+ if (![
4083
+ "end_design",
4084
+ "resume_design",
4085
+ "get_design_task"
4086
+ ].includes(tool.name) && typeof taskId === "string") {
4087
+ designTasks.assertEpoch(taskId, ownerId, getRecordProperty(parsed, "taskEpoch"));
4088
+ designTasks.touch(taskId, ownerId);
4089
+ }
4090
+ return await handler(parsed, ownerId);
2121
4091
  } catch (error) {
2122
4092
  log.error({
2123
4093
  tool: tool.name,
@@ -2128,21 +4098,41 @@ function registerLocalTool(mcp, tool) {
2128
4098
  };
2129
4099
  registerToolFn(tool.name, registrationOptions, registerHandler);
2130
4100
  }
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);
4101
+ function createToolResponse(toolName, payload, runtime) {
4102
+ const enrichedPayload = (() => {
4103
+ if (toolName === "get_screenshot") {
4104
+ const screenshot = payload;
4105
+ return {
4106
+ ...screenshot,
4107
+ asset: addLocalAssetPath(screenshot.asset)
4108
+ };
4109
+ }
4110
+ if (toolName === "get_code") {
4111
+ const code = payload;
4112
+ return code.assets ? {
4113
+ ...code,
4114
+ assets: code.assets.map((asset) => addLocalAssetPath(asset))
4115
+ } : code;
2143
4116
  }
2144
- return coercePayloadToToolResponse(payload);
4117
+ if (toolName === "apply_canvas" && runtime) return {
4118
+ ...payload,
4119
+ runtime
4120
+ };
4121
+ return payload;
2145
4122
  })();
4123
+ let rawResult;
4124
+ const definition = getToolDefinition(toolName);
4125
+ if (definition && hasFormatter(definition)) try {
4126
+ const formatter = definition.format;
4127
+ rawResult = formatter(enrichedPayload);
4128
+ } catch (error) {
4129
+ log.warn({
4130
+ tool: toolName,
4131
+ error
4132
+ }, "Failed to format tool result; returning raw payload.");
4133
+ rawResult = coercePayloadToToolResponse(enrichedPayload);
4134
+ }
4135
+ else rawResult = coercePayloadToToolResponse(enrichedPayload);
2146
4136
  const resultBytes = measureCallToolResultBytes(rawResult);
2147
4137
  if (resultBytes > 65536) {
2148
4138
  log.warn({
@@ -2154,6 +4144,34 @@ function createToolResponse(toolName, payload) {
2154
4144
  }
2155
4145
  return rawResult;
2156
4146
  }
4147
+ function buildAuthoringRuntimeEvidence(extension) {
4148
+ const runtime = extension.runtime;
4149
+ const issues = getExtensionRuntimeIssues(runtime);
4150
+ if (!hubRuntimeIdentity) issues.unshift("Hub runtime identity is unavailable");
4151
+ return {
4152
+ protocolVersion: 13,
4153
+ locked: false,
4154
+ valid: issues.length === 0,
4155
+ issues,
4156
+ hub: {
4157
+ packageVersion: hubRuntimeIdentity?.packageVersion ?? PACKAGE_VERSION,
4158
+ runtimeFingerprint: hubRuntimeIdentity?.runtimeFingerprint ?? "0".repeat(64),
4159
+ startedAt: hubRuntimeIdentity?.startedAt ?? (/* @__PURE__ */ new Date(0)).toISOString()
4160
+ },
4161
+ extension: {
4162
+ version: runtime?.version ?? "<missing>",
4163
+ runtimeFingerprint: runtime?.fingerprint ?? "0".repeat(64),
4164
+ connectedAt: extension.connectedAt
4165
+ }
4166
+ };
4167
+ }
4168
+ function addLocalAssetPath(asset) {
4169
+ const record = assetStore.get(asset.hash);
4170
+ return record && existsSync(record.filePath) ? {
4171
+ ...asset,
4172
+ localPath: record.filePath
4173
+ } : asset;
4174
+ }
2157
4175
  async function handleGetAssets({ hashes }) {
2158
4176
  if (hashes.length > 100) throw new Error("Too many hashes requested. Limit is 100.");
2159
4177
  const unique = Array.from(new Set(hashes));
@@ -2168,6 +4186,27 @@ async function handleGetAssets({ hashes }) {
2168
4186
  missing: unique.filter((hash) => !found.has(hash))
2169
4187
  }));
2170
4188
  }
4189
+ async function handleUploadAsset({ dataUrl }) {
4190
+ const decoded = decodeImageDataUrl(dataUrl, maxAssetSizeBytes);
4191
+ const filename = buildAssetFilename(decoded.hash, decoded.mimeType);
4192
+ const response = await fetch(`${assetHttpServer.getBaseUrl()}/assets/${filename}`, {
4193
+ method: "POST",
4194
+ headers: {
4195
+ "Content-Length": String(decoded.bytes.length),
4196
+ "Content-Type": decoded.mimeType
4197
+ },
4198
+ body: new Uint8Array(decoded.bytes)
4199
+ });
4200
+ if (!response.ok) {
4201
+ const detail = (await response.text()).slice(0, 500);
4202
+ throw new Error(`Hub asset import failed (${response.status}): ${detail}`);
4203
+ }
4204
+ return createUploadAssetToolResponse({
4205
+ assetHash: decoded.hash,
4206
+ mimeType: decoded.mimeType,
4207
+ size: decoded.bytes.length
4208
+ });
4209
+ }
2171
4210
  function unrefTimer(timer) {
2172
4211
  if (typeof timer === "object" && timer !== null) {
2173
4212
  const handle = timer;
@@ -2175,21 +4214,41 @@ function unrefTimer(timer) {
2175
4214
  }
2176
4215
  }
2177
4216
  function broadcastState() {
4217
+ publishHubRuntimeIdentity();
2178
4218
  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)));
4219
+ for (const extension of extensionRegistry.list()) {
4220
+ const message = {
4221
+ type: "state",
4222
+ activeId,
4223
+ assetServerUrl: assetHttpServer.getBaseUrl(extension.legacy)
4224
+ };
4225
+ extension.ws.send(JSON.stringify(message));
4226
+ }
2185
4227
  log.debug({
2186
4228
  activeId,
2187
4229
  count: extensionRegistry.size
2188
4230
  }, "Broadcasted state.");
2189
4231
  }
4232
+ function publishHubRuntimeIdentity() {
4233
+ if (!hubRuntimeIdentity) return;
4234
+ const activeExtension = extensionRegistry.getActive();
4235
+ hubRuntimeIdentity = {
4236
+ ...hubRuntimeIdentity,
4237
+ activeExtension: activeExtension ? {
4238
+ id: activeExtension.id,
4239
+ connectedAt: activeExtension.connectedAt,
4240
+ version: activeExtension.runtime?.version ?? null,
4241
+ fingerprint: activeExtension.runtime?.fingerprint ?? null
4242
+ } : null
4243
+ };
4244
+ writeHubRuntimeIdentity(HUB_RUNTIME_IDENTITY_PATH, hubRuntimeIdentity);
4245
+ }
2190
4246
  function shutdown() {
2191
4247
  if (shuttingDown) return;
2192
4248
  shuttingDown = true;
4249
+ clearInterval(designTaskTimer);
4250
+ clearInterval(clientCapabilityTimer);
4251
+ agentClients.close();
2193
4252
  log.info("Hub is shutting down...");
2194
4253
  consumerSessions.forEach((session) => {
2195
4254
  session.close().catch((err) => {
@@ -2203,6 +4262,7 @@ function shutdown() {
2203
4262
  netServer.close(() => log.info("Net server closed."));
2204
4263
  wss?.close(() => log.info("WebSocket server closed."));
2205
4264
  cleanupAll();
4265
+ removeHubRuntimeIdentityIfOwned(HUB_RUNTIME_IDENTITY_PATH, process.pid);
2206
4266
  releaseHubLockIfNeeded();
2207
4267
  unrefTimer(setTimeout(() => {
2208
4268
  log.warn("Shutdown timed out. Forcing exit.");
@@ -2210,7 +4270,8 @@ function shutdown() {
2210
4270
  }, SHUTDOWN_TIMEOUT));
2211
4271
  }
2212
4272
  const netServer = createServer((sock) => {
2213
- const mcp = createMcpServer();
4273
+ const ownerId = randomUUID();
4274
+ const mcp = createMcpServer(ownerId);
2214
4275
  consumerSessions.add(mcp);
2215
4276
  consumerCount++;
2216
4277
  log.info(`Consumer connected. Total: ${consumerCount}`);
@@ -2227,6 +4288,7 @@ const netServer = createServer((sock) => {
2227
4288
  transport.close().catch((closeErr) => log.warn({ err: closeErr }, "Transport close failed."));
2228
4289
  });
2229
4290
  sock.on("close", async () => {
4291
+ agentClients.disconnect(ownerId);
2230
4292
  await transport.close().catch((closeErr) => log.warn({ err: closeErr }, "Transport close failed."));
2231
4293
  await mcp.close().catch((closeErr) => log.warn({ err: closeErr }, "MCP session close failed."));
2232
4294
  consumerSessions.delete(mcp);
@@ -2242,7 +4304,10 @@ async function initializeHubRuntime() {
2242
4304
  ensureDir(RUNTIME_DIR);
2243
4305
  if (await probeSocketPath() === "live") await exitExistingHub();
2244
4306
  releaseHubLock = await acquireHubLock();
4307
+ designTasks.restore();
2245
4308
  await cleanSocketPath();
4309
+ hubRuntimeIdentity = createHubRuntimeIdentity(fileURLToPath(import.meta.url), PACKAGE_VERSION);
4310
+ writeHubRuntimeIdentity(HUB_RUNTIME_IDENTITY_PATH, hubRuntimeIdentity);
2246
4311
  await assetHttpServer.start();
2247
4312
  scheduleAssetCleanup();
2248
4313
  }
@@ -2308,6 +4373,7 @@ async function startHubRuntime() {
2308
4373
  async function abortStartup(error) {
2309
4374
  log.error({ err: error }, "Failed to initialize Hub runtime.");
2310
4375
  assetHttpServer.stop();
4376
+ removeHubRuntimeIdentityIfOwned(HUB_RUNTIME_IDENTITY_PATH, process.pid);
2311
4377
  await releaseHubLockIfNeeded();
2312
4378
  process.exit(1);
2313
4379
  }
@@ -2338,6 +4404,7 @@ activeWss.on("connection", (ws, request) => {
2338
4404
  },
2339
4405
  onDisconnected: (extensionId, wasActive) => {
2340
4406
  log.info({ id: extensionId }, `Extension disconnected. Remaining: ${extensionRegistry.size}`);
4407
+ designTasks.disconnectExtension(extensionId);
2341
4408
  cleanupForExtension(extensionId);
2342
4409
  if (wasActive) log.warn({ id: extensionId }, "Active extension disconnected.");
2343
4410
  },
@@ -2352,6 +4419,76 @@ activeWss.on("connection", (ws, request) => {
2352
4419
  extId: warning.extensionId
2353
4420
  }, "Invalid message shape.");
2354
4421
  },
4422
+ onRuntimeHello: (extension) => {
4423
+ publishHubRuntimeIdentity();
4424
+ log.info({
4425
+ extId: extension.id,
4426
+ extensionVersion: extension.runtime?.version,
4427
+ extensionRuntimeFingerprint: extension.runtime?.fingerprint
4428
+ }, "Extension runtime identity received.");
4429
+ },
4430
+ onSessions: (extension) => {
4431
+ const snapshot = extension.sessions;
4432
+ for (const review of snapshot.reviews ?? []) {
4433
+ const session = snapshot.sessions.find((value) => value.sessionId === review.sessionId);
4434
+ if (!session) continue;
4435
+ designTasks.restoreReview(review.task, extension, session);
4436
+ if (review.task.reviewClosed || review.task.status === "cancelled") agentClients.cancelFeedback(review.task.taskId, true).catch(() => {});
4437
+ }
4438
+ designTasks.reconcileSessions(snapshot.browserId, snapshot.sessions, snapshot.openTabIds);
4439
+ for (const record of designTasks.list()) {
4440
+ if (designTasks.current(record.task.target.fileKey) === record && snapshot.sessions.some((session) => session.fileKey === record.task.target.fileKey)) extension.ws.send(JSON.stringify({
4441
+ type: "designTaskState",
4442
+ task: record.task
4443
+ }));
4444
+ if (record.extensionId === extension.id && !snapshot.sessions.some((session) => session.sessionId === record.task.target.sessionId)) designTasks.stop(record.task.taskId, "interrupted");
4445
+ }
4446
+ for (const { record, extension: target, session } of designTasks.recoverSessions(extensionRegistry.list())) {
4447
+ const taskId = record.task.taskId;
4448
+ const binding = bindDesignTask(record, target, session);
4449
+ pendingDesignBindings.set(taskId, binding);
4450
+ binding.catch((error) => log.warn({
4451
+ error,
4452
+ taskId
4453
+ }, "Failed to restore a refreshed Figma tab.")).finally(() => {
4454
+ if (pendingDesignBindings.get(taskId) === binding) pendingDesignBindings.delete(taskId);
4455
+ });
4456
+ }
4457
+ },
4458
+ onDesignAction: (extension, sessionId, action) => {
4459
+ const session = extension.sessions?.sessions.find((value) => value.sessionId === sessionId);
4460
+ const record = designTasks.find(action.taskId);
4461
+ const reply = (result) => {
4462
+ try {
4463
+ extension.ws.send(JSON.stringify({
4464
+ type: "designActionResult",
4465
+ sessionId,
4466
+ result
4467
+ }));
4468
+ } catch {}
4469
+ };
4470
+ if (!session || record?.task.target.fileKey !== session.fileKey || ["feedback", "steer"].includes(action.action) && record.task.target.sessionId !== sessionId) {
4471
+ reply({
4472
+ requestId: action.requestId,
4473
+ taskId: action.taskId,
4474
+ status: "failed",
4475
+ message: "This action belongs to another Figma file."
4476
+ });
4477
+ return;
4478
+ }
4479
+ const accepted = () => reply({
4480
+ requestId: action.requestId,
4481
+ taskId: action.taskId,
4482
+ status: "accepted",
4483
+ message: action.action === "stop" ? "Stopping design task…" : "Sending feedback…"
4484
+ });
4485
+ agentClients.action(action, accepted).then(reply).catch((error) => reply({
4486
+ requestId: action.requestId,
4487
+ taskId: action.taskId,
4488
+ status: "failed",
4489
+ message: String(error).slice(0, 500)
4490
+ }));
4491
+ },
2355
4492
  onSocketError: (extensionId, error) => {
2356
4493
  log.warn({
2357
4494
  err: error,
@@ -2360,6 +4497,8 @@ activeWss.on("connection", (ws, request) => {
2360
4497
  },
2361
4498
  onStateChange: broadcastState,
2362
4499
  onToolError: (requestId, extensionId, error) => {
4500
+ if (error.code === TEMPAD_MCP_ERROR_CODES.EXTENSION_DISCONNECTED) designTasks.uncertain(requestId, extensionId);
4501
+ else designTasks.finishOperation(requestId, extensionId);
2363
4502
  const normalized = coerceToolError(error);
2364
4503
  log.warn({
2365
4504
  toolReq: requestId,
@@ -2370,7 +4509,8 @@ activeWss.on("connection", (ws, request) => {
2370
4509
  reject(requestId, extensionId, normalized);
2371
4510
  },
2372
4511
  onToolResult: (requestId, extensionId, payload) => {
2373
- resolve(requestId, extensionId, payload);
4512
+ designTasks.finishOperation(requestId, extensionId);
4513
+ resolve$1(requestId, extensionId, payload);
2374
4514
  }
2375
4515
  });
2376
4516
  });